Files

4494 lines
183 KiB
TypeScript

import type {
Event as OpenCodeEvent,
Message as OpenCodeMessage,
Part as OpenCodePart,
PermissionRequest,
PermissionRuleset,
QuestionRequest,
Session as OpenCodeSession,
Todo as OpenCodeTodo,
ToolPart,
} from "@opencode-ai/sdk/v2";
import * as HostProcess from "@hanzodev/shared/HostProcess";
import { getModelSelectionStringOptionValue } from "@hanzodev/shared/model";
import { causeErrorTag } from "@hanzodev/shared/observability";
import {
defaultInstanceIdForDriver,
type ModelSelection,
type OrchestrationV2AppThread,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2PlanStep,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRef,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
type PlanId,
ProviderDriverKind,
type ProviderInstanceId,
type ProviderRequestKind,
type ProviderSessionId,
type RuntimeRequestId,
type ThreadId,
settingsSecretLiteral,
} from "@hanzodev/contracts";
import { OpenCodeSettings } from "../settings.ts";
import * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as ProviderHost from "@hanzodev/provider-core/server/ProviderHost";
import { mcpToolPresentation } from "@hanzodev/provider-core/server/mcpToolPresentation";
import * as McpProviderSessions from "@hanzodev/provider-core/server/McpProviderSessions";
import * as ProviderEventLoggers from "@hanzodev/provider-core/server/ProviderEventLoggers";
import {
structuralProtocolMethod,
summarizeNativeProtocolPayload,
} from "@hanzodev/provider-core/server/nativeProtocolLogging";
import { mergeProviderInstanceEnvironment } from "@hanzodev/provider-core/server/instanceEnvironment";
import { hanzoOrchestrationSystemPrompt } from "@hanzodev/provider-core/server/orchestrationInstructions";
import { buildRuntimeInstructions } from "@hanzodev/provider-core/server/runtimeInstructions";
import * as OpenCodeRuntime from "./OpenCodeRuntime.ts";
import { readableProviderErrorMessage } from "./providerErrorMessage.ts";
import * as IdAllocator from "@hanzodev/provider-core/server/IdAllocator";
import * as ProviderContinuationRequests from "@hanzodev/provider-core/server/ProviderContinuationRequests";
import { makeProviderFailure } from "@hanzodev/provider-core/server/failure";
import { turnScopedSelectionTransition } from "@hanzodev/provider-core/server/selectionTransition";
import { providerMessageTextWithAttachmentPaths } from "@hanzodev/provider-core/server/attachmentPrompt";
import * as ProviderAdapter from "@hanzodev/provider-core/server/ProviderAdapter";
import {
ProviderAdapterDriverCreateError,
type ProviderAdapterDriver,
type ProviderAdapterDriverCreateInput,
} from "@hanzodev/provider-core/server/adapterDriver";
import {
makeSubagentChildThread,
subagentThreadTitle,
} from "@hanzodev/provider-core/server/subagentProjection";
import { openCodeCommandFailed, openCodeToolOutput, openCodeToolTurnItem } from "./toolItems.ts";
export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode");
export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_PROVIDER);
export const OPENCODE_SDK_PROTOCOL = "opencode-sdk.sse" as const;
const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({});
const OPENCODE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
const makeOpenCodeMessageId = Effect.fnUntraced(function* (
clock: Ref.Ref<{ readonly epochMillis: number; readonly counter: number }>,
) {
const epochMillis = DateTime.toEpochMillis(yield* DateTime.now);
const counter = yield* Ref.modify(clock, (previous) => {
const next = previous.epochMillis === epochMillis ? previous.counter + 1 : 1;
return [next, { epochMillis, counter: next }] as const;
});
const encodedTime = BigInt.asUintN(48, BigInt(epochMillis) * 0x1000n + BigInt(counter))
.toString(16)
.padStart(12, "0");
const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const random = (yield* Effect.forEach(Array.from({ length: 28 }), () =>
Random.nextIntBetween(0, alphabet.length - 1),
))
.map((index) => alphabet[index])
.join("");
return `msg_${encodedTime}${random}`;
});
// OpenCode has no turn object; correlate by initiating user message and settle on session idle.
const OpenCodeProviderCapabilitiesV2 = {
sessions: {
// The directory-bound client/server is not safe for cross-thread pooling.
supportsMultipleProviderThreadsPerSession: false,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: false,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: true,
exposesNativeThreadId: true,
},
turns: {
exposesNativeTurnId: false,
emitsTurnStarted: true,
emitsTurnCompleted: true,
supportsInterrupt: true,
supportsActiveSteering: true,
supportsSteeringByInterruptRestart: true,
supportsQueuedMessages: true,
terminalStatusQuality: "strong",
},
streaming: {
streamsAssistantText: true,
streamsReasoning: true,
streamsToolOutput: true,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: true,
supportsDynamicToolCallbacks: false,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: true,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: true,
},
planning: {
emitsPlanUpdated: true,
emitsTodoList: true,
emitsProposedPlan: false,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: true,
emitsSubagentLifecycle: true,
canWaitForSubagents: true,
canCloseSubagents: false,
canForkSubagentThread: true,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: true,
canGenerateSummaries: true,
canConsumeHandoffSummaries: true,
supportsDeltaHandoff: true,
supportsFullThreadHandoff: true,
maxRecommendedHandoffChars: null,
},
checkpointing: {
appCanCheckpointFilesystem: true,
supportsNestedCheckpointScopes: true,
providerCanRollbackConversation: true,
providerRollbackReturnsSnapshot: true,
providerCanReadConversationSnapshot: true,
},
identity: {
nativeThreadIds: "strong",
nativeTurnIds: "weak",
nativeItemIds: "strong",
nativeRequestIds: "strong",
},
runtimePolicy: {
enforcement: "native",
},
} satisfies OrchestrationV2ProviderCapabilities;
type TerminalTurnStatus = Extract<
OrchestrationV2ProviderTurn["status"],
"completed" | "interrupted" | "failed" | "cancelled"
>;
type OpenCodeStepUsage = Pick<
Extract<OpenCodePart, { readonly type: "step-finish" }>,
"id" | "tokens"
>;
interface OpenCodeTurnTokenUsageAccumulator {
readonly partIds: Set<string>;
readonly promptMessageIds: Set<string>;
readonly assistantOwnershipByMessageId: Map<string, "owned" | "other" | "unknown">;
readonly unresolvedStepsByMessageId: Map<string, Map<string, OpenCodeStepUsage>>;
inputTokens: number;
cachedInputTokens: number;
cacheCreationTokens: number;
outputTokens: number;
reasoningTokens: number;
hasSubagents: boolean;
complete: boolean;
lastStep: OpenCodeStepUsage | null;
}
function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumulator {
return {
partIds: new Set(),
promptMessageIds: new Set(),
assistantOwnershipByMessageId: new Map(),
unresolvedStepsByMessageId: new Map(),
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningTokens: 0,
hasSubagents: false,
complete: true,
lastStep: null,
};
}
function accumulateOpenCodeStepUsage(
accumulator: OpenCodeTurnTokenUsageAccumulator,
part: OpenCodeStepUsage,
): void {
if (accumulator.partIds.has(part.id)) return;
accumulator.partIds.add(part.id);
accumulator.inputTokens += part.tokens.input + part.tokens.cache.read + part.tokens.cache.write;
accumulator.cachedInputTokens += part.tokens.cache.read;
accumulator.cacheCreationTokens += part.tokens.cache.write;
accumulator.outputTokens += part.tokens.output + part.tokens.reasoning;
accumulator.reasoningTokens += part.tokens.reasoning;
accumulator.lastStep = part;
}
// The last step's prompt plus output is the context the next request starts from.
function openCodeContextUsage(
lastStep: OpenCodeStepUsage | null,
contextWindow: number | undefined,
completedAt: DateTime.Utc,
): Pick<OrchestrationV2ProviderTurn, "tokenUsage"> {
if (lastStep === null) return {};
const { tokens } = lastStep;
const inputTokens = tokens.input + tokens.cache.read + tokens.cache.write;
return {
tokenUsage: {
usedTokens: inputTokens + tokens.output,
maxTokens: contextWindow ?? null,
inputTokens,
cachedInputTokens: tokens.cache.read,
outputTokens: tokens.output,
reasoningOutputTokens: tokens.reasoning,
updatedAt: DateTime.formatIso(completedAt),
},
};
}
interface ActiveOpenCodeTurn {
readonly usage: OpenCodeTurnTokenUsageAccumulator;
readonly isRoot: boolean;
readonly threadId: ThreadId;
readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null;
readonly rootNodeId: ProviderAdapter.ProviderAdapterV2TurnInput["rootNodeId"];
readonly appThread: OrchestrationV2AppThread;
readonly modelSelection: ModelSelection;
readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy;
readonly providerTurnId: OrchestrationV2ProviderTurn["id"];
readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"];
readonly runOrdinal: number;
readonly startedAt: DateTime.Utc;
readonly itemOrdinals: Map<string, number>;
readonly parts: Map<string, Exclude<OpenCodePart, ToolPart>>;
readonly partIdsByMessage: Map<string, Set<string>>;
readonly toolNamesByCallId: Map<string, string>;
mcpServerNames?: ReadonlyArray<string>;
readonly providerTurn: OrchestrationV2ProviderTurn;
nextItemOrdinal: number;
nativeUserMessageId: string | null;
admissionMessageId: string | null;
readonly priorWakePromptIds: Set<string>;
priorWakeSettled: Deferred.Deferred<void> | null;
interrupted: boolean;
finalized: boolean;
contextOverflow: OrchestrationV2ProviderFailure | null;
planId: PlanId | null;
admissionGeneration: number;
admissionReconciliationGeneration: number | null;
admissionPending: boolean;
admissionAccepted: boolean;
admissionMessageObserved: boolean;
idleDuringAdmission: boolean;
admissionUncertain: boolean;
admissionStatusSequence: number;
admissionSettled: Deferred.Deferred<void>;
admissionAbortController: AbortController | null;
}
type OpenCodeAdmissionSignal =
| "accepted"
| "assistant-completed"
| "busy"
| "idle"
| "user-message";
type OpenCodeAdmissionAction = "hold" | "reconcile-idle" | "release";
export function advanceOpenCodePromptAdmission(
admission: Pick<
ActiveOpenCodeTurn,
"admissionAccepted" | "admissionMessageObserved" | "admissionPending" | "idleDuringAdmission"
>,
signal: OpenCodeAdmissionSignal,
): OpenCodeAdmissionAction {
if (!admission.admissionPending) return "release";
if (signal === "assistant-completed") {
admission.admissionAccepted = true;
admission.admissionMessageObserved = true;
admission.admissionPending = false;
return "release";
}
if (signal === "idle") {
admission.idleDuringAdmission = true;
return "hold";
}
if (signal === "accepted") admission.admissionAccepted = true;
if (signal === "busy" || signal === "user-message") admission.admissionMessageObserved = true;
if (!admission.admissionAccepted || !admission.admissionMessageObserved) return "hold";
if (admission.idleDuringAdmission) return "reconcile-idle";
admission.admissionPending = false;
return "release";
}
export function cancelOpenCodePromptAdmission(
admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">,
nextGeneration: number,
): void {
admission.admissionGeneration = nextGeneration;
admission.admissionPending = false;
}
export const reconcileOpenCodePromptAdmissionStatus = Effect.fn(
"reconcileOpenCodePromptAdmissionStatus",
)(function* (
admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">,
generation: number,
readStatus: Effect.Effect<"busy" | "idle" | "unknown">,
) {
if (admission.admissionGeneration !== generation || !admission.admissionPending) {
return "stale" as const;
}
const status = yield* readStatus.pipe(
Effect.timeoutOption("10 seconds"),
Effect.map(Option.getOrElse(() => "unknown" as const)),
);
if (admission.admissionGeneration !== generation || !admission.admissionPending) {
return "stale" as const;
}
if (status !== "unknown") admission.admissionPending = false;
return status;
});
interface OpenCodeSubagentContext {
readonly nativeItemId: string;
readonly nodeId: OrchestrationV2Subagent["id"];
readonly parentState: OpenCodeThreadState;
readonly parentTurn: ActiveOpenCodeTurn;
readonly prompt: string;
readonly title: string | null;
readonly startedAt: DateTime.Utc;
childSessionId: string | null;
childThreadId: ThreadId | null;
childProviderThreadId: OrchestrationV2ProviderThread["id"] | null;
model: string | null;
result: string | null;
// A background task call returns at launch; held here until its child session stops.
launch: ToolPart | null;
}
/** Root work OpenCode began with no Hanzo turn, such as a background task's result; held until a run admits it. */
interface OpenCodeWake {
readonly events: Array<OpenCodeEvent>;
// A user message alone can be a late update; only a busy root is work worth a run.
offered: boolean;
cancelling: boolean;
readonly admission: Deferred.Deferred<boolean>;
settled: Deferred.Deferred<void>;
}
interface OpenCodeThreadState {
readonly nativeSessionId: string;
providerThread: OrchestrationV2ProviderThread;
appThread: OrchestrationV2AppThread | null;
activeTurn: ActiveOpenCodeTurn | null;
readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
readonly runtimeRequests: Map<string, OrchestrationV2RuntimeRequest>;
readonly messageRoles: Map<string, "user" | "assistant">;
readonly userMessageIds: Array<string>;
parentSubagent: OpenCodeSubagentContext | null;
// null: a child resumed after a restart, whose next ordinal is recovered from OpenCode.
nextChildTurnOrdinal: number | null;
nextAdmissionGeneration: number;
wake: OpenCodeWake | null;
readonly lifecyclePermit: Semaphore.Semaphore;
permission: PermissionRuleset;
/** Parent rules last written into this child's `permission`; empty for root sessions. */
inheritedPermission: PermissionRuleset;
}
interface OpenCodeRequestOwner {
readonly state: OpenCodeThreadState;
readonly turn: ActiveOpenCodeTurn;
readonly subagent: OpenCodeSubagentContext | null;
}
function topLevelRequestOwner(state: OpenCodeThreadState): OpenCodeRequestOwner | undefined {
let owner = state;
let subagent: OpenCodeSubagentContext | null = null;
while (owner.parentSubagent !== null) {
subagent = owner.parentSubagent;
owner = subagent.parentState;
}
return owner.activeTurn === null ? undefined : { state: owner, turn: owner.activeTurn, subagent };
}
interface PendingOpenCodeRequest {
readonly requestId: RuntimeRequestId;
readonly nativeRequestId: string;
readonly nativeSessionId: string;
readonly turn: ActiveOpenCodeTurn;
readonly state: OpenCodeThreadState;
readonly nodeId: OrchestrationV2ExecutionNode["id"];
readonly parentNodeId: OrchestrationV2ExecutionNode["id"];
readonly turnItemId: OrchestrationV2TurnItem["id"];
readonly requestKind: OpenCodePermissionRequestKind | "user_input";
readonly createdAt: DateTime.Utc;
readonly permission?: PermissionRequest;
readonly question?: QuestionRequest;
}
export interface OpenCodeAdapterV2Options {
readonly instanceId: ProviderInstanceId;
readonly settings: OpenCodeSettings;
readonly environment: NodeJS.ProcessEnv;
readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger;
}
export interface OpenCodeProtocolLogEvent {
readonly direction: "incoming" | "outgoing";
readonly messageKind: "request" | "response" | "notification" | "error";
readonly method: string;
readonly payload: unknown;
}
function formatOpenCodeProtocolLogPayload(event: OpenCodeProtocolLogEvent) {
return {
direction: event.direction,
messageKind: event.messageKind,
method: structuralProtocolMethod(event.method),
payload: summarizeNativeProtocolPayload(event.payload),
};
}
export function makeOpenCodeProtocolLogger(input: {
readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined;
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly providerInstanceId: ProviderInstanceId;
readonly providerSessionId: ProviderSessionId;
readonly threadId: ThreadId;
}): (event: OpenCodeProtocolLogEvent) => Effect.Effect<void, never> {
return (event) =>
Effect.gen(function* () {
// Per-token deltas; the part's final message.part.updated is still logged.
if (!input.nativeEventLogger || event.method === "message.part.delta") return;
const observedAt = DateTime.formatIso(yield* DateTime.now);
const method = structuralProtocolMethod(event.method);
yield* input.nativeEventLogger.write(
{
observedAt,
event: {
id: yield* input.idAllocator.allocate.rawEvent({
providerSessionId: input.providerSessionId,
method,
}),
kind: "protocol",
protocol: OPENCODE_SDK_PROTOCOL,
provider: OPENCODE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
createdAt: observedAt,
threadId: input.threadId,
payload: formatOpenCodeProtocolLogPayload(event),
},
},
input.threadId,
);
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.interrupt
: Effect.logWarning("Failed to write native OpenCode event log.", {
errorTag: causeErrorTag(cause),
reasonCount: cause.reasons.length,
provider: OPENCODE_PROVIDER,
threadId: input.threadId,
}),
),
);
}
function protocolError(
detail: string,
payload?: unknown,
): ProviderAdapter.ProviderAdapterProtocolError {
return new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail,
...(payload === undefined ? {} : { payload }),
});
}
function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string {
const nativeId = providerThread.nativeThreadRef?.nativeId;
if (nativeId === null || nativeId === undefined) {
throw protocolError(`Provider thread ${providerThread.id} has no OpenCode session id`);
}
return nativeId;
}
function dateTimeFromEpoch(value: number | undefined, fallback: DateTime.Utc): DateTime.Utc {
if (value === undefined) return fallback;
return Option.getOrElse(DateTime.make(value), () => fallback);
}
function nonEmptyString(value: unknown): string | undefined {
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
}
function recordValue(input: unknown, key: string): unknown {
return typeof input === "object" && input !== null && key in input
? (input as Record<string, unknown>)[key]
: undefined;
}
function recordString(input: unknown, ...keys: ReadonlyArray<string>): string | undefined {
for (const key of keys) {
const value = nonEmptyString(recordValue(input, key));
if (value !== undefined) return value;
}
return undefined;
}
function sdkResponseForRawLog(value: unknown): unknown {
if (typeof value !== "object" || value === null) return value;
if ("data" in value) return { data: (value as { readonly data?: unknown }).data ?? null };
if ("stream" in value) return { subscribed: true };
return value;
}
type OpenCodePermissionRequestKind = Extract<
ProviderRequestKind,
"command" | "file-read" | "file-change"
>;
export function openCodePermissionRequestKind(
permission: string,
toolName?: string,
): OpenCodePermissionRequestKind {
const normalized = permission.toLowerCase();
const normalizedTool = toolName?.toLowerCase() ?? "";
if (
normalized === "edit" ||
normalized === "write" ||
normalized === "patch" ||
normalized === "apply_patch" ||
normalizedTool === "edit" ||
normalizedTool === "write" ||
normalizedTool === "patch" ||
normalizedTool === "apply_patch"
) {
return "file-change";
}
if (
normalized === "read" ||
normalized === "glob" ||
normalized === "grep" ||
normalized === "lsp" ||
normalized === "external_directory" ||
normalizedTool === "read" ||
normalizedTool.includes("glob") ||
normalizedTool.includes("grep") ||
normalizedTool.includes("search")
) {
return "file-read";
}
return "command";
}
const OPENCODE_ALWAYS_ALLOWED_PERMISSIONS = [
"question",
"read",
"glob",
"grep",
"lsp",
"todowrite",
"task",
"skill",
] as const;
const OPENCODE_RESTRICTED_PERMISSIONS = [
"bash",
"edit",
"webfetch",
"websearch",
"codesearch",
"external_directory",
"doom_loop",
] as const;
/** OpenCode has no OS sandbox; permission rules must enforce non-interactive policies too. */
export function openCodePermissionRules(
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
): PermissionRuleset {
const sandboxPolicy = recordValue(runtimePolicy, "sandboxPolicy");
const sandboxType = recordString(sandboxPolicy, "type");
const rawApprovalPolicy = runtimePolicy.approvalPolicy;
const approvalPolicy = nonEmptyString(rawApprovalPolicy);
const requiresApproval =
approvalPolicy === undefined
? (typeof rawApprovalPolicy === "object" && rawApprovalPolicy !== null) ||
runtimePolicy.runtimeMode !== "full-access"
: approvalPolicy !== "never";
const externallySandboxed = sandboxType === "externalSandbox";
const dangerFullAccess = sandboxType === "dangerFullAccess";
const implicitFullAccess =
sandboxType === undefined && runtimePolicy.runtimeMode === "full-access";
if (!requiresApproval && (externallySandboxed || dangerFullAccess || implicitFullAccess)) {
// Task children copy only external_directory and deny rules before their first tool call.
return [
{ permission: "*", pattern: "*", action: "allow" },
{ permission: "external_directory", pattern: "*", action: "allow" },
];
}
// Children initially inherit only denies; seed them before overrides to protect the policy-install gap.
const rules: PermissionRuleset = [
{ permission: "*", pattern: "*", action: "deny" },
...OPENCODE_RESTRICTED_PERMISSIONS.map((permission) => ({
permission,
pattern: "*",
action: "deny" as const,
})),
];
if (requiresApproval) {
rules.push({ permission: "*", pattern: "*", action: "ask" });
for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) {
rules.push({ permission, pattern: "*", action: "ask" });
}
}
rules.push(
...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({
permission,
pattern: "*",
action: "allow" as const,
})),
);
rules.push(
{ permission: "read", pattern: "*.env", action: requiresApproval ? "ask" : "deny" },
{ permission: "read", pattern: "*.env.*", action: requiresApproval ? "ask" : "deny" },
{ permission: "read", pattern: "*.env.example", action: "allow" },
);
if (
runtimePolicy.runtimeMode === "auto-accept-edits" ||
(!requiresApproval && sandboxType === "workspaceWrite")
) {
rules.push({ permission: "edit", pattern: "*", action: "allow" });
}
if (!requiresApproval && recordValue(sandboxPolicy, "networkAccess") === true) {
for (const permission of ["webfetch", "websearch", "codesearch"] as const) {
rules.push({ permission, pattern: "*", action: "allow" });
}
}
if (!requiresApproval && sandboxType === "readOnly") {
const access = recordValue(sandboxPolicy, "access");
if (recordString(access, "type") === "fullAccess") {
rules.push({ permission: "external_directory", pattern: "*", action: "allow" });
}
}
if (!requiresApproval && sandboxType === "workspaceWrite") {
const writableRoots = recordValue(sandboxPolicy, "writableRoots");
if (Array.isArray(writableRoots)) {
for (const root of writableRoots) {
if (typeof root === "string" && root.trim().length > 0) {
rules.push({
permission: "external_directory",
pattern: `${root.replace(/\/$/, "")}/*`,
action: "allow",
});
}
}
}
}
return rules;
}
function permissionRuleEquals(
left: PermissionRuleset[number],
right: PermissionRuleset[number],
): boolean {
return (
left.permission === right.permission &&
left.pattern === right.pattern &&
left.action === right.action
);
}
/**
* Children inherit only deny/external-directory rules; restore parent policy while retaining agent restrictions.
* `previousParentRules` are the parent rules already written into `childRules`.
*/
export function openCodeChildPermissionRules(
runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
childRules: PermissionRuleset,
previousParentRules: PermissionRuleset = [],
): PermissionRuleset {
const parentRules = openCodePermissionRules(runtimePolicy);
const inheritedRules = [
...parentRules.filter(
(rule) => rule.permission === "external_directory" || rule.action === "deny",
),
...previousParentRules,
];
const childSpecificRules = childRules.filter(
(childRule) =>
!inheritedRules.some((inheritedRule) => permissionRuleEquals(childRule, inheritedRule)),
);
return [...parentRules, ...childSpecificRules];
}
/** Boundaries are exclusive: use the next user message, or omit at head to retain the selected turn. */
export function openCodeBoundaryAfterProviderTurn(
providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
selectedProviderTurnId: OrchestrationV2ProviderTurn["id"],
): string | undefined {
const selected = providerTurns.find((turn) => turn.id === selectedProviderTurnId);
if (selected === undefined) return undefined;
return providerTurns
.filter((turn) => turn.ordinal > selected.ordinal)
.toSorted((left, right) => left.ordinal - right.ordinal)
.map((turn) => turn.nativeTurnRef?.nativeId)
.find((nativeId): nativeId is string => nativeId !== null && nativeId !== undefined);
}
function toolStatus(part: ToolPart): {
readonly node: OrchestrationV2ExecutionNode["status"];
readonly item: OrchestrationV2TurnItem["status"];
} {
switch (part.state.status) {
case "pending":
return { node: "pending", item: "pending" };
case "running":
return { node: "running", item: "running" };
case "completed":
return openCodeCommandFailed(part.tool, part.state.metadata)
? { node: "failed", item: "failed" }
: { node: "completed", item: "completed" };
case "error":
// Stop marks in-flight tools this way; OpenCode's own UI shows them as cancelled.
return part.state.metadata?.["interrupted"] === true ||
part.state.error === "Tool execution aborted" ||
(part.tool === "task" && part.state.error === "Task cancelled")
? { node: "interrupted", item: "interrupted" }
: { node: "failed", item: "failed" };
}
}
function toolInput(part: ToolPart): Record<string, unknown> {
return part.state.input;
}
function toolOutput(part: ToolPart): string | undefined {
if (part.state.status === "completed") return part.state.output;
if (part.state.status === "error") return part.state.error;
return undefined;
}
function toolStartedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc {
return dateTimeFromEpoch(
part.state.status === "pending" ? undefined : part.state.time.start,
now,
);
}
function toolCompletedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc | null {
return part.state.status === "completed" || part.state.status === "error"
? dateTimeFromEpoch(part.state.time.end, now)
: null;
}
function toolTitle(part: ToolPart): string | null {
return part.state.status === "running" || part.state.status === "completed"
? (part.state.title ?? null)
: null;
}
function toolModel(part: ToolPart): string | null {
const metadata =
part.state.status === "running" ||
part.state.status === "completed" ||
part.state.status === "error"
? part.state.metadata
: undefined;
const model = recordValue(metadata, "model");
const providerId = recordString(model, "providerID", "providerId");
const modelId = recordString(model, "modelID", "modelId", "id");
return providerId !== undefined && modelId !== undefined ? `${providerId}/${modelId}` : null;
}
function taskSessionId(part: ToolPart): string | null {
const metadata =
part.state.status === "running" ||
part.state.status === "completed" ||
part.state.status === "error"
? part.state.metadata
: undefined;
return recordString(metadata, "sessionId", "sessionID") ?? null;
}
function makeProviderThread(input: {
readonly idAllocator: IdAllocator.IdAllocatorV2["Service"];
readonly providerInstanceId: ProviderInstanceId;
readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"];
readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"];
readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"];
readonly nativeSession: OpenCodeSession;
readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"];
readonly now: DateTime.Utc;
}): OrchestrationV2ProviderThread {
const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now);
return {
id: input.idAllocator.derive.providerThread({
driver: OPENCODE_PROVIDER,
nativeThreadId: input.nativeSession.id,
}),
driver: OPENCODE_PROVIDER,
providerInstanceId: input.providerInstanceId,
providerSessionId: input.providerSessionId,
appThreadId: input.appThreadId,
ownerNodeId: input.ownerNodeId ?? null,
nativeThreadRef: {
driver: OPENCODE_PROVIDER,
nativeId: input.nativeSession.id,
strength: "strong",
},
nativeConversationHeadRef: null,
status: "idle",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: input.forkedFrom ?? null,
createdAt,
updatedAt: dateTimeFromEpoch(input.nativeSession.time.updated, input.now),
};
}
function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") {
return {
driver: OPENCODE_PROVIDER,
nativeId,
strength,
} satisfies OrchestrationV2ProviderRef;
}
function openCodeErrorMessage(event: Extract<OpenCodeEvent, { type: "session.error" }>): string {
const error = event.properties.error;
if (error === undefined) return "OpenCode session failed without an error payload.";
const statusCode = recordValue(error.data, "statusCode");
return (
readableProviderErrorMessage(
recordString(error.data, "message"),
typeof statusCode === "number" ? statusCode : undefined,
recordString(error.data, "responseBody"),
) ?? error.name
);
}
function terminalStatusForError(
event: Extract<OpenCodeEvent, { type: "session.error" }>,
turn: ActiveOpenCodeTurn,
): TerminalTurnStatus {
return turn.interrupted || isMessageAbortedError(event) ? "interrupted" : "failed";
}
// Events of one session's work; other events update adapter bookkeeping and are never held.
function sessionWorkEventSessionId(event: OpenCodeEvent): string | undefined {
switch (event.type) {
case "message.part.updated":
return event.properties.part.sessionID;
case "message.updated":
case "message.part.delta":
case "todo.updated":
case "session.compacted":
case "session.status":
case "session.idle":
case "session.error":
case "permission.asked":
case "question.asked":
return event.properties.sessionID;
default:
return undefined;
}
}
function isMessageAbortedError(event: Extract<OpenCodeEvent, { type: "session.error" }>): boolean {
return event.properties.error?.name === "MessageAbortedError";
}
// Node's fetch reports these when the connection failed before the request was sent.
const OPENCODE_UNSENT_REQUEST_CODES = new Set([
"ECONNREFUSED",
"ENOTFOUND",
"EAI_AGAIN",
"EHOSTUNREACH",
"ENETUNREACH",
"UND_ERR_CONNECT_TIMEOUT",
]);
// Only an HTTP error reply (the SDK puts its status on `cause`) or an unsent request
// proves OpenCode did not take a prompt; a reset or timeout after sending is ambiguous.
function isOpenCodePromptRejected(error: unknown): boolean {
const cause = OpenCodeRuntime.isOpenCodeRuntimeError(error) ? error.cause : error;
if (!(cause instanceof Error)) return false;
const reason = cause.cause as { readonly status?: unknown; readonly code?: unknown } | undefined;
return (
typeof reason?.status === "number" ||
(typeof reason?.code === "string" && OPENCODE_UNSENT_REQUEST_CODES.has(reason.code))
);
}
function isOpenCodeNotFound(cause: unknown): boolean {
const seen = new Set<unknown>();
const queue: Array<unknown> = [cause];
for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) {
const node = queue.shift();
if (node === null || typeof node !== "object" || seen.has(node)) {
continue;
}
seen.add(node);
const record = node as Record<string, unknown>;
const response = record.response;
const statuses = [
record.status,
record.statusCode,
response !== null && typeof response === "object"
? (response as { readonly status?: unknown }).status
: undefined,
].filter((status): status is number => typeof status === "number");
if (statuses.includes(404)) {
return true;
}
if (statuses.length > 0) {
continue;
}
const name = record.name;
if (typeof name === "string" && name.toLowerCase() === "notfounderror") {
return true;
}
for (const key of ["cause", "body", "error", "data"] as const) {
if (record[key] !== undefined) {
queue.push(record[key]);
}
}
}
return false;
}
function unwrapData<A>(operation: string, result: { readonly data?: A }): NonNullable<A> {
if (result.data === undefined) {
throw new OpenCodeRuntime.OpenCodeRuntimeError({
operation,
detail: `OpenCode ${operation} returned no response payload.`,
});
}
return result.data as NonNullable<A>;
}
export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function* (
options: OpenCodeAdapterV2Options,
) {
const runtime = yield* OpenCodeRuntime.OpenCodeRuntime;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const messageIdClock = yield* Ref.make({ epochMillis: -1, counter: 0 });
return ProviderAdapter.ProviderAdapterV2.of({
instanceId: options.instanceId,
driver: OPENCODE_PROVIDER,
getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () {
return Effect.succeed(OpenCodeProviderCapabilitiesV2);
}),
planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () {
return Effect.succeed(turnScopedSelectionTransition());
}),
openSession: Effect.fn("OpenCodeAdapterV2.openSession")(
function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) {
const scope = yield* Effect.scope;
const cwd = input.runtimePolicy.cwd ?? host.paths.cwd;
const connection = yield* runtime.connectToOpenCodeServer({
binaryPath: options.settings.binaryPath,
directory: cwd,
serverUrl: options.settings.serverUrl,
...(settingsSecretLiteral(options.settings.serverPassword)
? { serverPassword: settingsSecretLiteral(options.settings.serverPassword) }
: {}),
environment: options.environment,
});
const client = runtime.createOpenCodeSdkClient({
baseUrl: connection.url,
directory: cwd,
...(connection.serverPassword !== undefined
? { serverPassword: connection.serverPassword }
: {}),
});
const mcpSession = yield* mcpSessions.read(input.threadId);
const hasHanzoMcp = mcpSession !== undefined && !connection.external;
const orchestrationSystemPrompt = hanzoOrchestrationSystemPrompt(
hasHanzoMcp,
mcpSession?.capabilities?.has("device") === true,
);
if (hasHanzoMcp) {
yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () =>
client.mcp.add({
name: "hanzo-dev",
config: {
type: "remote",
url: mcpSession.endpoint,
headers: { Authorization: mcpSession.authorizationHeader },
oauth: false,
},
}),
);
}
const now = yield* DateTime.now;
let sessionEntity: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
status: "ready",
cwd,
model: input.modelSelection.model,
capabilities: OpenCodeProviderCapabilitiesV2,
createdAt: now,
updatedAt: now,
lastError: null,
};
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
let nativeStreamFailure: OrchestrationV2ProviderFailure | null = null;
const threads = new Map<string, OpenCodeThreadState>();
const variantCache: OpenCodeRuntime.OpenCodeVariantCache = new Map();
const commandReceipts = new Map<string, Deferred.Deferred<void>>();
const commandControllers = new Map<string, Set<AbortController>>();
const pendingRequests = new Map<string, PendingOpenCodeRequest>();
const pendingRequestsByNativeId = new Map<string, PendingOpenCodeRequest>();
const subagentsByNativeItemId = new Map<string, OpenCodeSubagentContext>();
const subagentsByChildSessionId = new Map<string, OpenCodeSubagentContext>();
const relatedSessionOwners = new Map<string, OpenCodeThreadState>();
// Busy children outlive parent settlement; keep their server open.
const busySessionIds = new Set<string>();
// A background task returns before its new child session reports busy.
const unstartedSessionIds = new Set<string>();
// A child can error before any turn of it is projected; its next idle settles the launch.
const sessionErrorOutcomes = new Map<string, TerminalTurnStatus>();
// Remember settled requests across routing retries to prevent resurrection; only recent IDs matter.
const settledNativeRequestIds = new Set<string>();
const pendingChildRequestRoutes = new Set<string>();
const rememberSettledRequest = (nativeRequestId: string) => {
if (settledNativeRequestIds.size >= 2_048) settledNativeRequestIds.clear();
settledNativeRequestIds.add(nativeRequestId);
};
// @effect-diagnostics-next-line abortControllerInEffect:off - Session closure aborts this stream independently of the creation fiber.
const abortController = new AbortController();
let closing = false;
let hasConnected = false;
// Orders native events with turn installation, so a held wake replays before later events.
const eventPermit = Semaphore.makeUnsafe(1);
const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) =>
Queue.offer(events, event).pipe(Effect.asVoid);
const logProtocolEvent = makeOpenCodeProtocolLogger({
nativeEventLogger: options.nativeEventLogger,
idAllocator,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
threadId: input.threadId,
});
const sdkCall = <A>(
method: string,
payload: unknown,
call: (signal: AbortSignal) => Promise<A>,
): Effect.Effect<A, OpenCodeRuntime.OpenCodeRuntimeError> =>
logProtocolEvent({
direction: "outgoing",
messageKind: "request",
method,
payload,
}).pipe(
Effect.andThen(OpenCodeRuntime.runOpenCodeSdk(method, call)),
Effect.tap((response) =>
logProtocolEvent({
direction: "incoming",
messageKind: "response",
method,
payload: sdkResponseForRawLog(response),
}),
),
);
const abortDescendants = Effect.fn("OpencodeAdapter.abortDescendants")(function* (
rootId: string,
) {
const visited = new Set([rootId]);
const semaphore = Semaphore.makeUnsafe(8);
const visit = Effect.fn("OpencodeAdapter.visit")(function* (
sessionId: string,
abort: boolean,
): Effect.fn.Return<OpenCodeRuntime.OpenCodeRuntimeError | undefined> {
const abortResult = abort
? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
client.session.abort({ sessionID: sessionId }, { signal }),
).pipe(
semaphore.withPermit,
Effect.catchIf(isOpenCodeNotFound, () => Effect.void),
Effect.result,
)
: undefined;
const childrenResult = yield* sdkCall(
"session.children",
{ sessionID: sessionId },
(signal) => client.session.children({ sessionID: sessionId }, { signal }),
).pipe(
semaphore.withPermit,
Effect.catchIf(isOpenCodeNotFound, () => Effect.void),
Effect.result,
);
const firstFailure = abortResult?._tag === "Failure" ? abortResult.failure : undefined;
if (childrenResult._tag === "Failure") return firstFailure ?? childrenResult.failure;
const fresh = (childrenResult.success?.data ?? []).filter((child) => {
if (visited.has(child.id)) return false;
visited.add(child.id);
return true;
});
const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), {
concurrency: 8,
});
return firstFailure ?? failures.find((failure) => failure !== undefined);
});
const failure = yield* visit(rootId, false);
if (failure) return yield* failure;
}, Effect.timeout("15 seconds"));
const updateProviderSession =
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (
status: OrchestrationV2ProviderSession["status"],
lastError: string | null = sessionEntity.lastError,
) {
const updatedAt = yield* DateTime.now;
sessionEntity = { ...sessionEntity, status, lastError, updatedAt };
yield* emitProviderEvent({
type: "provider_session.updated",
driver: OPENCODE_PROVIDER,
providerSession: sessionEntity,
});
});
const updateProviderThread =
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (
state: OpenCodeThreadState,
patch: Partial<OrchestrationV2ProviderThread>,
) {
const updatedAt = yield* DateTime.now;
state.providerThread = { ...state.providerThread, ...patch, updatedAt };
yield* emitProviderEvent({
type: "provider_thread.updated",
driver: OPENCODE_PROVIDER,
providerThread: state.providerThread,
});
});
const itemOrdinal = (turn: ActiveOpenCodeTurn, nativeItemId: string): number => {
const existing = turn.itemOrdinals.get(nativeItemId);
if (existing !== undefined) return existing;
const ordinal = turn.nextItemOrdinal++;
turn.itemOrdinals.set(nativeItemId, ordinal);
return ordinal;
};
const emitProviderTurn = (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
status: OrchestrationV2ProviderTurn["status"],
completedAt: DateTime.Utc | null,
) => {
const providerTurn: OrchestrationV2ProviderTurn = {
...turn.providerTurn,
nativeTurnRef:
turn.nativeUserMessageId === null
? turn.providerTurn.nativeTurnRef
: providerRef(turn.nativeUserMessageId, "weak"),
status,
completedAt,
...(completedAt === null
? {}
: {
turnTokenUsage:
turn.usage.partIds.size === 0
? {
usageScope: "main_agent" as const,
usageStatus: "unavailable" as const,
hasSubagents: turn.usage.hasSubagents,
}
: {
usageScope: "main_agent" as const,
usageStatus:
status === "completed" &&
turn.usage.complete &&
turn.usage.unresolvedStepsByMessageId.size === 0
? ("complete" as const)
: ("partial" as const),
inputTokens: turn.usage.inputTokens,
cachedInputTokens: turn.usage.cachedInputTokens,
cacheCreationTokens: turn.usage.cacheCreationTokens,
outputTokens: turn.usage.outputTokens,
reasoningTokens: turn.usage.reasoningTokens,
hasSubagents: turn.usage.hasSubagents,
},
...openCodeContextUsage(
turn.usage.lastStep,
variantCache.get(turn.modelSelection.model.trim())?.contextWindow,
completedAt,
),
}),
};
Object.assign(turn.providerTurn, providerTurn);
state.providerTurns.set(String(providerTurn.id), providerTurn);
return emitProviderEvent({
type: "provider_turn.updated",
driver: OPENCODE_PROVIDER,
threadId: turn.threadId,
providerTurn,
});
};
const emitTextPart = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
part: Extract<OpenCodePart, { type: "text" | "reasoning" }>,
forceCompleted = false,
) {
if (part.type === "text" && (part.ignored === true || part.synthetic === true)) return;
if (part.text.length === 0) return;
const emittedAt = yield* DateTime.now;
const isCompleted = forceCompleted || part.time?.end !== undefined;
const startedAt = dateTimeFromEpoch(part.time?.start, emittedAt);
const completedAt = isCompleted ? dateTimeFromEpoch(part.time?.end, emittedAt) : null;
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const ordinal = itemOrdinal(turn, part.id);
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: turn.rootNodeId,
rootNodeId: turn.rootNodeId,
kind: part.type === "text" ? "assistant_message" : "reasoning",
status: isCompleted ? "completed" : "running",
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt,
},
});
if (part.type === "text") {
const messageId = idAllocator.derive.messageFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const message: OrchestrationV2ConversationMessage = {
createdBy: "agent",
creationSource: "provider",
id: messageId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
role: "assistant",
text: part.text,
attachments: [],
streaming: !isCompleted,
createdAt: startedAt,
updatedAt: emittedAt,
};
yield* emitProviderEvent({
type: "message.updated",
driver: OPENCODE_PROVIDER,
message,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
parentItemId: null,
ordinal,
status: isCompleted ? "completed" : "running",
title: null,
startedAt,
completedAt,
updatedAt: emittedAt,
type: "assistant_message",
messageId,
text: part.text,
streaming: !isCompleted,
},
});
return;
}
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
parentItemId: null,
ordinal,
status: isCompleted ? "completed" : "running",
title: null,
startedAt,
completedAt,
updatedAt: emittedAt,
type: "reasoning",
text: part.text,
streaming: !isCompleted,
},
});
});
// A child turn's ordinal never exceeds its user message's position in the session, and that
// position survives restarts, so it stays above every ordinal allocated before.
const storedUserMessagePosition = Effect.fnUntraced(function* (
childSessionId: string,
messageId: string,
) {
const response = yield* sdkCall("session.messages", { sessionID: childSessionId }, () =>
client.session.messages({ sessionID: childSessionId }),
);
const userMessageIds = unwrapData("session.messages", response).flatMap((entry) =>
entry.info.role === "user" ? [entry.info.id] : [],
);
const index = userMessageIds.indexOf(messageId);
return (index === -1 ? userMessageIds.length : index) + 1;
});
const emitSubagent = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
part: ToolPart,
childOutcome?: TerminalTurnStatus,
) {
const now = yield* DateTime.now;
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
turn.usage.hasSubagents = true;
const input = toolInput(part);
const prompt = recordString(input, "prompt") ?? "";
const title = toolTitle(part) ?? recordString(input, "description") ?? null;
let context = subagentsByNativeItemId.get(part.id);
if (context === undefined) {
context = {
nativeItemId: part.id,
nodeId,
parentState: state,
parentTurn: turn,
prompt,
title,
startedAt: toolStartedAt(part, now),
childSessionId: null,
childThreadId: null,
childProviderThreadId: null,
model: null,
result: null,
launch: null,
};
subagentsByNativeItemId.set(part.id, context);
}
context.model = toolModel(part) ?? context.model;
const childSessionId = taskSessionId(part);
if (childSessionId !== null && context.childSessionId === null) {
context.childSessionId = childSessionId;
context.childThreadId = idAllocator.derive.subagentThread({
driver: OPENCODE_PROVIDER,
nativeThreadId: childSessionId,
});
context.childProviderThreadId = idAllocator.derive.providerThread({
driver: OPENCODE_PROVIDER,
nativeThreadId: childSessionId,
});
subagentsByChildSessionId.set(childSessionId, context);
relatedSessionOwners.set(childSessionId, state);
const childModelSelection: ModelSelection = {
instanceId: options.instanceId,
model: context.model ?? turn.modelSelection.model,
};
const childThread = makeSubagentChildThread({
parentThread: turn.appThread,
childThreadId: context.childThreadId,
parentNodeId: nodeId,
activeProviderThreadId: context.childProviderThreadId,
providerInstanceId: options.instanceId,
modelSelection: childModelSelection,
title: subagentThreadTitle({
parentTitle: turn.appThread.title,
title,
prompt,
ordinal: itemOrdinal(turn, part.id),
}),
now,
createdBy: "agent",
creationSource: "provider",
});
const childProviderThread: OrchestrationV2ProviderThread = {
id: context.childProviderThreadId,
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
providerSessionId: inputProviderSessionId,
appThreadId: context.childThreadId,
ownerNodeId: nodeId,
nativeThreadRef: providerRef(childSessionId),
nativeConversationHeadRef: null,
status: "active",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: null,
createdAt: now,
updatedAt: now,
};
const childSessionResponse = yield* sdkCall(
"session.get",
{ sessionID: childSessionId },
() => client.session.get({ sessionID: childSessionId }),
);
const nativeChildSession = unwrapData("session.get", childSessionResponse);
const childPermission = openCodeChildPermissionRules(
turn.runtimePolicy,
nativeChildSession.permission ?? [],
);
yield* sdkCall(
"session.update",
{ sessionID: childSessionId, permission: childPermission },
() =>
client.session.update({
sessionID: childSessionId,
permission: childPermission,
}),
);
// A Task call with task_id resumes the child, whose earlier turns already hold ordinals.
const knownChild = threads.get(childSessionId);
const resumedChild = knownChild?.parentSubagent == null ? undefined : knownChild;
const nextChildTurnOrdinal =
resumedChild === undefined
? recordString(input, "task_id") === childSessionId
? null
: 1
: resumedChild.nextChildTurnOrdinal;
threads.set(childSessionId, {
nativeSessionId: childSessionId,
providerThread: childProviderThread,
appThread: childThread,
activeTurn: null,
providerTurns: new Map(),
runtimeRequests: new Map(),
messageRoles: resumedChild?.messageRoles ?? new Map(),
userMessageIds: resumedChild?.userMessageIds ?? [],
parentSubagent: context,
nextChildTurnOrdinal,
nextAdmissionGeneration: 1,
wake: null,
lifecyclePermit: Semaphore.makeUnsafe(1),
permission: childPermission,
inheritedPermission: openCodePermissionRules(turn.runtimePolicy),
});
yield* emitProviderEvent({
type: "app_thread.created",
driver: OPENCODE_PROVIDER,
appThread: childThread,
});
yield* emitProviderEvent({
type: "provider_thread.updated",
driver: OPENCODE_PROVIDER,
providerThread: childProviderThread,
});
}
const output = toolOutput(part);
if (part.state.status === "completed" && output !== undefined) context.result = output;
const launchStatus = toolStatus(part);
context.launch =
childOutcome === undefined &&
launchStatus.item === "completed" &&
context.childSessionId !== null &&
(busySessionIds.has(context.childSessionId) ||
unstartedSessionIds.has(context.childSessionId))
? part
: null;
const status =
context.launch !== null
? ({ node: "running", item: "running" } as const)
: childOutcome === undefined
? launchStatus
: { node: childOutcome, item: childOutcome };
const completedAt =
context.launch !== null
? null
: childOutcome === undefined
? toolCompletedAt(part, now)
: now;
const subagentStatus: OrchestrationV2Subagent["status"] = status.item;
const subagent: OrchestrationV2Subagent = {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: turn.rootNodeId,
origin: "provider_native",
createdBy: "agent",
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
providerThreadId: context.childProviderThreadId,
childThreadId: context.childThreadId,
nativeTaskRef: nativeItemRef,
prompt,
title,
model: context.model,
status: subagentStatus,
result: context.result,
startedAt: context.startedAt,
completedAt,
updatedAt: now,
};
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: turn.rootNodeId,
rootNodeId: turn.rootNodeId,
kind: "subagent",
status: status.node,
countsForRun: false,
providerThreadId: context.childProviderThreadId ?? state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: context.startedAt,
completedAt,
},
});
yield* emitProviderEvent({
type: "subagent.updated",
driver: OPENCODE_PROVIDER,
subagent,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
parentItemId: null,
ordinal: itemOrdinal(turn, part.id),
status: status.item,
title,
startedAt: context.startedAt,
completedAt,
updatedAt: now,
type: "subagent",
subagentId: nodeId,
origin: "provider_native",
driver: OPENCODE_PROVIDER,
providerInstanceId: options.instanceId,
childThreadId: context.childThreadId,
prompt,
result: context.result,
},
});
});
const settleLaunchedSubagents = Effect.fnUntraced(function* (
childSessionId: string,
outcome?: TerminalTurnStatus,
) {
const lastTurn = Array.from(threads.get(childSessionId)?.providerTurns.values() ?? []).at(
-1,
)?.status;
const errorOutcome = sessionErrorOutcomes.get(childSessionId);
sessionErrorOutcomes.delete(childSessionId);
const childOutcome =
outcome ??
errorOutcome ??
(lastTurn === "interrupted" || lastTurn === "failed" || lastTurn === "cancelled"
? lastTurn
: "completed");
for (const context of subagentsByNativeItemId.values()) {
if (context.childSessionId === childSessionId && context.launch !== null) {
yield* emitSubagent(
context.parentState,
context.parentTurn,
context.launch,
childOutcome,
);
}
}
});
// No idle event settles a launched child that Stop aborts before it reports busy.
const interruptLaunchedSubagents = Effect.fnUntraced(function* (rootSessionId: string) {
for (const context of subagentsByNativeItemId.values()) {
let owner = context.parentState;
while (owner.parentSubagent !== null) owner = owner.parentSubagent.parentState;
if (owner.nativeSessionId === rootSessionId && context.launch !== null) {
yield* emitSubagent(
context.parentState,
context.parentTurn,
context.launch,
"interrupted",
);
}
}
});
const emitToolPart = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
part: ToolPart,
) {
const normalizedTool = part.tool.toLowerCase();
if (normalizedTool === "task") {
yield* emitSubagent(state, turn, part);
return;
}
if (normalizedTool === "question") return;
const now = yield* DateTime.now;
const status = toolStatus(part);
const startedAt = toolStartedAt(part, now);
const completedAt = toolCompletedAt(part, now);
const nativeItemRef = providerRef(part.id);
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.id,
});
const base = {
id: turnItemId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
parentItemId: null,
ordinal: itemOrdinal(turn, part.id),
status: status.item,
title: toolTitle(part),
startedAt,
completedAt,
updatedAt: now,
} satisfies Pick<
OrchestrationV2TurnItem,
| "id"
| "threadId"
| "runId"
| "nodeId"
| "providerThreadId"
| "providerTurnId"
| "nativeItemRef"
| "parentItemId"
| "ordinal"
| "status"
| "title"
| "startedAt"
| "completedAt"
| "updatedAt"
>;
const input = toolInput(part);
const output = toolOutput(part);
const isNativeTool = part.tool === "code_search" || part.tool === "apply_patch";
if (!isNativeTool && part.tool.includes("_") && turn.mcpServerNames === undefined) {
const serverNames = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.status", (signal) =>
client.mcp.status(undefined, { signal, throwOnError: true }),
).pipe(
Effect.timeout("1 second"),
Effect.map((response) => Object.keys(response.data ?? {})),
Effect.catch(() => Effect.void),
);
if (serverNames !== undefined) turn.mcpServerNames = serverNames;
}
const matchingServers = turn.mcpServerNames?.filter(
(name) =>
!isNativeTool && part.tool.startsWith(`${name.replace(/[^a-zA-Z0-9_-]/g, "_")}_`),
);
const serverName = matchingServers?.length === 1 ? matchingServers[0] : undefined;
const presentation =
serverName === undefined
? {}
: mcpToolPresentation({
serverName,
toolName: part.tool.slice(serverName.replace(/[^a-zA-Z0-9_-]/g, "_").length + 1),
title: toolTitle(part) === part.tool ? undefined : toolTitle(part),
});
const files =
part.state.status === "completed"
? part.state.attachments?.map((file) => ({ uri: file.url, mime: file.mime }))
: undefined;
const turnItem: OrchestrationV2TurnItem = matchingServers?.length
? {
...base,
type: "dynamic_tool",
...presentation,
toolName: part.tool,
input,
...(output === undefined && !files?.length
? {}
: { output: openCodeToolOutput(output, files) }),
}
: openCodeToolTurnItem(base, {
name: part.tool,
input,
output,
files,
completedMetadata:
part.state.status === "completed" ? part.state.metadata : undefined,
});
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: turn.rootNodeId,
rootNodeId: turn.rootNodeId,
kind: "tool_call",
status: status.node,
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt,
},
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem,
});
});
const emitTodo = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
todos: ReadonlyArray<OpenCodeTodo>,
) {
const now = yield* DateTime.now;
if (turn.planId === null) {
turn.planId = yield* idAllocator.allocate.plan({
threadId: turn.threadId,
...(turn.runId === null ? {} : { runId: turn.runId }),
driver: OPENCODE_PROVIDER,
});
}
const planId = turn.planId;
const nativeItemId = `${state.nativeSessionId}:todo:${turn.providerTurnId}`;
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId,
});
// A cancelled todo is not outstanding work, and plan steps have no
// cancelled status, so drop it rather than show it as pending.
const steps: Array<OrchestrationV2PlanStep> = todos.flatMap((todo, index) =>
todo.status === "cancelled"
? []
: [
{
id: `${nativeItemId}:${index + 1}`,
text: todo.content.trim() || `Todo ${index + 1}`,
status:
todo.status === "completed"
? "completed"
: todo.status === "in_progress"
? "running"
: "pending",
},
],
);
const completed = todos.length > 0 && steps.every((step) => step.status === "completed");
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: turn.rootNodeId,
rootNodeId: turn.rootNodeId,
kind: "todo_list",
status: completed ? "completed" : "running",
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(nativeItemId, "weak"),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: turn.startedAt,
completedAt: completed ? now : null,
},
});
yield* emitProviderEvent({
type: "plan.updated",
driver: OPENCODE_PROVIDER,
plan: {
id: planId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
status: completed ? "completed" : "active",
kind: "todo_list",
steps,
},
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
id: turnItemId,
threadId: turn.threadId,
runId: turn.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(nativeItemId, "weak"),
parentItemId: null,
ordinal: itemOrdinal(turn, nativeItemId),
status: completed ? "completed" : "running",
title: "Todo list",
startedAt: turn.startedAt,
completedAt: completed ? now : null,
updatedAt: now,
type: "todo_list",
planId,
steps,
},
});
});
const requestQuestions = (request: QuestionRequest) =>
request.questions.map((question, index) => ({
id: OpenCodeRuntime.openCodeQuestionId(index, question),
header: question.header.trim() || `Question ${index + 1}`,
question: question.question.trim() || question.header.trim() || `Question ${index + 1}`,
...(question.multiple === undefined ? {} : { multiSelect: question.multiple }),
...(question.custom === undefined ? {} : { allowCustomAnswer: question.custom }),
options: question.options.map((option) => ({
label: option.label.trim() || "Option",
description: option.description.trim() || option.label.trim() || "Option",
})),
}));
const runtimeRequestTurnItem = (
pending: PendingOpenCodeRequest,
status: OrchestrationV2TurnItem["status"],
completedAt: DateTime.Utc | null,
updatedAt: DateTime.Utc,
): OrchestrationV2TurnItem => {
const base = {
id: pending.turnItemId,
threadId: pending.turn.threadId,
runId: pending.turn.runId,
nodeId: pending.nodeId,
providerThreadId: pending.state.providerThread.id,
providerTurnId: pending.turn.providerTurnId,
nativeItemRef: providerRef(pending.nativeRequestId),
parentItemId: null,
ordinal: itemOrdinal(pending.turn, pending.nativeRequestId),
status,
startedAt: pending.createdAt,
completedAt,
updatedAt,
};
if (pending.question !== undefined) {
return {
...base,
title: "User input",
type: "user_input_request",
requestId: pending.requestId,
questions: requestQuestions(pending.question),
};
}
const permission = pending.permission;
if (permission === undefined) {
throw protocolError(`OpenCode request ${pending.requestId} has no native payload`);
}
return {
...base,
title: permission.permission,
type: "approval_request",
requestId: pending.requestId,
requestKind: pending.requestKind === "user_input" ? "command" : pending.requestKind,
prompt:
permission.patterns.length === 0
? permission.permission
: permission.patterns.join("\n"),
};
};
const emitRuntimeRequest = Effect.fnUntraced(function* (
owner: OpenCodeRequestOwner,
nativeRequestId: string,
request:
| { readonly type: "permission"; readonly value: PermissionRequest }
| { readonly type: "question"; readonly value: QuestionRequest },
) {
if (pendingRequestsByNativeId.has(nativeRequestId)) return;
const { state, turn, subagent } = owner;
const now = yield* DateTime.now;
const requestId = yield* idAllocator.allocate.runtimeRequest({
driver: OPENCODE_PROVIDER,
providerTurnId: turn.providerTurnId,
nativeRequestId,
});
const nodeId = idAllocator.derive.approvalNode({ requestId });
const turnItemId = idAllocator.derive.approvalTurnItem({ requestId });
const permissionToolName =
request.type === "permission" && request.value.tool !== undefined
? threads
.get(request.value.sessionID)
?.activeTurn?.toolNamesByCallId.get(request.value.tool.callID)
: undefined;
const permissionRequestKind =
request.type === "permission"
? openCodePermissionRequestKind(request.value.permission, permissionToolName)
: undefined;
const requestKind: OrchestrationV2RuntimeRequest["kind"] =
permissionRequestKind ?? "user_input";
const pending: PendingOpenCodeRequest = {
requestId,
nativeRequestId,
nativeSessionId: request.value.sessionID,
turn,
state,
nodeId,
parentNodeId: subagent?.nodeId ?? turn.rootNodeId,
turnItemId,
requestKind,
createdAt: now,
...(request.type === "permission"
? { permission: request.value }
: { question: request.value }),
};
pendingRequests.set(String(requestId), pending);
pendingRequestsByNativeId.set(nativeRequestId, pending);
const runtimeRequest: OrchestrationV2RuntimeRequest = {
id: requestId,
nodeId,
providerTurnId: turn.providerTurnId,
nativeRequestRef: providerRef(nativeRequestId),
kind: requestKind,
status: "pending",
responseCapability: {
type: "live",
providerSessionId: inputProviderSessionId,
},
createdAt: now,
resolvedAt: null,
};
state.runtimeRequests.set(String(requestId), runtimeRequest);
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: nodeId,
threadId: turn.threadId,
runId: turn.runId,
parentNodeId: pending.parentNodeId,
rootNodeId: turn.rootNodeId,
kind: request.type === "question" ? "user_input_request" : "approval_request",
status: "waiting",
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(nativeRequestId),
runtimeRequestId: requestId,
checkpointScopeId: null,
startedAt: now,
completedAt: null,
},
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: runtimeRequestTurnItem(pending, "waiting", null, now),
});
// A response can commit as soon as the actionable request is published.
yield* emitProviderEvent({
type: "runtime_request.updated",
driver: OPENCODE_PROVIDER,
threadId: turn.threadId,
runtimeRequest,
});
yield* updateProviderSession("waiting", null);
});
const resolveRuntimeRequest = Effect.fnUntraced(function* (
nativeRequestId: string,
status: "resolved" | "cancelled",
) {
const pending = pendingRequestsByNativeId.get(nativeRequestId);
if (pending === undefined) return;
const now = yield* DateTime.now;
const current = pending.state.runtimeRequests.get(String(pending.requestId));
if (current !== undefined) {
const resolved: OrchestrationV2RuntimeRequest = {
...current,
status,
resolvedAt: now,
};
pending.state.runtimeRequests.set(String(pending.requestId), resolved);
yield* emitProviderEvent({
type: "runtime_request.updated",
driver: OPENCODE_PROVIDER,
threadId: pending.turn.threadId,
runtimeRequest: resolved,
});
}
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: pending.nodeId,
threadId: pending.turn.threadId,
runId: pending.turn.runId,
parentNodeId: pending.parentNodeId,
rootNodeId: pending.turn.rootNodeId,
kind: pending.question === undefined ? "approval_request" : "user_input_request",
status: status === "resolved" ? "completed" : "cancelled",
countsForRun: false,
providerThreadId: pending.state.providerThread.id,
providerTurnId: pending.turn.providerTurnId,
nativeItemRef: providerRef(nativeRequestId),
runtimeRequestId: pending.requestId,
checkpointScopeId: null,
startedAt: pending.createdAt,
completedAt: now,
},
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: runtimeRequestTurnItem(
pending,
status === "resolved" ? "completed" : "cancelled",
now,
now,
),
});
pendingRequests.delete(String(pending.requestId));
pendingRequestsByNativeId.delete(nativeRequestId);
const hasOtherPending = Array.from(pendingRequests.values()).some(
(candidate) => candidate.turn.isRoot,
);
if (!hasOtherPending) yield* updateProviderSession("running", null);
});
const resolveSessionOwner = Effect.fnUntraced(function* (sessionId: string) {
const known = threads.get(sessionId) ?? relatedSessionOwners.get(sessionId);
if (known !== undefined) return known;
let cursor = sessionId;
const hops: string[] = [];
for (let depth = 0; depth < 5; depth += 1) {
const response = yield* sdkCall("session.get", { sessionID: cursor }, () =>
client.session.get({ sessionID: cursor }),
).pipe(Effect.option);
const info = Option.getOrUndefined(response)?.data;
const parentId = info?.parentID;
if (parentId === undefined) return undefined;
hops.push(cursor);
const owner = threads.get(parentId) ?? relatedSessionOwners.get(parentId);
if (owner !== undefined) {
for (const hop of hops) relatedSessionOwners.set(hop, owner);
return owner;
}
cursor = parentId;
}
return undefined;
});
const routeRuntimeRequest = Effect.fnUntraced(function* (
nativeRequestId: string,
sessionId: string,
request:
| { readonly type: "permission"; readonly value: PermissionRequest }
| { readonly type: "question"; readonly value: QuestionRequest },
) {
if (pendingChildRequestRoutes.has(nativeRequestId)) return;
const attempt = Effect.gen(function* () {
if (
settledNativeRequestIds.has(nativeRequestId) ||
pendingRequestsByNativeId.has(nativeRequestId)
) {
return true;
}
const state = yield* resolveSessionOwner(sessionId);
const owner = state === undefined ? undefined : topLevelRequestOwner(state);
if (owner === undefined) return false;
yield* emitRuntimeRequest(owner, nativeRequestId, request);
return true;
});
if (yield* attempt) return;
pendingChildRequestRoutes.add(nativeRequestId);
yield* Effect.gen(function* () {
for (let retry = 0; retry < 5; retry += 1) {
yield* Effect.sleep(Duration.millis(Math.min(200 * 2 ** retry, 2_000)));
if (yield* attempt) return;
}
}).pipe(
Effect.ensuring(Effect.sync(() => pendingChildRequestRoutes.delete(nativeRequestId))),
Effect.forkIn(scope),
);
});
const finalizeTurn = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
status: TerminalTurnStatus,
terminal?: {
readonly failure?: OrchestrationV2ProviderFailure;
readonly threadDisposition?: "reusable" | "broken";
},
) {
// Once claimed, terminal publication must finish even if the routing budget expires.
return yield* Effect.uninterruptibleMask((restore) =>
Effect.gen(function* () {
if (turn.finalized) return;
if (nativeStreamFailure !== null) {
status = "failed";
terminal = { failure: nativeStreamFailure, threadDisposition: "broken" };
}
let lastError = sessionEntity.lastError;
if (status === "completed" && turn.contextOverflow !== null) {
status = "failed";
terminal = { failure: turn.contextOverflow };
lastError = turn.contextOverflow.message;
}
turn.finalized = true;
if (turn.priorWakeSettled !== null)
yield* Deferred.succeed(turn.priorWakeSettled, undefined);
const completedAt = yield* DateTime.now;
for (const part of turn.parts.values()) {
if (part.type === "text" || part.type === "reasoning") {
yield* emitTextPart(state, turn, part, true);
}
}
for (const pending of Array.from(pendingRequests.values())) {
if (
pending.turn.providerTurnId === turn.providerTurnId ||
pending.nativeSessionId === state.nativeSessionId
) {
yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled");
}
}
// Prompts read the catalog only for variants; a completed turn needs its context window.
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model);
if (status === "completed" && turn.usage.lastStep !== null && parsedModel !== null) {
yield* restore(
OpenCodeRuntime.readOpenCodeCatalogModel(
client,
parsedModel,
undefined,
variantCache,
),
).pipe(Effect.exit);
}
yield* emitProviderTurn(state, turn, status, completedAt);
const threadDisposition = terminal?.threadDisposition ?? "reusable";
yield* updateProviderThread(state, {
status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle",
nativeConversationHeadRef:
turn.nativeUserMessageId === null
? state.providerThread.nativeConversationHeadRef
: providerRef(turn.nativeUserMessageId, "weak"),
});
state.activeTurn = null;
if (!turn.isRoot) {
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: turn.rootNodeId,
threadId: turn.threadId,
runId: null,
parentNodeId: null,
rootNodeId: turn.rootNodeId,
kind: "root_turn",
status,
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(state.nativeSessionId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: turn.startedAt,
completedAt,
},
});
return;
}
const anotherTurnIsActive = Array.from(threads.values()).some(
(candidate) => candidate.activeTurn?.isRoot === true,
);
yield* updateProviderSession(
anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready",
status === "failed" ? lastError : null,
);
yield* emitProviderEvent(
status === "failed"
? {
type: "turn.terminal",
driver: OPENCODE_PROVIDER,
providerThreadId: turn.providerThreadId,
providerTurnId: turn.providerTurnId,
runOrdinal: turn.runOrdinal,
failureItemOrdinal: itemOrdinal(
turn,
`terminal-failure:${turn.providerTurnId}`,
),
status,
failure:
terminal?.failure ??
makeProviderFailure({
message: sessionEntity.lastError ?? undefined,
class: "provider_error",
}),
threadDisposition,
}
: {
type: "turn.terminal",
driver: OPENCODE_PROVIDER,
providerThreadId: turn.providerThreadId,
providerTurnId: turn.providerTurnId,
runOrdinal: turn.runOrdinal,
status,
failure: null,
threadDisposition,
},
);
}),
);
});
// A call, not inline checks: TS keeps earlier narrowing of these mutable fields across yields.
const turnIsLive = (state: OpenCodeThreadState, turn: ActiveOpenCodeTurn) =>
state.activeTurn === turn && !turn.finalized && !turn.interrupted;
const promptAdmissionIsCurrent = (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
generation: number,
) =>
state.activeTurn === turn &&
!turn.finalized &&
!turn.interrupted &&
turn.admissionPending &&
turn.admissionGeneration === generation;
const runPromptAdmissionReconciliation = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
generation: number,
) {
while (promptAdmissionIsCurrent(state, turn, generation)) {
const statusSequence = turn.admissionStatusSequence;
const status = yield* reconcileOpenCodePromptAdmissionStatus(
turn,
generation,
sdkCall(
"session.status",
{ sessionID: state.nativeSessionId, generation },
(signal) => client.session.status(undefined, { signal }),
).pipe(
Effect.match({
onFailure: () => "unknown" as const,
onSuccess: (response) => {
const statuses = unwrapData("session.status", response);
const sessionStatus = statuses[state.nativeSessionId];
return sessionStatus === undefined || sessionStatus.type === "idle"
? ("idle" as const)
: ("busy" as const);
},
}),
),
);
if (
state.activeTurn !== turn ||
status === "stale" ||
turn.finalized ||
turn.interrupted ||
turn.admissionGeneration !== generation
) {
return;
}
if (turn.admissionStatusSequence !== statusSequence) {
turn.admissionPending = true;
continue;
}
if (status === "idle") {
yield* finalizeTurn(state, turn, "completed");
return;
}
if (status === "busy") return;
yield* Effect.sleep("250 millis");
}
});
const reconcilePromptAdmission = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
) {
const generation = turn.admissionGeneration;
if (
!promptAdmissionIsCurrent(state, turn, generation) ||
turn.admissionReconciliationGeneration === generation
) {
return;
}
turn.admissionReconciliationGeneration = generation;
yield* runPromptAdmissionReconciliation(state, turn, generation).pipe(
Effect.ensuring(
Effect.sync(() => {
if (turn.admissionReconciliationGeneration === generation) {
turn.admissionReconciliationGeneration = null;
}
}),
),
Effect.forkIn(scope),
);
});
const createChildTurn = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
message: Extract<OpenCodeMessage, { role: "user" }>,
) {
if (state.appThread === null || state.parentSubagent === null) return null;
const ordinal =
state.nextChildTurnOrdinal ??
(yield* storedUserMessagePosition(state.nativeSessionId, message.id));
state.nextChildTurnOrdinal = ordinal + 1;
const now = yield* DateTime.now;
const startedAt = dateTimeFromEpoch(message.time.created, now);
const rootNodeId = idAllocator.derive.nodeFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: `${state.nativeSessionId}:root:${message.id}`,
});
const providerTurnId = idAllocator.derive.providerTurn({
driver: OPENCODE_PROVIDER,
nativeTurnId: message.id,
});
const providerTurn: OrchestrationV2ProviderTurn = {
id: providerTurnId,
providerThreadId: state.providerThread.id,
nodeId: rootNodeId,
runAttemptId: null,
nativeTurnRef: providerRef(message.id, "weak"),
ordinal,
status: "running",
startedAt,
completedAt: null,
};
const turn: ActiveOpenCodeTurn = {
isRoot: false,
threadId: state.appThread.id,
runId: null,
rootNodeId,
appThread: state.appThread,
modelSelection: state.appThread.modelSelection,
runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy,
providerTurnId,
providerThreadId: providerTurn.providerThreadId,
runOrdinal: state.parentSubagent.parentTurn.runOrdinal,
startedAt,
itemOrdinals: new Map(),
usage: makeOpenCodeTurnTokenUsageAccumulator(),
parts: new Map(),
partIdsByMessage: new Map(),
toolNamesByCallId: new Map(),
providerTurn,
nextItemOrdinal: 1,
nativeUserMessageId: message.id,
admissionMessageId: null,
priorWakePromptIds: new Set(),
priorWakeSettled: null,
interrupted: false,
finalized: false,
contextOverflow: null,
planId: null,
admissionGeneration: 0,
admissionReconciliationGeneration: null,
admissionPending: false,
admissionAccepted: true,
admissionMessageObserved: true,
idleDuringAdmission: false,
admissionUncertain: false,
admissionStatusSequence: 0,
admissionSettled: Deferred.makeUnsafe<void>(),
admissionAbortController: null,
};
state.activeTurn = turn;
state.providerTurns.set(String(providerTurnId), providerTurn);
yield* emitProviderEvent({
type: "node.updated",
driver: OPENCODE_PROVIDER,
node: {
id: rootNodeId,
threadId: turn.threadId,
runId: null,
parentNodeId: null,
rootNodeId,
kind: "root_turn",
status: "running",
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId,
nativeItemRef: providerRef(message.id, "weak"),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt: null,
},
});
yield* emitProviderTurn(state, turn, "running", null);
return turn;
});
const projectChildUserPart = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
part: Extract<OpenCodePart, { type: "text" }>,
) {
const now = yield* DateTime.now;
const messageId = idAllocator.derive.messageFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.messageID,
});
const turnItemId = idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: part.messageID,
});
const projected: OrchestrationV2ConversationMessage = {
createdBy: "agent",
creationSource: "provider",
id: messageId,
threadId: turn.threadId,
runId: null,
nodeId: turn.rootNodeId,
role: "user",
text: part.text,
attachments: [],
streaming: false,
createdAt: turn.startedAt,
updatedAt: now,
};
yield* emitProviderEvent({
type: "message.updated",
driver: OPENCODE_PROVIDER,
message: projected,
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
createdBy: "agent",
creationSource: "provider",
id: turnItemId,
threadId: turn.threadId,
runId: null,
nodeId: turn.rootNodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(part.messageID),
parentItemId: null,
ordinal: itemOrdinal(turn, part.messageID),
status: "completed",
title: null,
startedAt: projected.createdAt,
completedAt: now,
updatedAt: now,
type: "user_message",
messageId,
inputIntent: "turn_start",
text: part.text,
attachments: [],
},
});
});
const emitCompactionItem = Effect.fn("OpenCodeAdapterV2.emitCompactionItem")(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
) {
const nativeItemId = `${turn.providerTurnId}:compaction`;
if (turn.itemOrdinals.has(nativeItemId)) return;
const now = yield* DateTime.now;
yield* emitProviderEvent({
type: "turn_item.updated",
driver: OPENCODE_PROVIDER,
turnItem: {
id: idAllocator.derive.turnItemFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId,
}),
threadId: turn.threadId,
runId: turn.runId,
nodeId: turn.rootNodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurnId,
nativeItemRef: providerRef(nativeItemId, "weak"),
parentItemId: null,
ordinal: itemOrdinal(turn, nativeItemId),
type: "compaction",
driver: OPENCODE_PROVIDER,
status: "completed",
title: "Context compacted",
startedAt: turn.startedAt,
completedAt: now,
updatedAt: now,
},
});
});
const handleMessageUpdated = Effect.fnUntraced(function* (
event: Extract<OpenCodeEvent, { type: "message.updated" }>,
) {
const state = threads.get(event.properties.sessionID);
if (state === undefined) return;
const message = event.properties.info;
state.messageRoles.set(message.id, message.role);
if (message.role === "assistant") {
const usage = state.activeTurn?.usage;
if (usage === undefined) return;
const prior = usage.assistantOwnershipByMessageId.get(message.id);
const ownership =
prior !== undefined && prior !== "unknown"
? prior
: !message.parentID
? "unknown"
: usage.promptMessageIds.has(message.parentID)
? "owned"
: "other";
usage.assistantOwnershipByMessageId.set(message.id, ownership);
if (ownership !== "unknown") {
if (ownership === "owned") {
for (const step of usage.unresolvedStepsByMessageId.get(message.id)?.values() ??
[]) {
accumulateOpenCodeStepUsage(usage, step);
}
}
usage.unresolvedStepsByMessageId.delete(message.id);
}
return;
}
const commandReceipt = commandReceipts.get(message.id);
if (commandReceipt) yield* Deferred.succeed(commandReceipt, undefined);
const isNewUserMessage = !state.userMessageIds.includes(message.id);
if (isNewUserMessage) state.userMessageIds.push(message.id);
let turn = state.activeTurn;
if (turn === null && state.parentSubagent !== null && isNewUserMessage) {
turn = yield* createChildTurn(state, message);
}
const matchesAdmission =
turn !== null &&
(turn.admissionMessageId === null || turn.admissionMessageId === message.id);
if (turn !== null && matchesAdmission) turn.usage.promptMessageIds.add(message.id);
if (turn !== null && matchesAdmission && turn.nativeUserMessageId === null) {
turn.nativeUserMessageId = message.id;
yield* emitProviderTurn(state, turn, "running", null);
}
if (turn !== null && matchesAdmission && turn.admissionPending) {
if (advanceOpenCodePromptAdmission(turn, "user-message") === "reconcile-idle") {
yield* reconcilePromptAdmission(state, turn);
}
}
});
const handlePartUpdated = Effect.fnUntraced(function* (
event: Extract<OpenCodeEvent, { type: "message.part.updated" }>,
) {
const part = event.properties.part;
const state = threads.get(part.sessionID);
const turn = state?.activeTurn;
if (state === undefined || turn === null || turn === undefined || turn.finalized) return;
if (part.type === "text" && state.messageRoles.get(part.messageID) === "user") {
if (!turn.isRoot) yield* projectChildUserPart(state, turn, part);
return;
}
if (part.type === "step-finish") {
const usage = turn.usage;
const ownership = usage.assistantOwnershipByMessageId.get(part.messageID);
if (ownership === "owned") accumulateOpenCodeStepUsage(usage, part);
else if (
ownership === "unknown" ||
(ownership === undefined && !state.messageRoles.has(part.messageID))
) {
const steps =
usage.unresolvedStepsByMessageId.get(part.messageID) ??
new Map<string, OpenCodeStepUsage>();
steps.set(part.id, { id: part.id, tokens: part.tokens });
usage.unresolvedStepsByMessageId.set(part.messageID, steps);
}
return;
}
if (part.type === "tool") {
turn.toolNamesByCallId.set(part.callID, part.tool);
} else {
turn.parts.set(part.id, part);
const ids = turn.partIdsByMessage.get(part.messageID) ?? new Set<string>();
ids.add(part.id);
turn.partIdsByMessage.set(part.messageID, ids);
}
switch (part.type) {
case "text":
case "reasoning":
yield* emitTextPart(state, turn, part);
return;
case "tool":
yield* emitToolPart(state, turn, part);
return;
default:
return;
}
});
const handlePartDelta = Effect.fnUntraced(function* (
event: Extract<OpenCodeEvent, { type: "message.part.delta" }>,
) {
if (event.properties.field !== "text") return;
const state = threads.get(event.properties.sessionID);
const turn = state?.activeTurn;
const current = turn?.parts.get(event.properties.partID);
if (
state === undefined ||
turn === null ||
turn === undefined ||
current === undefined ||
(current.type !== "text" && current.type !== "reasoning")
) {
return;
}
const updated = { ...current, text: current.text + event.properties.delta };
turn.parts.set(updated.id, updated);
yield* emitTextPart(state, turn, updated);
});
const handleAssistantCompleted = Effect.fnUntraced(function* (
event: Extract<OpenCodeEvent, { type: "message.updated" }>,
admitsPrompt = true,
) {
const message = event.properties.info;
if (message.role !== "assistant" || message.time.completed === undefined) return;
const state = threads.get(message.sessionID);
const turn = state?.activeTurn;
if (state === undefined || turn === null || turn === undefined) return;
// Versions may ignore supplied message IDs; completed assistant output admits settlement on idle.
if (admitsPrompt && !turn.priorWakePromptIds.has(message.parentID ?? "")) {
advanceOpenCodePromptAdmission(turn, "assistant-completed");
}
for (const partId of turn.partIdsByMessage.get(message.id) ?? []) {
const part = turn.parts.get(partId);
if (part?.type === "text" || part?.type === "reasoning") {
yield* emitTextPart(state, turn, part, true);
}
}
});
const abortRootSession = (state: OpenCodeThreadState) =>
sdkCall("session.abort", { sessionID: state.nativeSessionId }, (signal) =>
client.session.abort({ sessionID: state.nativeSessionId }, { signal }),
).pipe(Effect.timeout("10 seconds"));
// Native aborts target the whole session, so replacement admission waits for all cleanup.
const cleanupSessionWork = Effect.fn("OpencodeAdapter.cleanupSessionWork")(function* (
state: OpenCodeThreadState,
rootAbort: Effect.Effect<
unknown,
| Effect.Error<ReturnType<typeof abortRootSession>>
| ProviderAdapter.ProviderAdapterInterruptTimeoutError
>,
) {
const root = yield* rootAbort.pipe(Effect.result);
const descendants = yield* abortDescendants(state.nativeSessionId).pipe(Effect.result);
yield* interruptLaunchedSubagents(state.nativeSessionId);
if (root._tag === "Failure") return yield* root.failure;
if (descendants._tag === "Failure") return yield* descendants.failure;
});
const cancelWake = Effect.fn("OpencodeAdapter.cancelWake")(
function* (state: OpenCodeThreadState, wake: OpenCodeWake) {
if (closing || nativeStreamFailure !== null || state.wake !== wake) return;
wake.cancelling = true;
// prompt.ts publishes its user message before run-state.ts registers a cancellable runner.
// A noReply prompt saves one and never runs, so an undecided wake is aborted anyway.
const running =
wake.offered ||
(yield* Deferred.await(wake.admission).pipe(
Effect.timeoutOption("10 seconds"),
Effect.map(Option.getOrElse(() => true)),
));
yield* cleanupSessionWork(state, running ? abortRootSession(state) : Effect.void).pipe(
Effect.tapError(() =>
Effect.gen(function* () {
if (yield* Deferred.isDone(wake.settled)) return;
nativeStreamFailure = makeProviderFailure({
message:
"OpenCode cancellation failed before native idle; reconnect the provider session.",
class: "transport_error",
});
yield* updateProviderSession("error", nativeStreamFailure.message);
}),
),
);
},
(effect, state, wake) =>
effect.pipe(
Effect.ensuring(
Effect.sync(() => {
if (state.wake === wake) state.wake = null;
}),
),
),
);
const stopWake = (state: OpenCodeThreadState, wake: OpenCodeWake) =>
state.lifecyclePermit.withPermit(
cancelWake(state, wake).pipe(Effect.ignore({ log: true })),
);
const offerWake = (state: OpenCodeThreadState, wake: OpenCodeWake, threadId: ThreadId) =>
continuationRequests.offer({
threadId,
providerThreadId: state.providerThread.id,
driver: OPENCODE_PROVIDER,
detail: null,
delivery: "adapter_buffered",
dispatchIfCurrent: (dispatch) =>
eventPermit.withPermit(
Effect.suspend(() =>
state.wake === wake &&
!wake.cancelling &&
!closing &&
nativeStreamFailure === null
? Effect.asSome(dispatch)
: Effect.succeedNone,
),
),
clearIfCurrent: () => stopWake(state, wake),
onRunEndedWithoutStarting: () => stopWake(state, wake),
});
// Callers hold eventPermit. A root user message with no Hanzo turn starts a wake; its work stays
// held, with that of children no turn has claimed yet, until startTurn takes it.
const acceptEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) {
const sessionId = sessionWorkEventSessionId(event);
const owner =
sessionId === undefined
? undefined
: (threads.get(sessionId) ?? relatedSessionOwners.get(sessionId));
if (owner === undefined || sessionId === undefined) return yield* routeEvent(event);
const wake = owner.wake;
const isRoot = sessionId === owner.nativeSessionId;
const rootStatus =
isRoot && event.type === "session.status" ? event.properties.status.type : undefined;
// A later execution buffered into the same wake is unsettled until its own idle. Its new
// user message comes before busy, while prompt.ts may still be registering it.
const newRootUserMessage =
wake !== null &&
isRoot &&
event.type === "message.updated" &&
event.properties.info.role === "user" &&
!wake.events.some(
(held) =>
held.type === "message.updated" &&
held.properties.info.id === event.properties.info.id,
);
if (
wake !== null &&
(rootStatus === "busy" || rootStatus === "retry" || newRootUserMessage) &&
(yield* Deferred.isDone(wake.settled))
) {
wake.settled = Deferred.makeUnsafe<void>();
}
if (wake?.cancelling) {
if (!isRoot) return yield* routeEvent(event);
wake.events.push(event);
if (isRoot && (rootStatus === "busy" || rootStatus === "retry")) {
wake.offered = true;
yield* Deferred.succeed(wake.admission, true);
} else if (
isRoot &&
(rootStatus === "idle" ||
event.type === "session.idle" ||
// OpenCode stays busy and auto-compacts after an overflow.
(event.type === "session.error" &&
event.properties.error?.name !== "ContextOverflowError"))
) {
yield* Deferred.succeed(wake.admission, false);
yield* Deferred.succeed(wake.settled, undefined);
}
return;
}
if (wake !== null && isRoot && (rootStatus === "idle" || event.type === "session.idle")) {
yield* Deferred.succeed(wake.settled, undefined);
}
// Idle before busy: nothing ran, so the held user message was only an update.
if (
wake !== null &&
!wake.offered &&
isRoot &&
(rootStatus === "idle" ||
event.type === "session.idle" ||
event.type === "session.error")
) {
yield* Deferred.succeed(wake.admission, false);
owner.wake = null;
} else if (wake !== null && (wake.offered || isRoot)) {
wake.events.push(event);
if (!wake.offered && (rootStatus === "busy" || rootStatus === "retry")) {
wake.offered = true;
yield* Deferred.succeed(wake.admission, true);
const threadId = owner.providerThread.appThreadId;
if (threadId !== null) yield* offerWake(owner, wake, threadId);
}
return;
}
if (
event.type === "message.updated" &&
event.properties.info.role === "user" &&
isRoot &&
owner.parentSubagent === null &&
owner.activeTurn === null &&
owner.providerThread.appThreadId !== null &&
!owner.userMessageIds.includes(event.properties.info.id) &&
!closing &&
nativeStreamFailure === null
) {
owner.userMessageIds.push(event.properties.info.id);
owner.wake = {
events: [event],
offered: false,
cancelling: false,
admission: Deferred.makeUnsafe<boolean>(),
settled: Deferred.makeUnsafe<void>(),
};
return;
}
yield* routeEvent(event);
});
const handleEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) {
yield* logProtocolEvent({
direction: "incoming",
messageKind: "notification",
method: event.type,
payload: event,
});
// A slow native call only delays events, as on main; Stop goes through lifecyclePermit.
yield* eventPermit.withPermit(acceptEvent(event));
});
const routeEvent = Effect.fnUntraced(function* (
event: OpenCodeEvent,
historicalRootSessionId?: string,
) {
const historicalRoot =
historicalRootSessionId !== undefined &&
sessionWorkEventSessionId(event) === historicalRootSessionId;
// A foreground prompt inherits held output, but has not submitted its own native work yet.
if (
historicalRoot &&
(event.type === "session.status" ||
event.type === "session.idle" ||
event.type === "session.error")
)
return;
switch (event.type) {
case "server.connected":
if (hasConnected) {
for (const state of threads.values()) {
if (state.activeTurn !== null) state.activeTurn.usage.complete = false;
}
}
hasConnected = true;
return;
case "message.updated":
yield* handleMessageUpdated(event);
yield* handleAssistantCompleted(event, !historicalRoot);
return;
case "session.compacted": {
const state = threads.get(event.properties.sessionID);
if (state?.activeTurn !== undefined && state.activeTurn !== null) {
state.activeTurn.contextOverflow = null;
yield* emitCompactionItem(state, state.activeTurn);
}
return;
}
case "message.part.updated":
yield* handlePartUpdated(event);
return;
case "message.part.delta":
yield* handlePartDelta(event);
return;
case "todo.updated": {
const state = threads.get(event.properties.sessionID);
if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
yield* emitTodo(state, state.activeTurn, event.properties.todos);
}
return;
}
case "permission.asked":
yield* routeRuntimeRequest(event.properties.id, event.properties.sessionID, {
type: "permission",
value: event.properties,
});
return;
case "question.asked":
yield* routeRuntimeRequest(event.properties.id, event.properties.sessionID, {
type: "question",
value: event.properties,
});
return;
case "permission.replied":
case "question.replied":
rememberSettledRequest(event.properties.requestID);
yield* resolveRuntimeRequest(event.properties.requestID, "resolved");
return;
case "question.rejected":
rememberSettledRequest(event.properties.requestID);
yield* resolveRuntimeRequest(event.properties.requestID, "cancelled");
return;
case "session.created":
case "session.updated": {
const info = event.properties.info;
if (event.type === "session.created" && info.parentID !== undefined) {
unstartedSessionIds.add(info.id);
}
if (info.parentID !== undefined && !threads.has(info.id)) {
const owner = threads.get(info.parentID) ?? relatedSessionOwners.get(info.parentID);
if (owner !== undefined) {
relatedSessionOwners.set(info.id, owner);
}
}
return;
}
case "session.deleted":
relatedSessionOwners.delete(event.properties.info.id);
busySessionIds.delete(event.properties.info.id);
unstartedSessionIds.delete(event.properties.info.id);
yield* settleLaunchedSubagents(event.properties.info.id, "interrupted");
return;
case "session.status": {
const sessionId = event.properties.sessionID;
unstartedSessionIds.delete(sessionId);
switch (event.properties.status.type) {
case "busy":
case "retry":
if (threads.has(sessionId) || relatedSessionOwners.has(sessionId)) {
busySessionIds.add(sessionId);
}
break;
case "idle":
busySessionIds.delete(sessionId);
break;
}
const state = threads.get(sessionId);
if (state === undefined) return;
if (state.activeTurn?.admissionPending) {
state.activeTurn.admissionStatusSequence++;
}
if (event.properties.status.type === "busy") {
yield* updateProviderThread(state, { status: "active" });
return;
}
if (event.properties.status.type === "idle" && state.activeTurn !== null) {
if (state.activeTurn.priorWakeSettled !== null) {
if (state.activeTurn.contextOverflow !== null) {
yield* finalizeTurn(state, state.activeTurn, "completed");
} else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined);
return;
}
if (state.activeTurn.admissionPending) {
advanceOpenCodePromptAdmission(state.activeTurn, "idle");
return;
}
yield* finalizeTurn(
state,
state.activeTurn,
state.activeTurn.interrupted ? "interrupted" : "completed",
);
}
if (event.properties.status.type === "idle") {
yield* settleLaunchedSubagents(sessionId);
}
return;
}
case "session.idle": {
busySessionIds.delete(event.properties.sessionID);
unstartedSessionIds.delete(event.properties.sessionID);
const state = threads.get(event.properties.sessionID);
if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
if (state.activeTurn.priorWakeSettled !== null) {
if (state.activeTurn.contextOverflow !== null) {
yield* finalizeTurn(state, state.activeTurn, "completed");
} else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined);
return;
}
if (state.activeTurn.admissionPending) {
state.activeTurn.admissionStatusSequence++;
advanceOpenCodePromptAdmission(state.activeTurn, "idle");
return;
}
yield* finalizeTurn(
state,
state.activeTurn,
state.activeTurn.interrupted ? "interrupted" : "completed",
);
}
yield* settleLaunchedSubagents(event.properties.sessionID);
return;
}
case "session.error": {
const overflowTurn =
event.properties.error?.name === "ContextOverflowError" &&
event.properties.sessionID !== undefined
? threads.get(event.properties.sessionID)?.activeTurn
: undefined;
if (overflowTurn !== undefined && overflowTurn !== null) {
// OpenCode stays busy and auto-compacts; the turn fails only if it idles uncompacted.
overflowTurn.contextOverflow = makeProviderFailure({
message: openCodeErrorMessage(event),
code: "ContextOverflowError",
class: "provider_error",
});
return;
}
if (event.properties.sessionID !== undefined) {
sessionErrorOutcomes.set(
event.properties.sessionID,
isMessageAbortedError(event) ? "interrupted" : "failed",
);
}
const states =
event.properties.sessionID === undefined
? Array.from(threads.values()).filter((state) => state.activeTurn !== null)
: [threads.get(event.properties.sessionID)].filter(
(state): state is OpenCodeThreadState => state !== undefined,
);
const error = event.properties.error;
const usageLimit = error?.name === "APIError" && error.data.statusCode === 429;
const failure = makeProviderFailure({
message: openCodeErrorMessage(event),
code: error?.name ?? null,
class: usageLimit ? "usage_limit" : "provider_error",
});
if (
!isMessageAbortedError(event) &&
(event.properties.sessionID === undefined ||
states.some((state) => state.parentSubagent === null))
) {
yield* updateProviderSession("error", failure.message);
}
for (const state of states) {
if (state.activeTurn !== null) {
yield* finalizeTurn(
state,
state.activeTurn,
terminalStatusForError(event, state.activeTurn),
{
failure,
threadDisposition:
event.properties.sessionID === undefined ? "broken" : "reusable",
},
);
}
}
return;
}
default:
return;
}
});
const inputProviderSessionId = input.providerSessionId;
const subscription = yield* sdkCall("event.subscribe", {}, () =>
client.event.subscribe(undefined, { signal: abortController.signal }),
);
yield* Scope.addFinalizer(
scope,
Effect.sync(() => abortController.abort()),
);
yield* Stream.fromAsyncIterable(
subscription.stream,
(cause) =>
new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "event.subscribe",
detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause),
cause,
}),
).pipe(
Stream.runForEach(handleEvent),
Effect.exit,
Effect.flatMap((exit) =>
Effect.gen(function* () {
busySessionIds.clear();
unstartedSessionIds.clear();
sessionErrorOutcomes.clear();
if (closing || abortController.signal.aborted) return;
const detail = Exit.isSuccess(exit)
? "OpenCode event stream ended unexpectedly."
: OpenCodeRuntime.openCodeRuntimeErrorDetail(Cause.squash(exit.cause));
nativeStreamFailure = makeProviderFailure({
message: detail,
class: "transport_error",
});
yield* updateProviderSession("error", detail);
for (const state of threads.values()) {
// No continuation can admit a wake this stream will never finish.
state.wake = null;
if (state.activeTurn !== null)
yield* finalizeTurn(state, state.activeTurn, "failed", {
failure: makeProviderFailure({ message: detail, class: "transport_error" }),
threadDisposition: "broken",
});
yield* settleLaunchedSubagents(state.nativeSessionId, "failed");
}
yield* Queue.end(events);
}),
),
Effect.forkIn(scope),
);
if (!connection.external && connection.exitCode !== null) {
yield* connection.exitCode.pipe(
Effect.flatMap((code) =>
abortController.signal.aborted
? Effect.void
: Effect.gen(function* () {
const detail = `OpenCode server exited unexpectedly (${code}).`;
nativeStreamFailure = makeProviderFailure({
message: detail,
class: "transport_error",
});
yield* updateProviderSession("error", detail);
for (const state of threads.values()) {
state.wake = null;
if (state.activeTurn !== null) {
yield* finalizeTurn(state, state.activeTurn, "failed", {
failure: makeProviderFailure({
message: detail,
class: "transport_error",
}),
threadDisposition: "broken",
});
}
}
}),
),
Effect.forkIn(scope),
);
}
if (connection.external) {
yield* Scope.addFinalizer(
scope,
Effect.suspend(() =>
Effect.forEach(
Array.from(threads.values()).filter((state) => state.parentSubagent === null),
(state) =>
sdkCall("session.abort", { sessionID: state.nativeSessionId }, (signal) =>
client.session.abort({ sessionID: state.nativeSessionId }, { signal }),
).pipe(
Effect.timeout("1 second"),
Effect.ignore({ log: true }),
Effect.andThen(
abortDescendants(state.nativeSessionId).pipe(
Effect.timeout("1 second"),
Effect.ignore({ log: true }),
),
),
),
{ concurrency: 8, discard: true },
),
),
);
}
yield* Scope.addFinalizer(
scope,
Effect.sync(() => {
closing = true;
for (const state of threads.values()) state.wake = null;
}),
);
const registerThread = (
nativeSession: OpenCodeSession,
providerThread: OrchestrationV2ProviderThread,
appThread: OrchestrationV2AppThread | null,
): OpenCodeThreadState => {
const existing = threads.get(nativeSession.id);
if (existing !== undefined) {
existing.providerThread = providerThread;
if (appThread !== null) existing.appThread = appThread;
if (nativeSession.permission !== undefined)
existing.permission = nativeSession.permission;
return existing;
}
const parentSubagent = subagentsByChildSessionId.get(nativeSession.id) ?? null;
const state: OpenCodeThreadState = {
nativeSessionId: nativeSession.id,
providerThread,
appThread,
activeTurn: null,
providerTurns: new Map(),
runtimeRequests: new Map(),
messageRoles: new Map(),
userMessageIds: [],
parentSubagent,
nextChildTurnOrdinal: 1,
nextAdmissionGeneration: 1,
wake: null,
lifecyclePermit: Semaphore.makeUnsafe(1),
permission: nativeSession.permission ?? [],
inheritedPermission: parentSubagent?.parentState.permission ?? [],
};
threads.set(nativeSession.id, state);
return state;
};
// OpenCode copies parent rules into a child only at creation, so children are updated here too.
const applyPermissionRules = Effect.fnUntraced(function* (
state: OpenCodeThreadState,
policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy,
) {
const parentRules = openCodePermissionRules(policy);
const pending = [state];
for (let target = pending.pop(); target !== undefined; target = pending.pop()) {
const previous = target.permission;
const permission =
target.parentSubagent === null
? parentRules
: openCodeChildPermissionRules(policy, previous, target.inheritedPermission);
if (
permission.length !== previous.length ||
!permission.every((rule, index) => permissionRuleEquals(rule, previous[index]!))
) {
const sessionID = target.nativeSessionId;
yield* sdkCall("session.update", { sessionID, permission }, () =>
client.session.update({ sessionID, permission }),
);
target.permission = permission;
}
if (target.parentSubagent !== null) target.inheritedPermission = parentRules;
for (const child of threads.values()) {
if (child.parentSubagent?.parentState === target) pending.push(child);
}
}
});
const resolvePromptParts = Effect.fnUntraced(function* (
turnInput: ProviderAdapter.ProviderAdapterV2TurnInput,
) {
if (turnInput.resume) return [];
const text = (yield* providerMessageTextWithAttachmentPaths({
text: turnInput.message.text,
attachments: turnInput.message.attachments,
resolveAttachmentPath: host.resolveAttachmentPath,
resolveExtractedTextPath: host.resolveExtractedTextPath,
})).trim();
const files = OpenCodeRuntime.toOpenCodeFileParts({
attachments: turnInput.message.attachments,
resolveAttachmentPath: host.resolveAttachmentPath,
});
if (text.length === 0 && files.length === 0) {
throw protocolError("OpenCode turns require text or at least one valid attachment");
}
return [...(text.length === 0 ? [] : [{ type: "text" as const, text }]), ...files];
});
const readSnapshot = Effect.fnUntraced(function* (
providerThread: OrchestrationV2ProviderThread,
) {
const sessionId = nativeThreadId(providerThread);
const sessionResponse = yield* sdkCall("session.get", { sessionID: sessionId }, () =>
client.session.get({ sessionID: sessionId }),
);
const nativeSession = unwrapData("session.get", sessionResponse);
const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () =>
client.session.messages({ sessionID: sessionId }),
);
const nativeMessages = [];
for (const entry of unwrapData("session.messages", response)) {
// Reverted records remain in messages; stop at the revert marker to avoid resurrecting work.
if (entry.info.id === nativeSession.revert?.messageID) break;
nativeMessages.push(entry);
}
const state = threads.get(sessionId);
const snapshotNow = yield* DateTime.now;
const messages: Array<OrchestrationV2ConversationMessage> = nativeMessages.flatMap(
({ info, parts }) => {
const text = parts
.filter(
(part): part is Extract<OpenCodePart, { type: "text" }> => part.type === "text",
)
.filter((part) => part.ignored !== true && part.synthetic !== true)
.map((part) => part.text)
.join("\n");
if (text.length === 0) return [];
const createdAt = dateTimeFromEpoch(info.time.created, snapshotNow);
return [
{
createdBy: info.role === "user" ? "user" : "agent",
creationSource: "provider",
id: idAllocator.derive.messageFromProviderItem({
driver: OPENCODE_PROVIDER,
nativeItemId: info.id,
}),
threadId: providerThread.appThreadId ?? input.threadId,
runId: null,
nodeId: null,
role: info.role,
text,
attachments: [],
streaming: false,
createdAt,
updatedAt:
info.role === "assistant"
? dateTimeFromEpoch(info.time.completed, createdAt)
: createdAt,
},
];
},
);
const lastUser = nativeMessages.findLast(({ info }) => info.role === "user")?.info.id;
return {
providerThread: {
...providerThread,
providerSessionId: input.providerSessionId,
nativeConversationHeadRef:
lastUser === undefined ? null : providerRef(lastUser, "weak"),
status: "idle" as const,
updatedAt: snapshotNow,
},
providerTurns: state === undefined ? [] : [...state.providerTurns.values()],
messages,
runtimeRequests: state === undefined ? [] : [...state.runtimeRequests.values()],
providerPayload: nativeMessages,
};
});
// OpenCode runs each step with the agent and system prompt of the latest
// user message, so every prompt in a turn, steers included, repeats them.
const turnPromptOptions = (turn: ActiveOpenCodeTurn) => {
const agent =
getModelSelectionStringOptionValue(turn.modelSelection, "agent") ??
(turn.runtimePolicy.interactionMode === "plan" ? "plan" : undefined);
const variant = getModelSelectionStringOptionValue(turn.modelSelection, "variant");
return {
...(agent === undefined ? {} : { agent }),
...(variant === undefined ? {} : { variant }),
system: [
orchestrationSystemPrompt,
buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model }),
]
.filter(Boolean)
.join("\n\n"),
};
};
// Native commands await generation; user-message receipts admit their background requests.
const submitPrompt = Effect.fn("OpenCode.submitPrompt")(function* (
state: OpenCodeThreadState,
turn: ActiveOpenCodeTurn,
inputPayload: Parameters<typeof client.session.promptAsync>[0] & {
messageID: string;
sessionID: string;
},
abortController: AbortController,
messageText: string,
) {
const { variant, ...payloadWithoutVariant } = inputPayload;
const selectedVariant = yield* OpenCodeRuntime.resolveOpenCodeVariant(
client,
inputPayload.model,
variant,
abortController.signal,
variantCache,
);
const payload = {
...payloadWithoutVariant,
...(selectedVariant === undefined ? {} : { variant: selectedVariant }),
};
const match = messageText.trim().match(/^\/(\S+)(?:\s+([\s\S]*))?$/);
const command = match
? (yield* OpenCodeRuntime.loadOpenCodeCommands(client).pipe(
Effect.timeout("10 seconds"),
Effect.orElseSucceed(() => []),
)).find((entry) => entry.name === match[1])
: undefined;
if (!command) {
return yield* sdkCall("session.promptAsync", payload, (signal) =>
client.session.promptAsync(payload, {
signal: AbortSignal.any([signal, abortController.signal]),
}),
).pipe(Effect.asVoid);
}
const receipt = Deferred.makeUnsafe<void>();
commandReceipts.set(payload.messageID, receipt);
const controllers =
commandControllers.get(payload.sessionID) ?? new Set<AbortController>();
controllers.add(abortController);
commandControllers.set(payload.sessionID, controllers);
const generation = turn.admissionGeneration;
const commandPayload = {
sessionID: payload.sessionID,
messageID: payload.messageID,
command: command.name,
arguments: match?.[2] ?? "",
...(payload.model
? { model: `${payload.model.providerID}/${payload.model.modelID}` }
: {}),
...(payload.agent ? { agent: payload.agent } : {}),
...(payload.variant ? { variant: payload.variant } : {}),
parts: payload.parts?.filter((part) => part.type === "file") ?? [],
};
const request = yield* sdkCall("session.command", commandPayload, (signal) =>
client.session.command(commandPayload, {
signal: AbortSignal.any([signal, abortController.signal]),
}),
).pipe(
Effect.asVoid,
// OpenCode answers only when generation ends; once admitted, the event stream owns the outcome.
Effect.tapError((cause) =>
Deferred.isDoneUnsafe(receipt) ||
abortController.signal.aborted ||
turn.finalized ||
turn.admissionGeneration !== generation
? Effect.void
: finalizeTurn(state, turn, "failed", {
failure: makeProviderFailure({ cause, class: "provider_error" }),
}),
),
Effect.ensuring(
Effect.sync(() => {
commandReceipts.delete(payload.messageID);
controllers.delete(abortController);
if (controllers.size === 0) commandControllers.delete(payload.sessionID);
}),
),
Effect.forkIn(scope),
);
yield* Effect.raceFirst(Fiber.join(request), Deferred.await(receipt)).pipe(
Effect.timeout("10 seconds"),
Effect.catchTags({
TimeoutError: (cause) => {
const error = new OpenCodeRuntime.OpenCodeRuntimeError({
operation: "session.command",
detail: "OpenCode command admission did not complete within 10 seconds.",
cause,
});
abortController.abort();
return finalizeTurn(state, turn, "failed", {
failure: makeProviderFailure({ cause: error, class: "provider_error" }),
}).pipe(Effect.andThen(Effect.fail(error)));
},
}),
);
});
const runtimeSession: ProviderAdapter.ProviderAdapterV2SessionRuntime = {
instanceId: options.instanceId,
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
providerSession: sessionEntity,
events: Stream.fromEffectRepeat(Queue.take(events)),
hasPendingBackgroundWork: Effect.sync(
() =>
busySessionIds.size > 0 ||
Array.from(threads.values()).some((state) => state.wake?.offered === true),
),
ensureThread: Effect.fn("OpencodeAdapter.ensureThread")(
function* (threadInput) {
if (threadInput.existingProviderThread?.nativeThreadRef != null) {
return yield* runtimeSession.resumeThread({
providerThread: threadInput.existingProviderThread,
});
}
const permission = openCodePermissionRules(threadInput.runtimePolicy);
// OpenCode generates a title only when session.create leaves it unset.
const response = yield* sdkCall("session.create", { permission }, () =>
client.session.create({ permission }),
);
const nativeSession = unwrapData("session.create", response);
const createdAt = yield* DateTime.now;
const created = makeProviderThread({
idAllocator,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
appThreadId: threadInput.threadId,
nativeSession,
now: createdAt,
});
const existing = threadInput.existingProviderThread;
const providerThread =
existing === undefined
? created
: {
...existing,
providerSessionId: input.providerSessionId,
nativeThreadRef: created.nativeThreadRef,
nativeConversationHeadRef: created.nativeConversationHeadRef,
status: created.status,
updatedAt: created.updatedAt,
};
registerThread(nativeSession, providerThread, null).permission = permission;
return providerThread;
},
(effect, threadInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterEnsureThreadError({
driver: OPENCODE_PROVIDER,
threadId: threadInput.threadId,
cause,
}),
),
),
),
resumeThread: Effect.fn("OpencodeAdapter.resumeThread")(
function* (threadInput) {
const sessionId = nativeThreadId(threadInput.providerThread);
const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>
client.session.get({ sessionID: sessionId }),
);
const nativeSession = unwrapData("session.get", response);
const resumedAt = yield* DateTime.now;
const providerThread = {
...threadInput.providerThread,
providerSessionId: input.providerSessionId,
status: "idle" as const,
updatedAt: dateTimeFromEpoch(nativeSession.time.updated, resumedAt),
};
const state = registerThread(nativeSession, providerThread, null);
if (threadInput.runtimePolicy !== undefined) {
yield* applyPermissionRules(state, threadInput.runtimePolicy);
}
return providerThread;
},
(effect, threadInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterResumeThreadError({
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
providerThreadId: threadInput.providerThread.id,
cause,
}),
),
),
),
compactThread: (turnInput) =>
runtimeSession.startTurn({
...turnInput,
message: { ...turnInput.message, text: "/compact" },
}),
resumeTurn: (input) => runtimeSession.startTurn(ProviderAdapter.resumeTurnInput(input)),
startTurn: Effect.fn("OpencodeAdapter.startTurn")(
function* (turnInput) {
if (closing || nativeStreamFailure !== null) {
return yield* protocolError(
"OpenCode event stream has ended; reconnect the provider session before starting another turn.",
);
}
const sessionId = nativeThreadId(turnInput.providerThread);
const state = threads.get(sessionId);
if (state === undefined) {
return yield* protocolError(`OpenCode session ${sessionId} is not registered`);
}
if (state.activeTurn !== null) {
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`,
reason: "previous_turn_active",
});
}
const continuation =
turnInput.message.createdBy === "agent" &&
turnInput.message.creationSource === "provider";
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(
turnInput.modelSelection.model,
);
if (parsedModel === null) {
return yield* protocolError(
`OpenCode model '${turnInput.modelSelection.model}' must use provider/model format`,
);
}
yield* applyPermissionRules(state, turnInput.runtimePolicy);
// A continuation admits a wake OpenCode is already running, so it sends no prompt.
const isCompaction =
!continuation &&
turnInput.message.text.trim() === "/compact" &&
turnInput.message.attachments.length === 0;
const parts =
isCompaction || continuation ? [] : yield* resolvePromptParts(turnInput);
const startedAt = yield* DateTime.now;
const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`;
const providerTurnId = idAllocator.derive.providerTurn({
driver: OPENCODE_PROVIDER,
nativeTurnId: syntheticNativeTurnId,
});
const providerTurn: OrchestrationV2ProviderTurn = {
id: providerTurnId,
providerThreadId: turnInput.providerThread.id,
nodeId: turnInput.rootNodeId,
runAttemptId: turnInput.attemptId,
nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"),
ordinal: turnInput.providerTurnOrdinal,
status: "running",
startedAt,
completedAt: null,
};
const admissionMessageId = continuation
? null
: yield* makeOpenCodeMessageId(messageIdClock);
const turn: ActiveOpenCodeTurn = {
isRoot: true,
threadId: turnInput.threadId,
runId: turnInput.runId,
rootNodeId: turnInput.rootNodeId,
appThread: turnInput.appThread,
modelSelection: turnInput.modelSelection,
runtimePolicy: turnInput.runtimePolicy,
providerTurnId,
providerThreadId: turnInput.providerThread.id,
runOrdinal: turnInput.runOrdinal,
startedAt,
itemOrdinals: new Map(),
usage: makeOpenCodeTurnTokenUsageAccumulator(),
parts: new Map(),
partIdsByMessage: new Map(),
toolNamesByCallId: new Map(),
providerTurn,
nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1,
nativeUserMessageId: null,
admissionMessageId,
priorWakePromptIds: new Set(),
priorWakeSettled: null,
interrupted: false,
finalized: false,
contextOverflow: null,
planId: null,
admissionGeneration: state.nextAdmissionGeneration++,
admissionReconciliationGeneration: null,
admissionPending: !isCompaction && !continuation,
admissionAccepted: isCompaction || continuation,
admissionMessageObserved: false,
idleDuringAdmission: false,
admissionUncertain: false,
admissionStatusSequence: 0,
admissionSettled: Deferred.makeUnsafe<void>(),
admissionAbortController: continuation
? null
: // @effect-diagnostics-next-line abortControllerInEffect:off - Turn interruption owns prompt admission cancellation.
new AbortController(),
};
if (turn.admissionMessageId !== null)
turn.usage.promptMessageIds.add(turn.admissionMessageId);
const admissionSettled = turn.admissionSettled;
const admissionAbortController = turn.admissionAbortController;
yield* state.lifecyclePermit.withPermit(
Effect.gen(function* () {
const candidate = state.wake;
if (!continuation && candidate !== null && !candidate.offered) {
// A noReply prompt saves a user message and never runs; OpenCode queues a
// prompt behind a loop that did start, so the foreground submits either way.
const admission = yield* Deferred.await(candidate.admission).pipe(
Effect.timeoutOption("10 seconds"),
);
if (Option.isNone(admission) && state.wake === candidate) state.wake = null;
}
yield* eventPermit.withPermit(
Effect.gen(function* () {
// Do not yield before turn installation; EOF may otherwise finish scanning before registration.
if (closing || nativeStreamFailure !== null) {
return yield* protocolError(
"OpenCode event stream has ended; reconnect the provider session before starting another turn.",
);
}
if (state.activeTurn !== null) {
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`,
reason: "previous_turn_active",
});
}
const wake = state.wake;
if (!continuation) turn.priorWakeSettled = wake?.settled ?? null;
state.wake = null;
state.appThread = turnInput.appThread;
state.activeTurn = turn;
state.providerTurns.set(String(providerTurnId), providerTurn);
yield* emitProviderTurn(state, turn, "running", null);
yield* updateProviderThread(state, {
status: "active",
firstRunOrdinal:
state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal,
lastRunOrdinal: turnInput.runOrdinal,
});
yield* updateProviderSession("running", null);
if (!continuation) {
for (const event of wake?.events ?? []) {
if (
event.type === "message.updated" &&
event.properties.sessionID === sessionId &&
event.properties.info.role === "user"
) {
turn.priorWakePromptIds.add(event.properties.info.id);
}
}
}
// Work held after this turn settles is a later result; it starts its own wake.
yield* Effect.forEach(wake?.events ?? [], (event) =>
(state.activeTurn === turn
? routeEvent(event, continuation ? undefined : sessionId)
: acceptEvent(event)
).pipe(Effect.timeout("10 seconds")),
).pipe(
Effect.onError(() =>
Effect.gen(function* () {
if (state.activeTurn !== turn) return;
nativeStreamFailure = makeProviderFailure({
message:
"OpenCode buffered replay failed; reconnect the provider session.",
class: "transport_error",
});
turn.admissionAbortController?.abort();
yield* Deferred.succeed(admissionSettled, undefined);
yield* updateProviderSession("error", nativeStreamFailure.message);
yield* cleanupSessionWork(state, abortRootSession(state)).pipe(
Effect.ignore({ log: true }),
);
yield* finalizeTurn(state, turn, "failed", {
failure: nativeStreamFailure,
threadDisposition: "broken",
});
}),
),
);
// Stop or a newer turn took the wake first; nothing is left to run.
if (continuation && wake === null)
yield* finalizeTurn(state, turn, "completed");
}),
);
}),
);
if (continuation) return;
if (turn.priorWakeSettled !== null) {
yield* Deferred.await(turn.priorWakeSettled);
turn.priorWakeSettled = null;
if (!turnIsLive(state, turn)) {
yield* Deferred.succeed(admissionSettled, undefined);
return;
}
}
if (isCompaction) {
yield* sdkCall(
"session.summarize",
{ sessionID: sessionId, ...parsedModel, auto: false },
(signal) =>
client.session.summarize(
{ sessionID: sessionId, ...parsedModel, auto: false },
{ signal: AbortSignal.any([signal, admissionAbortController!.signal]) },
),
).pipe(
Effect.tap(() =>
turn.interrupted ||
turn.finalized ||
turn.contextOverflow !== null ||
nativeStreamFailure !== null
? Effect.void
: emitCompactionItem(state, turn),
),
Effect.tap(() =>
finalizeTurn(state, turn, turn.interrupted ? "interrupted" : "completed"),
),
Effect.tapError((cause) =>
finalizeTurn(state, turn, turn.interrupted ? "interrupted" : "failed", {
failure: makeProviderFailure({ cause, class: "provider_error" }),
}),
),
Effect.ensuring(Deferred.succeed(admissionSettled, undefined)),
);
return;
}
yield* submitPrompt(
state,
turn,
{
sessionID: sessionId,
messageID: turn.admissionMessageId!,
model: parsedModel,
...turnPromptOptions(turn),
parts,
},
admissionAbortController!,
turnInput.message.text,
).pipe(
Effect.tapError((cause) =>
admissionAbortController!.signal.aborted
? Effect.void
: finalizeTurn(state, turn, "failed", {
failure: makeProviderFailure({ cause, class: "provider_error" }),
}),
),
Effect.catch((cause) =>
admissionAbortController!.signal.aborted ? Effect.void : Effect.fail(cause),
),
Effect.ensuring(
Effect.all([
Deferred.succeed(admissionSettled, undefined).pipe(Effect.ignore),
Effect.sync(() => {
if (turn.admissionAbortController === admissionAbortController) {
turn.admissionAbortController = null;
}
}),
]).pipe(Effect.asVoid),
),
);
if (turnIsLive(state, turn)) {
const admissionAction = advanceOpenCodePromptAdmission(turn, "accepted");
if (admissionAction === "reconcile-idle") {
yield* reconcilePromptAdmission(state, turn);
}
}
},
(effect, turnInput) =>
Effect.suspend(() => {
const state = threads.get(nativeThreadId(turnInput.providerThread));
const wake =
turnInput.message.createdBy === "agent" &&
turnInput.message.creationSource === "provider"
? state?.wake
: null;
return effect.pipe(
Effect.onError(() =>
state !== undefined && wake != null ? stopWake(state, wake) : Effect.void,
),
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterTurnStartError({
driver: OPENCODE_PROVIDER,
threadId: turnInput.threadId,
providerThreadId: turnInput.providerThread.id,
runId: turnInput.runId,
cause,
}),
),
);
}),
),
steerTurn: Effect.fn("OpencodeAdapter.steerTurn")(
function* (steerInput) {
const sessionId = nativeThreadId(steerInput.providerThread);
const state = threads.get(sessionId);
const turn = state?.activeTurn;
if (
state === undefined ||
turn === undefined ||
turn === null ||
turn.providerTurnId !== steerInput.providerTurnId ||
turn.interrupted
) {
return yield* protocolError(
`OpenCode turn ${steerInput.providerTurnId} is not active`,
);
}
const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model);
if (parsedModel === null) {
return yield* protocolError(
`OpenCode model '${turn.modelSelection.model}' must use provider/model format`,
);
}
const text = (yield* providerMessageTextWithAttachmentPaths({
text: steerInput.message.text,
attachments: steerInput.message.attachments,
resolveAttachmentPath: host.resolveAttachmentPath,
resolveExtractedTextPath: host.resolveExtractedTextPath,
})).trim();
if (state.activeTurn !== turn || turn.interrupted || turn.finalized) {
return yield* protocolError(
`OpenCode turn ${steerInput.providerTurnId} is not active`,
);
}
const files = OpenCodeRuntime.toOpenCodeFileParts({
attachments: steerInput.message.attachments,
resolveAttachmentPath: host.resolveAttachmentPath,
});
if (text.length === 0 && files.length === 0) {
return yield* protocolError("OpenCode steering requires text or an attachment");
}
const parts = [
...(text.length === 0 ? [] : [{ type: "text" as const, text }]),
...files,
];
const admissionMessageId = yield* makeOpenCodeMessageId(messageIdClock);
while (turn.admissionAbortController !== null) {
const pendingAdmission = turn.admissionSettled;
yield* Deferred.await(pendingAdmission);
// Another waiting steer may have claimed admission first.
if (turn.admissionSettled === pendingAdmission) break;
}
if (state.activeTurn !== turn || turn.finalized || turn.interrupted) {
return yield* protocolError(
`OpenCode turn ${steerInput.providerTurnId} is not active`,
);
}
// A retry of a steer whose earlier attempt may have reached OpenCode stays uncertain.
if (!turn.admissionPending) turn.admissionUncertain = false;
turn.admissionGeneration = state.nextAdmissionGeneration++;
turn.admissionMessageId = admissionMessageId;
turn.admissionPending = true;
turn.admissionAccepted = false;
turn.admissionMessageObserved = false;
turn.idleDuringAdmission = false;
turn.admissionSettled = Deferred.makeUnsafe<void>();
// @effect-diagnostics-next-line abortControllerInEffect:off - Steering replaces the admission request independently of this command fiber.
turn.admissionAbortController = new AbortController();
if (turn.admissionMessageId !== null)
turn.usage.promptMessageIds.add(turn.admissionMessageId);
const admissionSettled = turn.admissionSettled;
const admissionAbortController = turn.admissionAbortController;
const generation = turn.admissionGeneration;
const acceptAdmission = Effect.suspend(() =>
state.activeTurn === turn &&
!turn.finalized &&
!turn.interrupted &&
advanceOpenCodePromptAdmission(turn, "accepted") === "reconcile-idle"
? reconcilePromptAdmission(state, turn)
: Effect.void,
);
yield* submitPrompt(
state,
turn,
{
sessionID: sessionId,
messageID: turn.admissionMessageId,
model: parsedModel,
...turnPromptOptions(turn),
parts,
},
admissionAbortController!,
steerInput.message.text,
).pipe(
Effect.tapError((error) => {
if (!promptAdmissionIsCurrent(state, turn, generation)) return Effect.void;
if (isOpenCodePromptRejected(error) && !turn.admissionUncertain) {
return reconcilePromptAdmission(state, turn);
}
// OpenCode may have taken this or an earlier attempt: wait for its output or Stop.
turn.admissionUncertain = true;
return acceptAdmission;
}),
Effect.ensuring(
Effect.all([
Deferred.succeed(admissionSettled, undefined).pipe(Effect.ignore),
Effect.sync(() => {
if (turn.admissionAbortController === admissionAbortController) {
turn.admissionAbortController = null;
}
}),
]).pipe(Effect.asVoid),
),
);
yield* acceptAdmission;
},
(effect, steerInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterSteerRunError({
driver: OPENCODE_PROVIDER,
providerThreadId: steerInput.providerThread.id,
providerTurnId: steerInput.providerTurnId,
cause,
}),
),
),
),
interruptTurn: Effect.fn("OpencodeAdapter.interruptTurn")(
function* (interruptInput) {
const sessionId = nativeThreadId(interruptInput.providerThread);
const state = threads.get(sessionId);
if (state === undefined) {
if (interruptInput.requestRuntimeRestart !== true)
return yield* protocolError(`OpenCode session ${sessionId} is not registered`);
for (const controller of commandControllers.get(sessionId) ?? [])
controller.abort();
const descendants = yield* abortDescendants(sessionId).pipe(Effect.result);
yield* interruptLaunchedSubagents(sessionId);
if (descendants._tag === "Failure") return yield* descendants.failure;
return;
}
return yield* state.lifecyclePermit.withPermit(
Effect.gen(function* () {
const turn = state.activeTurn;
if (
(turn === undefined || turn === null) &&
interruptInput.requestRuntimeRestart === true
) {
for (const controller of commandControllers.get(sessionId) ?? [])
controller.abort();
const wake = state.wake;
if (wake !== null) yield* cancelWake(state, wake);
else yield* cleanupSessionWork(state, Effect.void);
return;
}
if (
turn === undefined ||
turn === null ||
turn.providerTurnId !== interruptInput.providerTurnId
) {
return yield* protocolError(
`OpenCode turn ${interruptInput.providerTurnId} is not active`,
);
}
turn.interrupted = true;
for (const controller of commandControllers.get(sessionId) ?? [])
controller.abort();
const admissionWasPending = turn.admissionPending;
cancelOpenCodePromptAdmission(turn, state!.nextAdmissionGeneration++);
turn.admissionAbortController?.abort();
if (turn.priorWakeSettled !== null)
yield* Deferred.succeed(turn.priorWakeSettled, undefined);
if (admissionWasPending) {
// Local admission timeout must not block the server-side abort.
yield* Deferred.await(turn.admissionSettled).pipe(
Effect.timeout("10 seconds"),
Effect.ignore,
);
}
yield* cleanupSessionWork(
state,
sdkCall("session.abort", { sessionID: sessionId }, (signal) =>
client.session.abort({ sessionID: sessionId }, { signal }),
).pipe(
Effect.timeoutOrElse({
duration: OPENCODE_STOP_CONFIRM_TIMEOUT_MS,
orElse: () =>
Effect.fail(
new ProviderAdapter.ProviderAdapterInterruptTimeoutError({
driver: OPENCODE_PROVIDER,
providerThreadId: interruptInput.providerThread.id,
providerTurnId: interruptInput.providerTurnId,
timeoutMs: OPENCODE_STOP_CONFIRM_TIMEOUT_MS,
}),
),
}),
Effect.catch((cause) =>
turn.finalized
? Effect.void
: Effect.suspend(() => {
turn.interrupted = false;
return Effect.fail(cause);
}),
),
),
);
}),
);
},
(effect, interruptInput) =>
effect.pipe(
Effect.mapError((cause) =>
cause._tag === "ProviderAdapterInterruptTimeoutError"
? cause
: new ProviderAdapter.ProviderAdapterInterruptError({
driver: OPENCODE_PROVIDER,
providerThreadId: interruptInput.providerThread.id,
providerTurnId: interruptInput.providerTurnId,
cause,
}),
),
),
),
respondToRuntimeRequest: Effect.fn("OpencodeAdapter.respondToRuntimeRequest")(
function* (requestInput) {
const pending = pendingRequests.get(String(requestInput.requestId));
if (pending === undefined) {
return yield* protocolError(
`No pending OpenCode request ${requestInput.requestId}`,
);
}
if (pending.question !== undefined) {
if (requestInput.answers === undefined) {
return yield* protocolError(
`OpenCode question request ${requestInput.requestId} requires answers`,
);
}
const answers = OpenCodeRuntime.toOpenCodeQuestionAnswers(
pending.question,
requestInput.answers,
);
yield* sdkCall(
"question.reply",
{ requestID: pending.nativeRequestId, answers },
(signal) =>
client.question.reply(
{
requestID: pending.nativeRequestId,
answers,
},
{ signal },
),
).pipe(Effect.timeout("10 seconds"));
return;
}
if (requestInput.decision === undefined) {
return yield* protocolError(
`OpenCode approval request ${requestInput.requestId} requires a decision`,
);
}
const reply = OpenCodeRuntime.toOpenCodePermissionReply(requestInput.decision);
yield* sdkCall(
"permission.reply",
{ requestID: pending.nativeRequestId, reply },
(signal) =>
client.permission.reply(
{
requestID: pending.nativeRequestId,
reply,
},
{ signal },
),
).pipe(Effect.timeout("10 seconds"));
},
(effect, requestInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({
driver: OPENCODE_PROVIDER,
requestId: requestInput.requestId,
cause,
}),
),
),
),
readThreadSnapshot: (snapshotInput) =>
readSnapshot(snapshotInput.providerThread).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({
driver: OPENCODE_PROVIDER,
providerThreadId: snapshotInput.providerThread.id,
cause,
}),
),
),
rollbackThread: Effect.fn("OpencodeAdapter.rollbackThread")(
function* (rollbackInput) {
const sessionId = nativeThreadId(rollbackInput.providerThread);
const state = threads.get(sessionId);
if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
return yield* protocolError(
`Cannot roll back OpenCode thread ${rollbackInput.providerThread.id} while a turn is active`,
);
}
const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () =>
client.session.messages({ sessionID: sessionId }),
);
const messages = unwrapData("session.messages", response);
let boundaryMessageId: string | undefined;
if (rollbackInput.target.type === "thread_start") {
boundaryMessageId = messages.find(({ info }) => info.role === "user")?.info.id;
} else {
boundaryMessageId = openCodeBoundaryAfterProviderTurn(
rollbackInput.providerThreadTurns,
rollbackInput.target.providerTurn.id,
);
}
let retainedThread = rollbackInput.providerThread;
if (boundaryMessageId !== undefined) {
const boundaryIndex = messages.findIndex(
({ info }) => info.id === boundaryMessageId,
);
if (boundaryIndex < 0)
return yield* protocolError(
"The OpenCode rewind boundary is no longer available.",
);
const fork = unwrapData(
"session.fork",
yield* sdkCall(
"session.fork",
{ sessionID: sessionId, messageID: boundaryMessageId },
() =>
client.session.fork({ sessionID: sessionId, messageID: boundaryMessageId }),
),
);
const retained = unwrapData(
"session.messages",
yield* sdkCall("session.messages", { sessionID: fork.id }, () =>
client.session.messages({ sessionID: fork.id }),
),
);
if (retained.length !== boundaryIndex)
return yield* protocolError(
"OpenCode did not preserve the requested rewind boundary.",
);
yield* sdkCall("session.update", { sessionID: fork.id }, () =>
client.session.update({
sessionID: fork.id,
permission: openCodePermissionRules(input.runtimePolicy),
}),
);
retainedThread = {
...rollbackInput.providerThread,
nativeThreadRef: providerRef(fork.id),
};
registerThread(fork, retainedThread, state?.appThread ?? null);
}
const snapshot = yield* readSnapshot(retainedThread);
return {
...snapshot,
providerThread: {
...snapshot.providerThread,
nativeConversationHeadRef:
rollbackInput.target.type === "provider_turn"
? rollbackInput.target.providerTurn.nativeTurnRef
: null,
},
};
},
(effect, rollbackInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterRollbackThreadError({
driver: OPENCODE_PROVIDER,
providerThreadId: rollbackInput.providerThread.id,
checkpointId: rollbackInput.target.checkpointId,
cause,
}),
),
),
),
forkThread: Effect.fn("OpencodeAdapter.forkThread")(
function* (forkInput) {
const sourceSessionId = nativeThreadId(forkInput.sourceProviderThread);
const sourceState = threads.get(sourceSessionId);
if (sourceState?.activeTurn !== null && sourceState?.activeTurn !== undefined) {
return yield* protocolError(
`Cannot fork OpenCode thread ${forkInput.sourceProviderThread.id} while a turn is active`,
);
}
let boundaryMessageId: string | undefined;
if (forkInput.providerTurnId !== undefined) {
const sourceTurns = forkInput.sourceProviderTurns ?? [];
const selected = sourceTurns.find((turn) => turn.id === forkInput.providerTurnId);
if (selected === undefined) {
return yield* protocolError(
`OpenCode fork boundary turn ${forkInput.providerTurnId} was not found`,
);
}
boundaryMessageId = openCodeBoundaryAfterProviderTurn(sourceTurns, selected.id);
}
const response = yield* sdkCall(
"session.fork",
{
sessionID: sourceSessionId,
...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }),
},
() =>
client.session.fork({
sessionID: sourceSessionId,
...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }),
}),
);
const nativeSession = unwrapData("session.fork", response);
const forkedAt = yield* DateTime.now;
const providerThread = makeProviderThread({
idAllocator,
providerInstanceId: options.instanceId,
providerSessionId: input.providerSessionId,
appThreadId: forkInput.targetThreadId,
...(forkInput.ownerNodeId === undefined
? {}
: { ownerNodeId: forkInput.ownerNodeId }),
nativeSession,
forkedFrom: {
providerThreadId: forkInput.sourceProviderThread.id,
...(forkInput.providerTurnId === undefined
? {}
: { providerTurnId: forkInput.providerTurnId }),
},
now: forkedAt,
});
registerThread(nativeSession, providerThread, null);
return providerThread;
},
(effect, forkInput) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterForkThreadError({
driver: OPENCODE_PROVIDER,
providerThreadId: forkInput.sourceProviderThread.id,
cause,
}),
),
),
),
};
return runtimeSession;
},
(effect, input) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapter.ProviderAdapterOpenSessionError({
driver: OPENCODE_PROVIDER,
providerSessionId: input.providerSessionId,
cause,
}),
),
),
),
});
});
export type OpenCodeAdapterV2DriverEnv =
| OpenCodeRuntime.OpenCodeRuntime
| IdAllocator.IdAllocatorV2
| McpProviderSessions.McpProviderSessions
| ProviderEventLoggers.ProviderEventLoggers
| ProviderHost.ProviderHost;
export const OpenCodeAdapterV2Driver: ProviderAdapterDriver<
OpenCodeSettings,
OpenCodeAdapterV2DriverEnv
> = {
driverKind: OPENCODE_PROVIDER,
configSchema: OpenCodeSettings,
defaultConfig: (): OpenCodeSettings => DEFAULT_OPENCODE_SETTINGS,
create: Effect.fn("OpenCodeAdapterV2Driver.create")(
function* (input: ProviderAdapterDriverCreateInput<OpenCodeSettings>) {
const hostEnvironment = yield* HostProcess.Environment;
const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
return yield* makeOpenCodeAdapterV2({
instanceId: input.instanceId,
settings: { ...input.config, enabled: input.enabled },
environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment),
...(providerEventLoggers.native === undefined
? {}
: { nativeEventLogger: providerEventLoggers.native }),
});
},
(effect, input) =>
effect.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterDriverCreateError({
driver: OPENCODE_PROVIDER,
instanceId: input.instanceId,
detail: "Failed to create OpenCode v2 adapter.",
cause,
}),
),
),
),
};