import * as NodeURL from "node:url";
import {
AbsolutePath,
Agent,
Form,
Location,
Model,
Permission,
Provider,
Session,
SessionMessage,
Skill,
type OpenCodeEvent,
} from "@opencode/client/effect";
import { Mcp } from "@opencode/schema/mcp";
import {
isOrchestrationV2WorkActive,
type ChatAttachment,
type OrchestrationV2AppThread,
type OrchestrationV2ConversationMessage,
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
type OrchestrationV2RuntimeRequest,
type OrchestrationV2Subagent,
type OrchestrationV2TurnItem,
type OrchestrationV2UserInputQuestion,
type MessageId,
type ModelSelection,
type ProviderApprovalDecision,
type ProviderInstanceId,
type RunId,
type RuntimeRequestId,
} from "@t3tools/contracts";
import type * as Cause from "effect/Cause";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Digest from "effect/crypto/Digest";
import * as Effect from "effect/Effect";
import * as Hex from "effect/encoding/Hex";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Queue from "effect/Queue";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as Stream from "effect/Stream";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as OpenCode2Client from "./OpenCode2Client.ts";
import * as OpenCode2Server from "./OpenCode2Server.ts";
import * as OpenCodeRuntime from "../OpenCodeRuntime.ts";
import { readableProviderErrorMessage } from "../providerErrorMessage.ts";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions";
import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions";
import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
import * as KeyedLock from "@t3tools/shared/KeyedLock";
import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";
import { causeErrorTag } from "@t3tools/shared/observability";
import {
isProviderNativeImageAttachment,
providerMessageTextWithAttachmentPaths,
} from "@t3tools/provider-core/server/attachmentPrompt";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import {
backgroundWorkNotification,
type BackgroundWorkReport,
} from "@t3tools/provider-core/server/notification";
import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests";
import {
makeProviderFailure,
makeProviderRetryTurnItem,
} from "@t3tools/provider-core/server/failure";
import {
makeSubagentChildThread,
makeSubagentConversationArtifacts,
subagentThreadTitle,
} from "@t3tools/provider-core/server/subagentProjection";
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition";
import { OPENCODE_PROVIDER, openCodePermissionRequestKind } from "../adapter.ts";
import { openCodeCommandFailed, openCodeToolTurnItem } from "../toolItems.ts";
const OpenCode2ProviderCapabilities = {
sessions: {
supportsMultipleProviderThreadsPerSession: true,
supportsModelSwitchInSession: true,
supportsProviderSwitchingViaHandoff: true,
supportsRuntimeModeSwitchInSession: true,
pendingRequestsSurviveRestart: false,
},
threads: {
canCreateEmptyThread: true,
canReadThreadSnapshot: true,
canRollbackThread: true,
canForkThread: true,
canForkFromTurn: true,
canForkFromSubagentThread: false,
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: false,
streamsPlanText: false,
emitsMessageCompleted: true,
},
tools: {
exposesToolItemIds: true,
emitsToolStarted: true,
emitsToolCompleted: true,
emitsToolOutput: true,
supportsMcpTools: false,
supportsDynamicToolCallbacks: false,
},
approvals: {
supportsCommandApproval: true,
supportsFileReadApproval: true,
supportsFileChangeApproval: true,
supportsApplyPatchApproval: true,
approvalsHaveNativeRequestIds: true,
approvalCallbacksAreLiveOnly: true,
approvalsCanOriginateFromSubagents: true,
},
planning: {
emitsPlanUpdated: false,
emitsTodoList: false,
emitsProposedPlan: false,
supportsStructuredQuestions: true,
planDeltasHaveItemIds: false,
},
subagents: {
supportsSubagents: true,
exposesSubagentThreadIds: true,
emitsSubagentLifecycle: true,
canWaitForSubagents: true,
canCloseSubagents: false,
canForkSubagentThread: false,
},
context: {
acceptsSystemContext: false,
acceptsDeveloperContext: false,
acceptsSyntheticUserContext: true,
canGenerateSummaries: false,
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 EventOf<T extends OpenCodeEvent["type"]> = Extract<OpenCodeEvent, { readonly type: T }>;
type Tokens = EventOf<"session.step.ended">["data"]["tokens"];
interface TurnOwner {
readonly appThread: OrchestrationV2AppThread;
readonly threadId: OrchestrationV2AppThread["id"];
readonly runId: RunId | null;
readonly runOrdinal: number;
readonly rootNodeId: ProviderAdapter.ProviderAdapterV2TurnInput["rootNodeId"];
readonly modelSelection: ModelSelection;
readonly runtimePolicy: Pick<ProviderAdapter.ProviderAdapterV2RuntimePolicy, "cwd">;
}
interface ActiveTurn {
readonly input: TurnOwner;
providerTurn: OrchestrationV2ProviderTurn;
readonly texts: Map<string, OpenBlock>;
readonly tools: Map<string, { readonly name: string; input: Record<string, unknown> }>;
readonly startedAt: Map<string, DateTime.Utc>;
readonly ordinals: Map<string, number>;
nextOrdinal: number;
readonly usage: {
input: number;
cached: number;
cacheWrite: number;
output: number;
reasoning: number;
};
// Steps OpenCode started; a step that ends without tokens leaves the total partial.
startedSteps: number;
// A reconnect dropped events, so steps may have ended unseen.
missedEvents: boolean;
steps: number;
readonly models: Set<string>;
lastStep: Tokens | undefined;
before: string | null | undefined;
compaction: { readonly nativeId: string; readonly startedAt: DateTime.Utc } | undefined;
compactions: number;
retry:
| {
readonly retry: OrchestrationV2ProviderRetry;
readonly failure: OrchestrationV2ProviderFailure;
readonly startedAt: DateTime.Utc;
}
| undefined;
interrupted: boolean;
unsent: boolean;
readonly steers: Set<string>;
readonly settledInbox: Set<string>;
heldEnd: TurnTerminal | undefined;
awaitingStart: boolean;
/** Scope child tool IDs because model-generated IDs can repeat parent IDs. */
readonly scope: string;
usedSubagents: boolean;
}
interface SubagentCall {
readonly toolId: string;
readonly nativeId: string;
readonly state: ThreadState;
readonly turn: ActiveTurn;
readonly ordinal: number;
readonly startedAt: DateTime.Utc;
prompt: string;
title: string | null;
agent: string | undefined;
model: string | null;
background: boolean;
joined: SubagentCall | undefined;
child: ThreadState | undefined;
status: OrchestrationV2Subagent["status"];
result: string | null;
completedAt: DateTime.Utc | null;
}
interface Wake {
readonly messageId: MessageId | undefined;
readonly events: Array<OpenCode2Client.OpenCode2StreamEvent>;
running: boolean;
readonly reports: Array<BackgroundWorkReport>;
readonly detail: string | null;
dropped: boolean;
readonly after: string | undefined;
readonly first: string | undefined;
readonly children: Set<string>;
}
interface OpenBlock {
readonly block: { readonly assistantMessageID: string; readonly ordinal: number };
readonly kind: "text" | "reasoning";
readonly startedAt: DateTime.Utc;
text: string;
}
interface ThreadState {
readonly sessionId: string;
providerThread: OrchestrationV2ProviderThread;
publishedBackgroundWork?: boolean;
readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>;
active: ActiveTurn | undefined;
model: ModelRef | undefined;
/** Locally ended but possibly live; consume its next execution end without settling a new turn. */
unsettled: boolean;
/** A late first start belongs to the failed prompt; only a subsequent start proves a lost end. */
unsettledStarted: boolean;
directory: string;
agent: string;
title: string | undefined;
rules: ReadonlyArray<Rule> | undefined;
policy: RulesPolicy;
readonly grants: Array<Rule>;
readonly calls: Map<string, SubagentCall>;
subagent:
| {
call: SubagentCall;
readonly appThread: OrchestrationV2AppThread;
turns: number;
prompt: string | undefined;
queued: string | undefined;
}
| undefined;
readonly wakes: Array<Wake>;
readonly reports: Map<
string,
{
readonly inboxId: string;
readonly childId: string;
readonly report: BackgroundWorkReport;
readonly text: string;
}
>;
readonly stoppedChildren: Set<string>;
readonly strandedSteers: Set<string>;
mcp:
| { readonly name: string; readonly directory: string; readonly credential: string }
| undefined;
instructions: string | undefined;
}
type TurnTerminal =
| { readonly status: "completed" | "interrupted" }
| { readonly status: "failed"; readonly failure: ReturnType<typeof makeProviderFailure> };
type Rule = Permission.Rule;
type RulesPolicy = Pick<
ProviderAdapter.ProviderAdapterV2RuntimePolicy,
"runtimeMode" | "interactionMode"
>;
type NativeForm = EventOf<"form.created">["data"]["form"];
interface PendingRequest {
readonly request: OrchestrationV2RuntimeRequest;
readonly item: OrchestrationV2TurnItem;
readonly node: OrchestrationV2ExecutionNode;
readonly state: ThreadState;
readonly turn: ActiveTurn;
readonly sessionId: string;
answering: boolean;
readonly native:
| {
readonly type: "permission";
readonly id: string;
readonly action: string;
readonly resources: ReadonlyArray<string>;
readonly save: ReadonlyArray<string>;
}
| { readonly type: "form"; readonly id: string; readonly form: NativeForm };
}
const rule = (action: string, effect: Rule["effect"]): Rule => ({ action, resource: "*", effect });
/** OpenCode hides tools for names over 64 chars and rejects names over 100; hash long thread IDs. */
export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId: string) {
const name = `t3-code-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`;
if (name.length <= 64) return name;
const crypto = yield* Digest.Digest;
const digest = yield* crypto
.digest(Digest.sha256, new TextEncoder().encode(threadId))
.pipe(Effect.orDie);
return `t3-code-${Hex.encode(digest).slice(0, 16)}`;
});
// Last match wins: deny all threads' T3 servers, then allow only this thread's.
const mcpRules = (mcpServerName: string | null): ReadonlyArray<Rule> =>
mcpServerName === null
? []
: [
{ action: "t3-code-*", resource: "*", effect: "deny" },
{ action: `${mcpServerName}_*`, resource: "*", effect: "allow" },
];
const sessionRules = (
policy: RulesPolicy,
paths: ReadonlyArray<Rule>,
grants: ReadonlyArray<Rule>,
mcpServerName: string | null,
): ReadonlyArray<Rule> => [
...(policy.runtimeMode === "full-access"
? [rule("*", "allow")]
: [
rule("shell", "ask"),
rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"),
rule("external_directory", "ask"),
]),
...grants,
// Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read.
...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []),
...paths,
...mcpRules(mcpServerName),
];
const sameRules = (left: ReadonlyArray<Rule> | undefined, right: ReadonlyArray<Rule>) =>
left?.length === right.length &&
left.every(
(entry, index) =>
entry.action === right[index]?.action &&
entry.resource === right[index]?.resource &&
entry.effect === right[index]?.effect,
);
// Rejection without a message stops the whole execution, meaning Cancel.
const DECLINED = "The user declined this request.";
// Steer before decline; otherwise the model sees only Unable to execute command and retries.
const declinedNote = (action: string, resources: ReadonlyArray<string>) =>
`The user declined the ${action} request${resources.length === 0 ? "" : ` (${resources.join(", ")})`}. Do not retry it; continue without it or ask the user how to proceed.`;
const sessionGrantLabel = (action: string, save: ReadonlyArray<string>) =>
save.every((pattern) => pattern === "*")
? `Allow every ${action} request this session`
: `Allow ${save.join(", ")} this session`;
const text = (value: string | undefined, fallback: string) => value?.trim() || fallback;
const formQuestions = (
form: NativeForm,
):
| { readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion> }
| { readonly unsupported: string } => {
const questions: Array<OrchestrationV2UserInputQuestion> = [];
for (const [index, field] of form.fields.entries()) {
if (field.type === "external") return { unsupported: "a link to open" };
if (field.type !== "string" && field.type !== "multiselect") {
return { unsupported: `a ${field.type} value` };
}
if (field.hidden === true) return { unsupported: "a hidden field" };
if ((field.when?.length ?? 0) > 0) return { unsupported: "a field that depends on another" };
const header = text(field.title, `Question ${index + 1}`);
const options = (field.options ?? []).map((option) => {
const label = text(option.label, text(option.value, "Option"));
return { label, description: text(option.description, label), value: option.value };
});
questions.push({
id: field.key,
header,
question: text(field.description, header),
options,
multiSelect: field.type === "multiselect",
allowCustomAnswer: field.custom === true || options.length === 0,
});
}
return { questions };
};
const formAnswer = (form: NativeForm, answers: Readonly<Record<string, unknown>>) => {
const answer: Record<string, string | ReadonlyArray<string>> = {};
for (const field of form.fields) {
const raw = answers[field.key];
const values = (Array.isArray(raw) ? raw : [raw]).filter(
(value): value is string => typeof value === "string" && value.trim().length > 0,
);
if (values.length > 0) {
answer[field.key] = field.type === "multiselect" ? values : values.join(", ");
}
}
return answer;
};
const approves = (decision: ProviderApprovalDecision) =>
decision === "accept" || decision === "acceptForSession" || decision === "acceptAlways";
const permissionGone = {
PermissionNotFoundError: () => Effect.void,
SessionNotFoundError: () => Effect.void,
};
const formGone = {
FormNotFoundError: () => Effect.void,
FormAlreadySettledError: () => Effect.void,
SessionNotFoundError: () => Effect.void,
};
const agentPaths = (rules: ReadonlyArray<Rule>) =>
rules.filter(
(entry) =>
entry.effect === "allow" &&
entry.resource !== "*" &&
(entry.action === "edit" || entry.action === "external_directory"),
);
const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({
driver: OPENCODE_PROVIDER,
nativeId,
strength,
});
const sessionIdOf = (providerThread: OrchestrationV2ProviderThread) => {
const nativeId = providerThread.nativeThreadRef?.nativeId;
return nativeId === undefined || nativeId === null
? Effect.fail(
new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail: `Provider thread ${providerThread.id} has no OpenCode session`,
}),
)
: Effect.succeed(nativeId);
};
const textOf = (content: ReadonlyArray<{ readonly type: string; readonly text?: string }>) =>
content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n");
const stringField = (record: Readonly<Record<string, unknown>> | undefined, key: string) => {
const value = record?.[key];
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
};
const reportOutcome = (state: string | undefined) =>
state === "completed"
? ("completed" as const)
: state === "error"
? ("failed" as const)
: state === "cancelled"
? ("cancelled" as const)
: ("unknown" as const);
const subagentOutput = (text: string) =>
/^<subagent\b[^>]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text;
const isContinuation = (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) =>
turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider";
const wakeTurnId = (sessionId: string, attemptId: string) => `${sessionId}:wake:${attemptId}`;
const isWakeTurn = (turn: OrchestrationV2ProviderTurn) =>
turn.nativeTurnRef?.nativeId?.includes(":wake:") === true;
// OpenCode's claude-agent reports a spent Claude plan as provider.unknown with Claude's own text.
const claudeUsageLimit = (message: string | undefined) =>
message !== undefined && /^You've hit your [^\n·]*\blimit\b/.test(message)
? { resetAt: /\bResets at (\d{4}-\d\d-\d\dT[\d:.]+Z)\.?\s*$/.exec(message)?.[1] ?? null }
: undefined;
const INTERRUPT_TIMEOUT = "10 seconds";
const INSTRUCTIONS_KEY = "t3-code";
const RECONNECT_ATTEMPTS = 5;
const RECONNECT_DELAY = "2 seconds";
const RECONCILE_TIMEOUT = "15 seconds";
const RECONNECT_WAIT = "30 seconds";
const LOST_BACKGROUND =
"T3 Code lost its connection to OpenCode while this subagent ran, so its result is not shown.";
const INVENTORY_TIMEOUT = "5 seconds";
const ACTIVE_CHECK_TIMEOUT = "5 seconds";
// Other failures may still have admitted the prompt.
const CLEAR_PROMPT_REJECTIONS: ReadonlySet<string> = new Set([
"InvalidRequestError",
"ConflictError",
"UnauthorizedError",
"CommandNotFoundError",
"SkillNotFoundError",
]);
export const OPENCODE_2_STILL_STOPPING =
"OpenCode is still stopping the previous turn. Send the message again in a moment.";
const REQUEST_REPLY_TIMEOUT = "10 seconds";
const deliver = <E>(answer: Effect.Effect<void, E>) =>
answer.pipe(
Effect.retry({ times: 1 }),
Effect.timeout(REQUEST_REPLY_TIMEOUT),
Effect.exit,
Effect.map(Exit.isSuccess),
);
type ModelRef = ReturnType<typeof Model.Ref.make>;
// msg_ IDs cannot cross sessions; include session identity because T3 IDs repeat across environments.
// Pre-acknowledgement IDs also establish fork/rollback boundaries.
const turnPromptId = (sessionId: string, attemptId: string) =>
SessionMessage.ID.make(`msg_t3_turn_${sessionId}:${attemptId}`);
const steerPromptId = (sessionId: string, messageId: string) =>
SessionMessage.ID.make(`msg_t3_steer_${sessionId}:${messageId}`);
const promptOf = (turn: OrchestrationV2ProviderTurn) => {
const nativeId = turn.nativeTurnRef?.nativeId;
return nativeId?.startsWith("msg_") === true ? nativeId : undefined;
};
const boundaryAfter = (
turns: ReadonlyArray<OrchestrationV2ProviderTurn>,
providerThreadId: OrchestrationV2ProviderThread["id"],
kept: OrchestrationV2ProviderTurn | undefined,
prompts: ReadonlySet<string>,
) => {
const later = turns
.filter(
(turn) =>
turn.providerThreadId === providerThreadId &&
(kept === undefined || turn.ordinal > kept.ordinal),
)
.toSorted((left, right) => left.ordinal - right.ordinal);
if (later.some((turn) => promptOf(turn) === undefined && !isWakeTurn(turn))) {
return Effect.fail(
new ProviderAdapter.ProviderAdapterProtocolError({
driver: OPENCODE_PROVIDER,
detail:
"This OpenCode conversation has turns from an earlier T3 Code version, so it can't be cut there.",
}),
);
}
return Effect.succeed(
later.map(promptOf).find((messageId) => messageId !== undefined && prompts.has(messageId)) ??
null,
);
};
const isProviderAdapterError = Schema.is(ProviderAdapter.ProviderAdapterV2Error);
const modelRef = (selection: ProviderAdapter.ProviderAdapterV2TurnInput["modelSelection"]) => {
const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(selection.model);
if (parsed === null) return undefined;
const variant = getModelSelectionStringOptionValue(selection, "variant");
return Model.Ref.make({
providerID: Provider.ID.make(parsed.providerID),
id: Model.ID.make(parsed.modelID),
...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }),
});
};
const malformedModel = (model: string) =>
`OpenCode model '${model}' must use provider/model format`;
const sameModel = (left: ModelRef, right: ModelRef | undefined) =>
left.providerID === right?.providerID &&
left.id === right?.id &&
(left.variant ?? "default") === (right?.variant ?? "default");
const agentFor = (input: ProviderAdapter.ProviderAdapterV2TurnInput) =>
input.runtimePolicy.interactionMode === "plan" ? "plan" : "build";
const commandOf = (text: string) => {
const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text.trim());
return match === null ? undefined : { name: match[1]!, text: match[2] ?? "" };
};
const skillMentions = (text: string) => [
...new Set([...text.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => match[2] ?? [])),
];
const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) => {
// A step whose start was missed, in a reconnect gap or as an unreadable event, ran on an unreported model.
const models =
turn.models.size === 0 || turn.missedEvents || turn.steps > turn.startedSteps
? {}
: { models: [...turn.models] };
return turn.steps === 0
? {
usageScope: "main_agent" as const,
usageStatus: "unavailable" as const,
hasSubagents: turn.usedSubagents,
...models,
}
: {
...models,
usageScope: "main_agent" as const,
usageStatus:
status === "completed" && !turn.missedEvents && turn.steps >= turn.startedSteps
? ("complete" as const)
: ("partial" as const),
inputTokens: turn.usage.input,
cachedInputTokens: turn.usage.cached,
cacheCreationTokens: turn.usage.cacheWrite,
outputTokens: turn.usage.output,
reasoningTokens: turn.usage.reasoning,
hasSubagents: turn.usedSubagents,
};
};
export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: ProviderInstanceId) {
const server = yield* OpenCode2Server.OpenCode2Server;
const idAllocator = yield* IdAllocator.IdAllocatorV2;
const host = yield* ProviderHost.ProviderHost;
const mcpSessions = yield* McpProviderSessions.McpProviderSessions;
const fileSystem = yield* FileSystem.FileSystem;
const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests;
const crypto = yield* Digest.Digest;
const driver = OPENCODE_PROVIDER;
const mcpServerNameFor = (threadId: string) =>
t3McpServerName(threadId).pipe(Effect.provideService(Digest.Digest, crypto));
const borrow = Effect.gen(function* () {
const lent = yield* Deferred.make<
OpenCode2Server.OpenCode2Connection,
OpenCodeRuntime.OpenCodeRuntimeError
>();
yield* server
.withConnection((connection) =>
Deferred.succeed(lent, connection).pipe(Effect.andThen(Effect.never)),
)
.pipe(
Effect.catch((error) => Deferred.fail(lent, error)),
Effect.forkScoped,
);
return yield* Deferred.await(lent);
});
const openSession = Effect.fn("OpenCode2Adapter.openSession")(function* (
input: Parameters<ProviderAdapter.ProviderAdapterV2["Service"]["openSession"]>[0],
initial: {
readonly connection: OpenCode2Server.OpenCode2Connection;
readonly scope: Scope.Closeable;
},
) {
let connection = initial.connection;
let client = connection.client;
const sessionScope = yield* Effect.scope;
// Project config changes model limits; key by directory because this runtime serves all instance threads.
const contextWindows = new Map<string, Map<string, number>>();
const directoryOf = (cwd: string | null | undefined) => cwd ?? host.paths.cwd;
const windowOf = (cwd: string | null | undefined, model: string) =>
contextWindows.get(directoryOf(cwd))?.get(model);
const now = yield* DateTime.now;
let session: OrchestrationV2ProviderSession = {
id: input.providerSessionId,
driver,
providerInstanceId: instanceId,
status: "ready",
cwd: input.runtimePolicy.cwd ?? host.paths.cwd,
model: input.modelSelection.model,
capabilities: OpenCode2ProviderCapabilities,
createdAt: now,
updatedAt: now,
lastError: null,
};
const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>();
const threads = new Map<string, ThreadState>();
const childOwners = new Map<string, ThreadState>();
const announced = new Map<string, EventOf<"session.created">["data"]>();
const strays = new Map<string, ThreadState>();
const busy = new Set<string>();
const pending = new Map<RuntimeRequestId, PendingRequest>();
const lock = yield* Semaphore.make(1);
const clearing = new Map<string, Deferred.Deferred<void>>();
const stagedReverts = new Set<string>();
const sessionGates = yield* KeyedLock.make<string>();
const exclusive =
(providerThread: OrchestrationV2ProviderThread) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) => {
const sessionId = providerThread.nativeThreadRef?.nativeId;
if (sessionId == null) return effect;
return sessionGates.withLock(sessionId, effect);
};
const emit = (event: ProviderAdapter.ProviderAdapterV2Event) =>
Queue.offer(events, event).pipe(Effect.asVoid);
const ownerOf = (sessionId: string) => childOwners.get(sessionId) ?? threads.get(sessionId);
const markUnsettled = (state: ThreadState) => {
state.unsettled = true;
state.unsettledStarted = busy.has(state.sessionId);
};
const newThreadState = (
sessionId: string,
providerThread: OrchestrationV2ProviderThread,
directory: string,
subagent: ThreadState["subagent"],
): ThreadState => ({
sessionId,
providerThread,
providerTurns: new Map(),
active: undefined,
model: undefined,
unsettled: false,
unsettledStarted: false,
directory,
agent: "build",
title: undefined,
rules: undefined,
policy: input.runtimePolicy,
grants: [],
calls: new Map(),
subagent,
wakes: [],
reports: new Map(),
stoppedChildren: new Set(),
strandedSteers: new Set(),
mcp: undefined,
instructions: undefined,
});
const rootOf = (state: ThreadState): ThreadState => {
let current = state;
while (current.subagent !== undefined) current = current.subagent.call.state;
return current;
};
const sessionsOf = (thread: ThreadState): ReadonlyArray<ThreadState> => [
thread,
...[...threads.values()].filter((state) => {
for (let above = state.subagent?.call.state; above; above = above.subagent?.call.state) {
if (above === thread) return true;
}
return false;
}),
];
const runningCalls = (thread: ThreadState): ReadonlyArray<SubagentCall> =>
sessionsOf(thread).flatMap((state) => [...state.calls.values()]);
/**
* The calls a subagent session answers for: the one that launched it and
* the ones that joined it while it ran.
*/
const callsAttachedTo = (child: ThreadState): ReadonlyArray<SubagentCall> => {
const parent = child.subagent?.call.state;
if (parent === undefined) return [];
return [...parent.calls.values()].filter((candidate) => candidate.child === child);
};
const callsAbove = (sessionId: string) => {
const calls: Array<SubagentCall> = [];
let current = threads.get(sessionId);
while (current?.subagent !== undefined) {
calls.push(current.subagent.call);
current = current.subagent.call.state;
}
return calls;
};
const requestTurn = (sessionId: string) => {
const state = ownerOf(sessionId);
if (state === undefined) return undefined;
const background = callsAbove(sessionId).findLast((call) => call.background);
if (background !== undefined) {
return isOrchestrationV2WorkActive(background.status)
? { state, turn: background.turn }
: undefined;
}
return state.active === undefined ? undefined : { state, turn: state.active };
};
const owesWork = (state: ThreadState) =>
state.wakes.length > 0 ||
state.reports.size > 0 ||
(state.subagent !== undefined && busy.has(state.sessionId)) ||
[...state.calls.values()].some((call) => call.background);
const hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork);
const emitProviderThread = Effect.fnUntraced(function* (state: ThreadState) {
const pendingBackgroundWork = hasBackground(state);
state.publishedBackgroundWork = pendingBackgroundWork;
yield* emit({
type: "provider_thread.updated",
driver,
providerThread: state.providerThread,
pendingBackgroundWork,
});
});
const setSessionStatus =
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (
status: OrchestrationV2ProviderSession["status"],
lastError: string | null,
) {
// The session is shared by every thread on this instance and is persisted
// once per attached thread, so a repeat of the same state is not worth a write.
if (session.status === status && session.lastError === lastError) return;
session = { ...session, status, lastError, updatedAt: yield* DateTime.now };
yield* emit({ type: "provider_session.updated", driver, providerSession: session });
});
const ordinalOf = (turn: ActiveTurn, nativeId: string) => {
const known = turn.ordinals.get(nativeId);
if (known !== undefined) return known;
const next = turn.nextOrdinal++;
turn.ordinals.set(nativeId, next);
return next;
};
const itemBase = (
state: ThreadState,
turn: ActiveTurn,
nativeId: string,
status: OrchestrationV2TurnItem["status"],
startedAt: DateTime.Utc,
completedAt: DateTime.Utc | null,
updatedAt: DateTime.Utc,
) => ({
id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: nativeId }),
threadId: turn.input.threadId,
runId: turn.input.runId,
nodeId: idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId: nativeId }),
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: ref(nativeId),
parentItemId: null,
ordinal: ordinalOf(turn, nativeId),
status,
title: null,
startedAt,
completedAt,
updatedAt,
});
const emitNode = (
state: ThreadState,
turn: ActiveTurn,
nativeId: string,
kind: OrchestrationV2ExecutionNode["kind"],
status: OrchestrationV2ExecutionNode["status"],
startedAt: DateTime.Utc,
completedAt: DateTime.Utc | null,
) =>
emit({
type: "node.updated",
driver,
node: {
id: idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId: nativeId }),
threadId: turn.input.threadId,
runId: turn.input.runId,
parentNodeId: turn.input.rootNodeId,
rootNodeId: turn.input.rootNodeId,
kind,
status,
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: ref(nativeId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt,
},
});
const emitText = Effect.fnUntraced(function* (
state: ThreadState,
turn: ActiveTurn,
data: {
readonly assistantMessageID: string;
readonly ordinal: number;
readonly text?: string;
},
kind: "text" | "reasoning",
update: (current: string) => string,
completed = "text" in data,
) {
const nativeId = `${data.assistantMessageID}:${kind}:${data.ordinal}`;
const updatedAt = yield* DateTime.now;
const entry = turn.texts.get(nativeId) ?? {
block: data,
kind,
startedAt: updatedAt,
text: "",
};
entry.text = update(entry.text);
if (completed) turn.texts.delete(nativeId);
else turn.texts.set(nativeId, entry);
if (entry.text.length === 0) return;
const status = completed ? "completed" : "running";
const completedAt = completed ? updatedAt : null;
const nodeKind = kind === "text" ? "assistant_message" : "reasoning";
yield* emitNode(state, turn, nativeId, nodeKind, status, entry.startedAt, completedAt);
const base = itemBase(state, turn, nativeId, status, entry.startedAt, completedAt, updatedAt);
if (kind === "reasoning") {
yield* emit({
type: "turn_item.updated",
driver,
turnItem: { ...base, type: "reasoning", text: entry.text, streaming: !completed },
});
return;
}
const messageId = idAllocator.derive.messageFromProviderItem({
driver,
nativeItemId: nativeId,
});
const message: OrchestrationV2ConversationMessage = {
createdBy: "agent",
creationSource: "provider",
id: messageId,
threadId: turn.input.threadId,
runId: turn.input.runId,
nodeId: base.nodeId,
role: "assistant",
text: entry.text,
attachments: [],
streaming: !completed,
createdAt: entry.startedAt,
updatedAt,
};
yield* emit({ type: "message.updated", driver, message });
yield* emit({
type: "turn_item.updated",
driver,
turnItem: {
...base,
type: "assistant_message",
messageId,
text: entry.text,
streaming: !completed,
},
});
});
const emitTool = Effect.fnUntraced(function* (
state: ThreadState,
turn: ActiveTurn,
id: string,
status: "running" | "completed" | "failed" | "interrupted",
result?: {
readonly output: string | undefined;
readonly metadata: unknown;
readonly files?: ReadonlyArray<{ readonly uri: string; readonly mime: string }>;
},
) {
const tool = turn.tools.get(id);
if (tool === undefined) return;
const updatedAt = yield* DateTime.now;
const startedAt = turn.startedAt.get(id) ?? updatedAt;
const completedAt = status === "running" ? null : updatedAt;
const nativeId = `${turn.scope}${id}`;
const settled =
status === "completed" && openCodeCommandFailed(tool.name, result?.metadata)
? "failed"
: status;
yield* emitNode(state, turn, nativeId, "tool_call", settled, startedAt, completedAt);
yield* emit({
type: "turn_item.updated",
driver,
turnItem: openCodeToolTurnItem(
itemBase(state, turn, nativeId, settled, startedAt, completedAt, updatedAt),
{
name: tool.name,
input: tool.input,
output: result?.output,
files: result?.files,
completedMetadata: status === "completed" ? result?.metadata : undefined,
},
),
});
});
const emitCompaction = Effect.fnUntraced(function* (
state: ThreadState,
turn: ActiveTurn,
status: "running" | "completed" | "failed" | "interrupted",
summary?: string,
) {
const compaction = turn.compaction;
if (compaction === undefined) return;
const updatedAt = yield* DateTime.now;
const completedAt = status === "running" ? null : updatedAt;
yield* emit({
type: "turn_item.updated",
driver,
turnItem: {
...itemBase(
state,
turn,
compaction.nativeId,
status,
compaction.startedAt,
completedAt,
updatedAt,
),
nodeId: turn.input.rootNodeId,
type: "compaction",
driver,
title:
status === "running"
? "Compacting context"
: status === "completed"
? "Context compacted"
: status === "failed"
? "Compaction failed"
: "Compaction interrupted",
...(summary === undefined || summary.length === 0 ? {} : { summary }),
},
});
if (status !== "running") turn.compaction = undefined;
});
const emitRetry = Effect.fnUntraced(function* (
state: ThreadState,
turn: ActiveTurn,
status: "running" | TurnTerminal["status"],
failure?: OrchestrationV2ProviderFailure,
) {
const retry = turn.retry;
if (retry === undefined) return;
yield* emit({
type: "turn_item.updated",
driver,
turnItem: makeProviderRetryTurnItem({
driver,
threadId: turn.input.threadId,
runId: turn.input.runId,
nodeId: turn.input.rootNodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurn.id,
itemOrdinal: ordinalOf(turn, `terminal-failure:${turn.providerTurn.id}`),
failure: failure ?? retry.failure,
retry: retry.retry,
status,
startedAt: retry.startedAt,
updatedAt: yield* DateTime.now,
}),
});
});
const updateRetry = Effect.fnUntraced(function* (
state: ThreadState,
turn: ActiveTurn,
{ attempt, error }: Pick<EventOf<"session.retry.scheduled">["data"], "attempt" | "error">,
delayMs: number,
) {
turn.retry = {
retry: {
// OpenCode counts the first request as attempt 1, so its first retry is attempt 2.
attempt: Math.max(1, attempt - 1),
maxAttempts: null,
retryDelayMs: Math.max(0, Math.trunc(delayMs)),
},
failure: makeProviderFailure({
message: readableProviderErrorMessage(error.message, error.status, error.response?.body),
code: error.type,
class: "provider_error",
retryable: true,
}),
startedAt: turn.retry?.startedAt ?? (yield* DateTime.now),
};
yield* emitRetry(state, turn, "running");
});
const emitProviderTurn = (
state: ThreadState,
turn: ActiveTurn,
providerTurn: OrchestrationV2ProviderTurn,
) => {
state.providerTurns.set(String(providerTurn.id), providerTurn);
return emit({
type: "provider_turn.updated",
driver,
threadId: turn.input.threadId,
providerTurn,
});
};
const makeTurn = (
owner: TurnOwner,
providerTurn: OrchestrationV2ProviderTurn,
options: { readonly scope: string; readonly awaitingStart: boolean },
): ActiveTurn => ({
input: owner,
providerTurn,
texts: new Map(),
tools: new Map(),
startedAt: new Map(),
ordinals: new Map(),
nextOrdinal: providerTurn.ordinal * 100 + 1,
usage: { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 },
startedSteps: 0,
missedEvents: false,
steps: 0,
models: new Set(),
lastStep: undefined,
before: undefined,
compaction: undefined,
compactions: 0,
retry: undefined,
interrupted: false,
unsent: false,
steers: new Set(),
settledInbox: new Set(),
heldEnd: undefined,
awaitingStart: options.awaitingStart,
scope: options.scope,
usedSubagents: false,
});
const emitSubagent = Effect.fnUntraced(function* (call: SubagentCall) {
const updatedAt = yield* DateTime.now;
const { turn, state } = call;
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver,
nativeItemId: call.nativeId,
});
const completedAt = isOrchestrationV2WorkActive(call.status)
? null
: (call.completedAt ?? updatedAt);
const childProviderThreadId = call.child?.providerThread.id ?? null;
const childThreadId = call.child?.subagent?.appThread.id ?? null;
yield* emit({
type: "node.updated",
driver,
node: {
id: nodeId,
threadId: turn.input.threadId,
runId: turn.input.runId,
parentNodeId: turn.input.rootNodeId,
rootNodeId: turn.input.rootNodeId,
kind: "subagent",
status: call.status,
countsForRun: false,
providerThreadId: childProviderThreadId ?? state.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: ref(call.nativeId),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: call.startedAt,
completedAt,
},
});
yield* emit({
type: "subagent.updated",
driver,
subagent: {
id: nodeId,
threadId: turn.input.threadId,
runId: turn.input.runId,
parentNodeId: turn.input.rootNodeId,
origin: "provider_native",
createdBy: "agent",
driver,
providerInstanceId: instanceId,
providerThreadId: childProviderThreadId,
childThreadId,
nativeTaskRef: ref(call.nativeId),
prompt: call.prompt,
title: call.title,
model: call.model,
status: call.status,
result: call.result,
startedAt: call.startedAt,
completedAt,
updatedAt,
},
});
yield* emit({
type: "turn_item.updated",
driver,
turnItem: {
id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: call.nativeId }),
threadId: turn.input.threadId,
runId: turn.input.runId,
nodeId,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: ref(call.nativeId),
parentItemId: null,
ordinal: call.ordinal,
status: call.status,
title: call.title,
startedAt: call.startedAt,
completedAt,
updatedAt,
type: "subagent",
subagentId: nodeId,
origin: "provider_native",
driver,
providerInstanceId: instanceId,
childThreadId,
prompt: call.prompt,
result: call.result,
},
});
yield* syncRosterAncestors(call.state);
});
const syncRoster = Effect.fnUntraced(function* (state: ThreadState) {
const roster = runningCalls(state)
.filter((call) => call.background)
.map((call) => ({
taskId: call.nativeId,
kind: "subagent" as const,
...(call.title?.trim() ? { description: call.title.trim() } : {}),
...(call.child?.subagent === undefined
? {}
: { childThreadId: call.child.subagent.appThread.id }),
}));
const current = state.providerThread.pendingBackgroundTasks ?? [];
if (
state.publishedBackgroundWork === hasBackground(state) &&
current.length === roster.length &&
current.every(
(task, index) =>
task.taskId === roster[index]?.taskId &&
task.description === roster[index]?.description &&
(task.kind === "subagent" ? task.childThreadId : undefined) ===
roster[index]?.childThreadId,
)
) {
return;
}
state.providerThread = {
...state.providerThread,
pendingBackgroundTasks: roster,
updatedAt: yield* DateTime.now,
};
yield* emitProviderThread(state);
});
const syncRosterAncestors = Effect.fnUntraced(function* (state: ThreadState) {
let current: ThreadState | undefined = state;
while (current !== undefined) {
yield* syncRoster(current);
current = current.subagent?.call.state;
}
});
const withReportedModel = (
providerThread: OrchestrationV2ProviderThread,
model: ModelRef | undefined,
): OrchestrationV2ProviderThread => {
if (model === undefined) return providerThread;
const modelSelection: ModelSelection = {
instanceId,
model: `${model.providerID}/${model.id}`,
options: model.variant === undefined ? [] : [{ id: "variant", value: model.variant }],
};
if (
providerThread.nativeMetadata?.modelSelection !== undefined &&
modelSelectionsEqual(providerThread.nativeMetadata.modelSelection, modelSelection)
)
return providerThread;
return {
...providerThread,
nativeMetadata: { ...providerThread.nativeMetadata, modelSelection },
};
};
const attachChild = Effect.fnUntraced(function* (call: SubagentCall, childId: string) {
if (call.child !== undefined) return;
const info = announced.get(childId);
announced.delete(childId);
const now = yield* DateTime.now;
const nodeId = idAllocator.derive.nodeFromProviderItem({
driver,
nativeItemId: call.nativeId,
});
const childThreadId = idAllocator.derive.threadFromProviderThread({
driver,
nativeThreadId: childId,
providerInstanceId: instanceId,
});
const providerThreadId = idAllocator.derive.providerThread({
driver,
nativeThreadId: childId,
providerInstanceId: instanceId,
});
if (info?.model !== undefined) call.model = `${info.model.providerID}/${info.model.id}`;
call.title = call.title ?? info?.title ?? null;
const parentThread = call.turn.input.appThread;
const appThread = makeSubagentChildThread({
parentThread,
childThreadId,
parentNodeId: nodeId,
activeProviderThreadId: providerThreadId,
providerInstanceId: instanceId,
modelSelection: {
instanceId,
model: call.model ?? call.turn.input.modelSelection.model,
},
title: subagentThreadTitle({
parentTitle: parentThread.title,
title: call.title,
prompt: call.prompt,
ordinal: call.ordinal,
}),
now,
createdBy: "agent",
creationSource: "provider",
});
const providerThread: OrchestrationV2ProviderThread = {
id: providerThreadId,
driver,
providerInstanceId: instanceId,
providerSessionId: input.providerSessionId,
appThreadId: childThreadId,
ownerNodeId: nodeId,
nativeThreadRef: ref(childId),
nativeConversationHeadRef: null,
status: "active",
firstRunOrdinal: null,
lastRunOrdinal: null,
handoffIds: [],
forkedFrom: null,
createdAt: now,
updatedAt: now,
};
const previous = threads.get(childId);
// Repeated subagent calls steer the same run; OpenCode reports it once for every joined call.
if (previous?.active !== undefined) {
call.joined = [...call.state.calls.values()].findLast(
(candidate) =>
candidate !== call && candidate.child === previous && candidate.joined === undefined,
);
}
const subagent = {
call,
appThread,
turns: previous?.subagent?.turns ?? 0,
prompt: call.prompt,
queued: undefined,
};
const child =
previous ?? newThreadState(childId, providerThread, call.state.directory, subagent);
child.subagent = subagent;
child.model = info?.model ?? child.model;
child.providerThread = withReportedModel(providerThread, child.model);
child.directory = call.state.directory;
child.agent = info?.agent ?? call.agent ?? child.agent;
child.rules = info?.permissions ?? child.rules;
threads.set(childId, child);
childOwners.set(childId, rootOf(call.state));
call.child = child;
yield* emit({ type: "app_thread.created", driver, appThread });
yield* emitProviderThread(child);
yield* emitSubagent(call);
// Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them.
if (info === undefined) {
yield* writeRules(child, rootOf(call.state).policy).pipe(
Effect.timeout(REQUEST_REPLY_TIMEOUT),
Effect.ignore({ log: true }),
);
}
});
const settleCall: (
call: SubagentCall,
status: OrchestrationV2Subagent["status"],
result?: string,
) => Effect.Effect<void> = Effect.fnUntraced(function* (call, status, result) {
if (!isOrchestrationV2WorkActive(call.status)) return;
call.status = status;
call.completedAt = yield* DateTime.now;
if (result !== undefined) call.result = result;
call.state.calls.delete(call.toolId);
const child = call.child;
if (child !== undefined) {
for (const nested of Array.from(child.calls.values())) {
if (nested.background && status !== "failed") continue;
yield* settleCall(nested, status === "completed" ? "interrupted" : status);
}
if (child.active !== undefined && status !== "completed") {
yield* finishTurn(child, { status: "interrupted" });
}
child.providerThread = {
...child.providerThread,
status: "idle",
updatedAt: call.completedAt,
};
yield* emitProviderThread(child);
}
yield* emitSubagent(call);
});
const startChildTurn = Effect.fnUntraced(function* (child: ThreadState) {
const subagent = child.subagent;
if (subagent === undefined || child.active !== undefined) return;
subagent.turns += 1;
const startedAt = yield* DateTime.now;
const nativeTurnId = `${child.sessionId}:turn:${subagent.turns}`;
const rootNodeId = idAllocator.derive.nodeFromProviderItem({
driver,
nativeItemId: `${nativeTurnId}:root`,
});
const providerTurn: OrchestrationV2ProviderTurn = {
id: idAllocator.derive.providerTurn({ driver, nativeTurnId }),
providerThreadId: child.providerThread.id,
nodeId: rootNodeId,
runAttemptId: null,
nativeTurnRef: ref(nativeTurnId, "weak"),
ordinal: subagent.turns,
status: "running",
startedAt,
completedAt: null,
};
const turn = makeTurn(
{
appThread: subagent.appThread,
threadId: subagent.appThread.id,
runId: null,
runOrdinal: subagent.call.turn.input.runOrdinal,
rootNodeId,
modelSelection: subagent.appThread.modelSelection,
runtimePolicy: subagent.call.turn.input.runtimePolicy,
},
providerTurn,
{ scope: `${child.sessionId}:`, awaitingStart: false },
);
turn.before = subagent.queued;
subagent.queued = undefined;
child.active = turn;
yield* emit({
type: "node.updated",
driver,
node: {
id: rootNodeId,
threadId: turn.input.threadId,
runId: null,
parentNodeId: null,
rootNodeId,
kind: "root_turn",
status: "running",
countsForRun: false,
providerThreadId: child.providerThread.id,
providerTurnId: providerTurn.id,
nativeItemRef: ref(nativeTurnId, "weak"),
runtimeRequestId: null,
checkpointScopeId: null,
startedAt,
completedAt: null,
},
});
yield* emitProviderTurn(child, turn, providerTurn);
const prompt = subagent.prompt;
subagent.prompt = undefined;
if (prompt !== undefined && prompt.length > 0) {
const nativeId = `${nativeTurnId}:prompt`;
const artifacts = makeSubagentConversationArtifacts({
messageId: idAllocator.derive.messageFromProviderItem({ driver, nativeItemId: nativeId }),
senderThreadId: subagent.call.turn.input.threadId,
turnItemId: idAllocator.derive.turnItemFromProviderItem({
driver,
nativeItemId: nativeId,
}),
threadId: turn.input.threadId,
rootNodeId,
providerThreadId: child.providerThread.id,
providerTurnId: providerTurn.id,
nativeItemRef: ref(nativeId, "weak"),
role: "user",
text: prompt,
ordinal: ordinalOf(turn, nativeId),
now: startedAt,
});
yield* emit({ type: "message.updated", driver, message: artifacts.message });
yield* emit({ type: "turn_item.updated", driver, turnItem: artifacts.turnItem });
}
});
const offerWake = Effect.fnUntraced(function* (state: ThreadState, wake: Wake) {
const route = state.providerThread.appThreadId;
if (route === null || wake.messageId === undefined) return;
const notification = backgroundWorkNotification(wake.reports);
yield* continuationRequests.offer({
threadId: route,
providerThreadId: state.providerThread.id,
driver,
detail: wake.detail,
messageId: wake.messageId,
...(notification === null ? {} : { notification }),
dispatchIfCurrent: (dispatch) =>
wake.dropped ? Effect.succeedNone : Effect.asSome(dispatch),
});
});
const finishTurn = Effect.fnUntraced(function* (
state: ThreadState,
terminal: TurnTerminal,
threadDisposition: "reusable" | "broken" = "reusable",
) {
const turn = state.active;
if (turn === undefined) return;
state.active = undefined;
for (const inboxID of turn.steers) state.strandedSteers.add(inboxID);
for (const entry of pending.values()) {
const background = callsAbove(entry.sessionId).some((call) => call.background);
if (
entry.sessionId === state.sessionId ||
(entry.turn === turn && !(background && terminal.status !== "failed"))
) {
yield* settleRequest(entry, "cancelled");
}
}
const completedAt = yield* DateTime.now;
for (const open of turn.texts.values()) {
yield* emitText(state, turn, open.block, open.kind, (text) => text, true);
}
for (const id of turn.tools.keys()) {
yield* emitTool(
state,
turn,
id,
terminal.status === "completed" ? "completed" : "interrupted",
);
}
for (const call of Array.from(state.calls.values())) {
if (call.turn !== turn) continue;
if (call.background && terminal.status !== "failed") continue;
yield* settleCall(call, terminal.status === "completed" ? "completed" : terminal.status);
}
if (state.subagent !== undefined) {
yield* emit({
type: "node.updated",
driver,
node: {
id: turn.input.rootNodeId,
threadId: turn.input.threadId,
runId: null,
parentNodeId: null,
rootNodeId: turn.input.rootNodeId,
kind: "root_turn",
status: terminal.status,
countsForRun: false,
providerThreadId: state.providerThread.id,
providerTurnId: turn.providerTurn.id,
nativeItemRef: turn.providerTurn.nativeTurnRef,
runtimeRequestId: null,
checkpointScopeId: null,
startedAt: turn.providerTurn.startedAt,
completedAt,
},
});
}
yield* emitCompaction(state, turn, terminal.status === "failed" ? "failed" : "interrupted");
yield* emitRetry(
state,
turn,
terminal.status,
terminal.status === "failed" ? terminal.failure : undefined,
);
const window = windowOf(turn.input.runtimePolicy.cwd, turn.input.modelSelection.model);
const lastStep = turn.lastStep;
yield* emitProviderTurn(state, turn, {
...turn.providerTurn,
status: terminal.status,
completedAt,
turnTokenUsage: turnTokenUsage(turn, terminal.status),
...(lastStep === undefined
? {}
: {
tokenUsage: {
usedTokens:
lastStep.input + lastStep.cache.read + lastStep.cache.write + lastStep.output,
maxTokens: window ?? null,
inputTokens: lastStep.input + lastStep.cache.read + lastStep.cache.write,
cachedInputTokens: lastStep.cache.read,
outputTokens: lastStep.output,
reasoningOutputTokens: lastStep.reasoning,
updatedAt: DateTime.formatIso(completedAt),
},
}),
});
// Subagent turns are runless; their calls own settlement.
if (state.subagent !== undefined) {
const call = state.subagent.call;
if (!call.background && terminal.status !== "completed") {
yield* settleCall(call, terminal.status);
}
if (terminal.status === "failed") {
// Background calls settle when the parent reads a report; failed children have no report.
// Fail every attached call so earlier background calls cannot leave phantom work,
// regardless of which call joined last or is still foreground.
for (const attached of callsAttachedTo(state)) {
yield* settleCall(attached, terminal.status, terminal.failure.message);
}
}
return;
}
state.providerThread = {
...state.providerThread,
status: threadDisposition === "broken" ? "error" : "idle",
updatedAt: completedAt,
};
yield* emitProviderThread(state);
const anyActive = [...threads.values()].some(
(candidate) => candidate.subagent === undefined && candidate.active !== undefined,
);
yield* setSessionStatus(pending.size > 0 ? "waiting" : anyActive ? "running" : "ready", null);
const base = {
type: "turn.terminal" as const,
driver,
// Native forks change thread IDs; terminal events must retain the recorded start identity.
providerThreadId: turn.providerTurn.providerThreadId,
providerTurnId: turn.providerTurn.id,
runOrdinal: turn.input.runOrdinal,
threadDisposition,
};
yield* emit(
terminal.status === "failed"
? {
...base,
status: "failed",
failure: terminal.failure,
failureItemOrdinal: ordinalOf(turn, `terminal-failure:${turn.providerTurn.id}`),
...(turn.retry === undefined
? {}
: { retry: turn.retry.retry, retryStartedAt: turn.retry.startedAt }),
}
: { ...base, status: terminal.status, failure: null },
);
// Cold servers list models lazily; refresh unknown windows off-stream for the next turn.
if (window === undefined) {
yield* Effect.forkIn(readModels(directoryOf(turn.input.runtimePolicy.cwd)), sessionScope);
}
});
// OpenCode waits forever on unanswered requests; stop that run and keep its end from settling the next.
const abandonRequest = Effect.fnUntraced(function* (state: ThreadState, reason: string) {
yield* Effect.logWarning("Could not answer an OpenCode request; ending its turn.", {
reason,
});
if (state.active === undefined) return;
markUnsettled(state);
yield* finishTurn(state, {
status: "failed",
failure: makeProviderFailure({
message: "OpenCode is waiting on a request T3 Code couldn't answer.",
class: "provider_error",
}),
});
yield* client.session
.interrupt({ sessionID: Session.ID.make(state.sessionId) })
.pipe(Effect.timeout("2 seconds"), Effect.ignore({ log: true }));
});
const forgetRequest = Effect.fnUntraced(function* (entry: PendingRequest) {
if (!pending.delete(entry.request.id)) return false;
if (pending.size === 0 && session.status === "waiting") {
yield* setSessionStatus("running", null);
}
return true;
});
// The orchestrator already recorded T3-owned answers; only forget them here.
const settleRequest = Effect.fnUntraced(function* (
entry: PendingRequest,
status: "resolved" | "cancelled",
) {
if (!(yield* forgetRequest(entry)) || entry.answering) return;
const now = yield* DateTime.now;
const itemStatus = status === "resolved" ? "completed" : "cancelled";
yield* emit({
type: "runtime_request.updated",
driver,
threadId: entry.turn.input.threadId,
runtimeRequest: { ...entry.request, status, resolvedAt: now },
});
yield* emit({
type: "node.updated",
driver,
node: { ...entry.node, status: itemStatus, completedAt: now },
});
yield* emit({
type: "turn_item.updated",
driver,
turnItem: { ...entry.item, status: itemStatus, completedAt: now, updatedAt: now },
});
});
const stopStaleRequest = (
sessionId: string,
native: { readonly type: "permission" | "form"; readonly id: string },
): Effect.Effect<void> =>
native.type === "permission"
? client.permission
.reply({
sessionID: Session.ID.make(sessionId),
requestID: Permission.ID.make(native.id),
decision: "reject",
})
.pipe(
Effect.catchTags(permissionGone),
Effect.timeout(REQUEST_REPLY_TIMEOUT),
Effect.ignore({ log: true }),
)
: client.session.form
.cancel({ sessionID: sessionId, formID: Form.ID.make(native.id) })
.pipe(
Effect.catchTags(formGone),
Effect.timeout(REQUEST_REPLY_TIMEOUT),
Effect.ignore({ log: true }),
);
// T3 expired pre-load requests and no longer shows them; stop them so OpenCode cannot wait forever.
const stopLeftoverRequests = Effect.fnUntraced(function* (state: ThreadState) {
const sessionID = Session.ID.make(state.sessionId);
const listed = yield* Effect.all([
client.permission.list({ sessionID }),
client.session.form.list({ sessionID }),
]).pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option);
if (listed._tag === "None") {
return yield* Effect.logWarning("Could not list an OpenCode session's open requests.");
}
const [permissions, forms] = listed.value;
if (permissions.length === 0 && forms.length === 0) return;
markUnsettled(state);
for (const request of permissions) {
yield* stopStaleRequest(state.sessionId, { type: "permission", id: request.id });
}
for (const form of forms) {
yield* stopStaleRequest(state.sessionId, { type: "form", id: form.id });
}
});
const showRequest = Effect.fnUntraced(function* (
sessionId: string,
native: PendingRequest["native"],
body:
| {
readonly type: "approval_request";
readonly requestKind: Extract<
OrchestrationV2TurnItem,
{ type: "approval_request" }
>["requestKind"];
readonly prompt: string;
readonly options: Extract<
OrchestrationV2TurnItem,