The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 03:37 UTC
| 1 | import type { |
| 2 | Event as OpenCodeEvent, |
| 3 | Message as OpenCodeMessage, |
| 4 | Part as OpenCodePart, |
| 5 | PermissionRequest, |
| 6 | PermissionRuleset, |
| 7 | QuestionRequest, |
| 8 | Session as OpenCodeSession, |
| 9 | Todo as OpenCodeTodo, |
| 10 | ToolPart, |
| 11 | } from "@opencode-ai/sdk/v2"; |
| 12 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 13 | import { getModelSelectionStringOptionValue } from "@t3tools/shared/model"; |
| 14 | import { causeErrorTag } from "@t3tools/shared/observability"; |
| 15 | import { |
| 16 | defaultInstanceIdForDriver, |
| 17 | type ModelSelection, |
| 18 | type OrchestrationV2AppThread, |
| 19 | type OrchestrationV2ConversationMessage, |
| 20 | type OrchestrationV2ExecutionNode, |
| 21 | type OrchestrationV2PlanStep, |
| 22 | type OrchestrationV2ProviderCapabilities, |
| 23 | type OrchestrationV2ProviderFailure, |
| 24 | type OrchestrationV2ProviderRef, |
| 25 | type OrchestrationV2ProviderSession, |
| 26 | type OrchestrationV2ProviderThread, |
| 27 | type OrchestrationV2ProviderTurn, |
| 28 | type OrchestrationV2RuntimeRequest, |
| 29 | type OrchestrationV2Subagent, |
| 30 | type OrchestrationV2TurnItem, |
| 31 | type PlanId, |
| 32 | ProviderDriverKind, |
| 33 | ProviderSetupError, |
| 34 | type ProviderInstanceId, |
| 35 | type ProviderRequestKind, |
| 36 | type ProviderSessionId, |
| 37 | type RuntimeRequestId, |
| 38 | type ThreadId, |
| 39 | settingsSecretLiteral, |
| 40 | } from "@t3tools/contracts"; |
| 41 | import { OpenCodeSettings } from "../settings.ts"; |
| 42 | import * as Cause from "effect/Cause"; |
| 43 | import * as DateTime from "effect/DateTime"; |
| 44 | import * as Deferred from "effect/Deferred"; |
| 45 | import * as Duration from "effect/Duration"; |
| 46 | import * as Effect from "effect/Effect"; |
| 47 | import * as Exit from "effect/Exit"; |
| 48 | import * as Fiber from "effect/Fiber"; |
| 49 | import * as Option from "effect/Option"; |
| 50 | import * as Queue from "effect/Queue"; |
| 51 | import * as Random from "effect/Random"; |
| 52 | import * as Ref from "effect/Ref"; |
| 53 | import * as Schema from "effect/Schema"; |
| 54 | import * as Semaphore from "effect/Semaphore"; |
| 55 | import * as Scope from "effect/Scope"; |
| 56 | import * as Stream from "effect/Stream"; |
| 57 | |
| 58 | import { brokenVersionDetail } from "@t3tools/provider-core/server/compatibility"; |
| 59 | import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; |
| 60 | import { mcpToolPresentation } from "@t3tools/provider-core/server/mcpToolPresentation"; |
| 61 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 62 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 63 | import { |
| 64 | structuralProtocolMethod, |
| 65 | summarizeNativeProtocolPayload, |
| 66 | } from "@t3tools/provider-core/server/nativeProtocolLogging"; |
| 67 | import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; |
| 68 | import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; |
| 69 | import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; |
| 70 | import * as OpenCodeRuntime from "./OpenCodeRuntime.ts"; |
| 71 | import { readableProviderErrorMessage } from "./providerErrorMessage.ts"; |
| 72 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 73 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 74 | import { makeProviderFailure } from "@t3tools/provider-core/server/failure"; |
| 75 | import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition"; |
| 76 | import { providerMessageTextWithAttachmentPaths } from "@t3tools/provider-core/server/attachmentPrompt"; |
| 77 | import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 78 | import { |
| 79 | ProviderAdapterDriverCreateError, |
| 80 | type ProviderAdapterDriver, |
| 81 | type ProviderAdapterDriverCreateInput, |
| 82 | } from "@t3tools/provider-core/server/adapterDriver"; |
| 83 | import { |
| 84 | makeSubagentChildThread, |
| 85 | subagentThreadTitle, |
| 86 | } from "@t3tools/provider-core/server/subagentProjection"; |
| 87 | import { openCodeCommandFailed, openCodeToolOutput, openCodeToolTurnItem } from "./toolItems.ts"; |
| 88 | |
| 89 | export const OPENCODE_PROVIDER = ProviderDriverKind.make("opencode"); |
| 90 | export const OPENCODE_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(OPENCODE_PROVIDER); |
| 91 | export const OPENCODE_SDK_PROTOCOL = "opencode-sdk.sse" as const; |
| 92 | const DEFAULT_OPENCODE_SETTINGS = Schema.decodeSync(OpenCodeSettings)({}); |
| 93 | const OPENCODE_STOP_CONFIRM_TIMEOUT_MS = 10_000; |
| 94 | |
| 95 | const makeOpenCodeMessageId = Effect.fnUntraced(function* ( |
| 96 | clock: Ref.Ref<{ readonly epochMillis: number; readonly counter: number }>, |
| 97 | ) { |
| 98 | const epochMillis = DateTime.toEpochMillis(yield* DateTime.now); |
| 99 | const counter = yield* Ref.modify(clock, (previous) => { |
| 100 | const next = previous.epochMillis === epochMillis ? previous.counter + 1 : 1; |
| 101 | return [next, { epochMillis, counter: next }] as const; |
| 102 | }); |
| 103 | const encodedTime = BigInt.asUintN(48, BigInt(epochMillis) * 0x1000n + BigInt(counter)) |
| 104 | .toString(16) |
| 105 | .padStart(12, "0"); |
| 106 | const alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; |
| 107 | const random = (yield* Effect.forEach(Array.from({ length: 28 }), () => |
| 108 | Random.nextIntBetween(0, alphabet.length - 1), |
| 109 | )) |
| 110 | .map((index) => alphabet[index]) |
| 111 | .join(""); |
| 112 | return `msg_${encodedTime}${random}`; |
| 113 | }); |
| 114 | |
| 115 | // OpenCode has no turn object; correlate by initiating user message and settle on session idle. |
| 116 | const OpenCodeProviderCapabilitiesV2 = { |
| 117 | sessions: { |
| 118 | // The directory-bound client/server is not safe for cross-thread pooling. |
| 119 | supportsMultipleProviderThreadsPerSession: false, |
| 120 | supportsModelSwitchInSession: true, |
| 121 | supportsProviderSwitchingViaHandoff: true, |
| 122 | supportsRuntimeModeSwitchInSession: false, |
| 123 | pendingRequestsSurviveRestart: false, |
| 124 | }, |
| 125 | threads: { |
| 126 | canCreateEmptyThread: true, |
| 127 | canReadThreadSnapshot: true, |
| 128 | canRollbackThread: true, |
| 129 | canForkThread: true, |
| 130 | canForkFromTurn: true, |
| 131 | canForkFromSubagentThread: true, |
| 132 | exposesNativeThreadId: true, |
| 133 | }, |
| 134 | turns: { |
| 135 | exposesNativeTurnId: false, |
| 136 | emitsTurnStarted: true, |
| 137 | emitsTurnCompleted: true, |
| 138 | supportsInterrupt: true, |
| 139 | supportsNativeResume: true, |
| 140 | supportsActiveSteering: true, |
| 141 | supportsSteeringByInterruptRestart: true, |
| 142 | supportsQueuedMessages: true, |
| 143 | terminalStatusQuality: "strong", |
| 144 | }, |
| 145 | streaming: { |
| 146 | streamsAssistantText: true, |
| 147 | streamsReasoning: true, |
| 148 | streamsToolOutput: true, |
| 149 | streamsPlanText: false, |
| 150 | emitsMessageCompleted: true, |
| 151 | }, |
| 152 | tools: { |
| 153 | exposesToolItemIds: true, |
| 154 | emitsToolStarted: true, |
| 155 | emitsToolCompleted: true, |
| 156 | emitsToolOutput: true, |
| 157 | supportsMcpTools: true, |
| 158 | supportsDynamicToolCallbacks: false, |
| 159 | }, |
| 160 | approvals: { |
| 161 | supportsCommandApproval: true, |
| 162 | supportsFileReadApproval: true, |
| 163 | supportsFileChangeApproval: true, |
| 164 | supportsApplyPatchApproval: true, |
| 165 | approvalsHaveNativeRequestIds: true, |
| 166 | approvalCallbacksAreLiveOnly: true, |
| 167 | approvalsCanOriginateFromSubagents: true, |
| 168 | }, |
| 169 | planning: { |
| 170 | emitsPlanUpdated: true, |
| 171 | emitsTodoList: true, |
| 172 | emitsProposedPlan: false, |
| 173 | supportsStructuredQuestions: true, |
| 174 | planDeltasHaveItemIds: false, |
| 175 | }, |
| 176 | subagents: { |
| 177 | supportsSubagents: true, |
| 178 | exposesSubagentThreadIds: true, |
| 179 | emitsSubagentLifecycle: true, |
| 180 | canWaitForSubagents: true, |
| 181 | canCloseSubagents: false, |
| 182 | canForkSubagentThread: true, |
| 183 | }, |
| 184 | context: { |
| 185 | acceptsSystemContext: false, |
| 186 | acceptsDeveloperContext: false, |
| 187 | acceptsSyntheticUserContext: true, |
| 188 | canGenerateSummaries: true, |
| 189 | canConsumeHandoffSummaries: true, |
| 190 | supportsDeltaHandoff: true, |
| 191 | supportsFullThreadHandoff: true, |
| 192 | maxRecommendedHandoffChars: null, |
| 193 | }, |
| 194 | checkpointing: { |
| 195 | appCanCheckpointFilesystem: true, |
| 196 | supportsNestedCheckpointScopes: true, |
| 197 | providerCanRollbackConversation: true, |
| 198 | providerRollbackReturnsSnapshot: true, |
| 199 | providerCanReadConversationSnapshot: true, |
| 200 | }, |
| 201 | identity: { |
| 202 | nativeThreadIds: "strong", |
| 203 | nativeTurnIds: "weak", |
| 204 | nativeItemIds: "strong", |
| 205 | nativeRequestIds: "strong", |
| 206 | }, |
| 207 | runtimePolicy: { |
| 208 | enforcement: "native", |
| 209 | }, |
| 210 | } satisfies OrchestrationV2ProviderCapabilities; |
| 211 | |
| 212 | type TerminalTurnStatus = Extract< |
| 213 | OrchestrationV2ProviderTurn["status"], |
| 214 | "completed" | "interrupted" | "failed" | "cancelled" |
| 215 | >; |
| 216 | |
| 217 | type OpenCodeStepUsage = Pick< |
| 218 | Extract<OpenCodePart, { readonly type: "step-finish" }>, |
| 219 | "id" | "tokens" |
| 220 | >; |
| 221 | |
| 222 | interface OpenCodeTurnTokenUsageAccumulator { |
| 223 | readonly partIds: Set<string>; |
| 224 | readonly promptMessageIds: Set<string>; |
| 225 | readonly assistantOwnershipByMessageId: Map<string, "owned" | "other" | "unknown">; |
| 226 | readonly unresolvedStepsByMessageId: Map<string, Map<string, OpenCodeStepUsage>>; |
| 227 | inputTokens: number; |
| 228 | cachedInputTokens: number; |
| 229 | cacheCreationTokens: number; |
| 230 | outputTokens: number; |
| 231 | reasoningTokens: number; |
| 232 | hasSubagents: boolean; |
| 233 | complete: boolean; |
| 234 | lastStep: OpenCodeStepUsage | null; |
| 235 | } |
| 236 | |
| 237 | function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumulator { |
| 238 | return { |
| 239 | partIds: new Set(), |
| 240 | promptMessageIds: new Set(), |
| 241 | assistantOwnershipByMessageId: new Map(), |
| 242 | unresolvedStepsByMessageId: new Map(), |
| 243 | inputTokens: 0, |
| 244 | cachedInputTokens: 0, |
| 245 | cacheCreationTokens: 0, |
| 246 | outputTokens: 0, |
| 247 | reasoningTokens: 0, |
| 248 | hasSubagents: false, |
| 249 | complete: true, |
| 250 | lastStep: null, |
| 251 | }; |
| 252 | } |
| 253 | |
| 254 | function accumulateOpenCodeStepUsage( |
| 255 | accumulator: OpenCodeTurnTokenUsageAccumulator, |
| 256 | part: OpenCodeStepUsage, |
| 257 | ): void { |
| 258 | if (accumulator.partIds.has(part.id)) return; |
| 259 | accumulator.partIds.add(part.id); |
| 260 | accumulator.inputTokens += part.tokens.input + part.tokens.cache.read + part.tokens.cache.write; |
| 261 | accumulator.cachedInputTokens += part.tokens.cache.read; |
| 262 | accumulator.cacheCreationTokens += part.tokens.cache.write; |
| 263 | accumulator.outputTokens += part.tokens.output + part.tokens.reasoning; |
| 264 | accumulator.reasoningTokens += part.tokens.reasoning; |
| 265 | accumulator.lastStep = part; |
| 266 | } |
| 267 | |
| 268 | // The last step's prompt plus output is the context the next request starts from. |
| 269 | function openCodeContextUsage( |
| 270 | lastStep: OpenCodeStepUsage | null, |
| 271 | contextWindow: number | undefined, |
| 272 | completedAt: DateTime.Utc, |
| 273 | ): Pick<OrchestrationV2ProviderTurn, "tokenUsage"> { |
| 274 | if (lastStep === null) return {}; |
| 275 | const { tokens } = lastStep; |
| 276 | const inputTokens = tokens.input + tokens.cache.read + tokens.cache.write; |
| 277 | return { |
| 278 | tokenUsage: { |
| 279 | usedTokens: inputTokens + tokens.output, |
| 280 | maxTokens: contextWindow ?? null, |
| 281 | inputTokens, |
| 282 | cachedInputTokens: tokens.cache.read, |
| 283 | outputTokens: tokens.output, |
| 284 | reasoningOutputTokens: tokens.reasoning, |
| 285 | updatedAt: DateTime.formatIso(completedAt), |
| 286 | }, |
| 287 | }; |
| 288 | } |
| 289 | |
| 290 | interface ActiveOpenCodeTurn { |
| 291 | readonly usage: OpenCodeTurnTokenUsageAccumulator; |
| 292 | readonly isRoot: boolean; |
| 293 | readonly threadId: ThreadId; |
| 294 | readonly runId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null; |
| 295 | readonly rootNodeId: ProviderAdapter.ProviderAdapterV2TurnInput["rootNodeId"]; |
| 296 | readonly appThread: OrchestrationV2AppThread; |
| 297 | readonly modelSelection: ModelSelection; |
| 298 | readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; |
| 299 | readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; |
| 300 | readonly providerThreadId: OrchestrationV2ProviderTurn["providerThreadId"]; |
| 301 | readonly runOrdinal: number; |
| 302 | readonly startedAt: DateTime.Utc; |
| 303 | readonly itemOrdinals: Map<string, number>; |
| 304 | readonly parts: Map<string, Exclude<OpenCodePart, ToolPart>>; |
| 305 | readonly partIdsByMessage: Map<string, Set<string>>; |
| 306 | readonly toolNamesByCallId: Map<string, string>; |
| 307 | mcpServerNames?: ReadonlyArray<string>; |
| 308 | readonly providerTurn: OrchestrationV2ProviderTurn; |
| 309 | nextItemOrdinal: number; |
| 310 | nativeUserMessageId: string | null; |
| 311 | admissionMessageId: string | null; |
| 312 | readonly priorWakePromptIds: Set<string>; |
| 313 | priorWakeSettled: Deferred.Deferred<void> | null; |
| 314 | interrupted: boolean; |
| 315 | finalized: boolean; |
| 316 | contextOverflow: OrchestrationV2ProviderFailure | null; |
| 317 | planId: PlanId | null; |
| 318 | admissionGeneration: number; |
| 319 | admissionReconciliationGeneration: number | null; |
| 320 | admissionPending: boolean; |
| 321 | admissionAccepted: boolean; |
| 322 | admissionMessageObserved: boolean; |
| 323 | idleDuringAdmission: boolean; |
| 324 | admissionUncertain: boolean; |
| 325 | admissionStatusSequence: number; |
| 326 | admissionSettled: Deferred.Deferred<void>; |
| 327 | admissionAbortController: AbortController | null; |
| 328 | } |
| 329 | |
| 330 | type OpenCodeAdmissionSignal = |
| 331 | | "accepted" |
| 332 | | "assistant-completed" |
| 333 | | "busy" |
| 334 | | "idle" |
| 335 | | "user-message"; |
| 336 | type OpenCodeAdmissionAction = "hold" | "reconcile-idle" | "release"; |
| 337 | |
| 338 | export function advanceOpenCodePromptAdmission( |
| 339 | admission: Pick< |
| 340 | ActiveOpenCodeTurn, |
| 341 | "admissionAccepted" | "admissionMessageObserved" | "admissionPending" | "idleDuringAdmission" |
| 342 | >, |
| 343 | signal: OpenCodeAdmissionSignal, |
| 344 | ): OpenCodeAdmissionAction { |
| 345 | if (!admission.admissionPending) return "release"; |
| 346 | if (signal === "assistant-completed") { |
| 347 | admission.admissionAccepted = true; |
| 348 | admission.admissionMessageObserved = true; |
| 349 | admission.admissionPending = false; |
| 350 | return "release"; |
| 351 | } |
| 352 | if (signal === "idle") { |
| 353 | admission.idleDuringAdmission = true; |
| 354 | return "hold"; |
| 355 | } |
| 356 | if (signal === "accepted") admission.admissionAccepted = true; |
| 357 | if (signal === "busy" || signal === "user-message") admission.admissionMessageObserved = true; |
| 358 | if (!admission.admissionAccepted || !admission.admissionMessageObserved) return "hold"; |
| 359 | if (admission.idleDuringAdmission) return "reconcile-idle"; |
| 360 | admission.admissionPending = false; |
| 361 | return "release"; |
| 362 | } |
| 363 | |
| 364 | export function cancelOpenCodePromptAdmission( |
| 365 | admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">, |
| 366 | nextGeneration: number, |
| 367 | ): void { |
| 368 | admission.admissionGeneration = nextGeneration; |
| 369 | admission.admissionPending = false; |
| 370 | } |
| 371 | |
| 372 | export const reconcileOpenCodePromptAdmissionStatus = Effect.fn( |
| 373 | "reconcileOpenCodePromptAdmissionStatus", |
| 374 | )(function* ( |
| 375 | admission: Pick<ActiveOpenCodeTurn, "admissionGeneration" | "admissionPending">, |
| 376 | generation: number, |
| 377 | readStatus: Effect.Effect<"busy" | "idle" | "unknown">, |
| 378 | ) { |
| 379 | if (admission.admissionGeneration !== generation || !admission.admissionPending) { |
| 380 | return "stale" as const; |
| 381 | } |
| 382 | const status = yield* readStatus.pipe( |
| 383 | Effect.timeoutOption("10 seconds"), |
| 384 | Effect.map(Option.getOrElse(() => "unknown" as const)), |
| 385 | ); |
| 386 | if (admission.admissionGeneration !== generation || !admission.admissionPending) { |
| 387 | return "stale" as const; |
| 388 | } |
| 389 | if (status !== "unknown") admission.admissionPending = false; |
| 390 | return status; |
| 391 | }); |
| 392 | |
| 393 | interface OpenCodeSubagentContext { |
| 394 | readonly nativeItemId: string; |
| 395 | readonly nodeId: OrchestrationV2Subagent["id"]; |
| 396 | readonly parentState: OpenCodeThreadState; |
| 397 | readonly parentTurn: ActiveOpenCodeTurn; |
| 398 | readonly prompt: string; |
| 399 | readonly title: string | null; |
| 400 | readonly startedAt: DateTime.Utc; |
| 401 | childSessionId: string | null; |
| 402 | childThreadId: ThreadId | null; |
| 403 | childProviderThreadId: OrchestrationV2ProviderThread["id"] | null; |
| 404 | model: string | null; |
| 405 | result: string | null; |
| 406 | // A background task call returns at launch; held here until its child session stops. |
| 407 | launch: ToolPart | null; |
| 408 | } |
| 409 | |
| 410 | /** Root work OpenCode began with no T3 turn, such as a background task's result; held until a run admits it. */ |
| 411 | interface OpenCodeWake { |
| 412 | readonly events: Array<OpenCodeEvent>; |
| 413 | // A user message alone can be a late update; only a busy root is work worth a run. |
| 414 | offered: boolean; |
| 415 | cancelling: boolean; |
| 416 | readonly admission: Deferred.Deferred<boolean>; |
| 417 | settled: Deferred.Deferred<void>; |
| 418 | } |
| 419 | |
| 420 | interface OpenCodeThreadState { |
| 421 | readonly nativeSessionId: string; |
| 422 | providerThread: OrchestrationV2ProviderThread; |
| 423 | appThread: OrchestrationV2AppThread | null; |
| 424 | activeTurn: ActiveOpenCodeTurn | null; |
| 425 | readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>; |
| 426 | readonly runtimeRequests: Map<string, OrchestrationV2RuntimeRequest>; |
| 427 | readonly messageRoles: Map<string, "user" | "assistant">; |
| 428 | readonly userMessageIds: Array<string>; |
| 429 | parentSubagent: OpenCodeSubagentContext | null; |
| 430 | // null: a child resumed after a restart, whose next ordinal is recovered from OpenCode. |
| 431 | nextChildTurnOrdinal: number | null; |
| 432 | nextAdmissionGeneration: number; |
| 433 | wake: OpenCodeWake | null; |
| 434 | readonly lifecyclePermit: Semaphore.Semaphore; |
| 435 | permission: PermissionRuleset; |
| 436 | /** Parent rules last written into this child's `permission`; empty for root sessions. */ |
| 437 | inheritedPermission: PermissionRuleset; |
| 438 | } |
| 439 | |
| 440 | interface OpenCodeRequestOwner { |
| 441 | readonly state: OpenCodeThreadState; |
| 442 | readonly turn: ActiveOpenCodeTurn; |
| 443 | readonly subagent: OpenCodeSubagentContext | null; |
| 444 | } |
| 445 | |
| 446 | function topLevelRequestOwner(state: OpenCodeThreadState): OpenCodeRequestOwner | undefined { |
| 447 | let owner = state; |
| 448 | let subagent: OpenCodeSubagentContext | null = null; |
| 449 | while (owner.parentSubagent !== null) { |
| 450 | subagent = owner.parentSubagent; |
| 451 | owner = subagent.parentState; |
| 452 | } |
| 453 | return owner.activeTurn === null ? undefined : { state: owner, turn: owner.activeTurn, subagent }; |
| 454 | } |
| 455 | |
| 456 | interface PendingOpenCodeRequest { |
| 457 | readonly requestId: RuntimeRequestId; |
| 458 | readonly nativeRequestId: string; |
| 459 | readonly nativeSessionId: string; |
| 460 | readonly turn: ActiveOpenCodeTurn; |
| 461 | readonly state: OpenCodeThreadState; |
| 462 | readonly nodeId: OrchestrationV2ExecutionNode["id"]; |
| 463 | readonly parentNodeId: OrchestrationV2ExecutionNode["id"]; |
| 464 | readonly turnItemId: OrchestrationV2TurnItem["id"]; |
| 465 | readonly requestKind: OpenCodePermissionRequestKind | "user_input"; |
| 466 | readonly createdAt: DateTime.Utc; |
| 467 | readonly permission?: PermissionRequest; |
| 468 | readonly question?: QuestionRequest; |
| 469 | } |
| 470 | |
| 471 | export interface OpenCodeAdapterV2Options { |
| 472 | readonly instanceId: ProviderInstanceId; |
| 473 | readonly settings: OpenCodeSettings; |
| 474 | readonly environment: NodeJS.ProcessEnv; |
| 475 | readonly nativeEventLogger?: ProviderEventLoggers.EventNdjsonLogger; |
| 476 | } |
| 477 | |
| 478 | export interface OpenCodeProtocolLogEvent { |
| 479 | readonly direction: "incoming" | "outgoing"; |
| 480 | readonly messageKind: "request" | "response" | "notification" | "error"; |
| 481 | readonly method: string; |
| 482 | readonly payload: unknown; |
| 483 | } |
| 484 | |
| 485 | function formatOpenCodeProtocolLogPayload(event: OpenCodeProtocolLogEvent) { |
| 486 | return { |
| 487 | direction: event.direction, |
| 488 | messageKind: event.messageKind, |
| 489 | method: structuralProtocolMethod(event.method), |
| 490 | payload: summarizeNativeProtocolPayload(event.payload), |
| 491 | }; |
| 492 | } |
| 493 | |
| 494 | export function makeOpenCodeProtocolLogger(input: { |
| 495 | readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined; |
| 496 | readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; |
| 497 | readonly providerInstanceId: ProviderInstanceId; |
| 498 | readonly providerSessionId: ProviderSessionId; |
| 499 | readonly threadId: ThreadId; |
| 500 | }): (event: OpenCodeProtocolLogEvent) => Effect.Effect<void, never> { |
| 501 | return (event) => |
| 502 | Effect.gen(function* () { |
| 503 | // Per-token deltas; the part's final message.part.updated is still logged. |
| 504 | if (!input.nativeEventLogger || event.method === "message.part.delta") return; |
| 505 | const observedAt = DateTime.formatIso(yield* DateTime.now); |
| 506 | const method = structuralProtocolMethod(event.method); |
| 507 | yield* input.nativeEventLogger.write( |
| 508 | { |
| 509 | observedAt, |
| 510 | event: { |
| 511 | id: yield* input.idAllocator.allocate.rawEvent({ |
| 512 | providerSessionId: input.providerSessionId, |
| 513 | method, |
| 514 | }), |
| 515 | kind: "protocol", |
| 516 | protocol: OPENCODE_SDK_PROTOCOL, |
| 517 | provider: OPENCODE_PROVIDER, |
| 518 | providerInstanceId: input.providerInstanceId, |
| 519 | providerSessionId: input.providerSessionId, |
| 520 | createdAt: observedAt, |
| 521 | threadId: input.threadId, |
| 522 | payload: formatOpenCodeProtocolLogPayload(event), |
| 523 | }, |
| 524 | }, |
| 525 | input.threadId, |
| 526 | ); |
| 527 | }).pipe( |
| 528 | Effect.catchCause((cause) => |
| 529 | Cause.hasInterrupts(cause) |
| 530 | ? Effect.interrupt |
| 531 | : Effect.logWarning("Failed to write native OpenCode event log.", { |
| 532 | errorTag: causeErrorTag(cause), |
| 533 | reasonCount: cause.reasons.length, |
| 534 | provider: OPENCODE_PROVIDER, |
| 535 | threadId: input.threadId, |
| 536 | }), |
| 537 | ), |
| 538 | ); |
| 539 | } |
| 540 | |
| 541 | function protocolError( |
| 542 | detail: string, |
| 543 | payload?: unknown, |
| 544 | ): ProviderAdapter.ProviderAdapterProtocolError { |
| 545 | return new ProviderAdapter.ProviderAdapterProtocolError({ |
| 546 | driver: OPENCODE_PROVIDER, |
| 547 | detail, |
| 548 | ...(payload === undefined ? {} : { payload }), |
| 549 | }); |
| 550 | } |
| 551 | |
| 552 | function nativeThreadId(providerThread: OrchestrationV2ProviderThread): string { |
| 553 | const nativeId = providerThread.nativeThreadRef?.nativeId; |
| 554 | if (nativeId === null || nativeId === undefined) { |
| 555 | throw protocolError(`Provider thread ${providerThread.id} has no OpenCode session id`); |
| 556 | } |
| 557 | return nativeId; |
| 558 | } |
| 559 | |
| 560 | function dateTimeFromEpoch(value: number | undefined, fallback: DateTime.Utc): DateTime.Utc { |
| 561 | if (value === undefined) return fallback; |
| 562 | return Option.getOrElse(DateTime.make(value), () => fallback); |
| 563 | } |
| 564 | |
| 565 | function nonEmptyString(value: unknown): string | undefined { |
| 566 | return typeof value === "string" && value.trim().length > 0 ? value : undefined; |
| 567 | } |
| 568 | |
| 569 | function recordValue(input: unknown, key: string): unknown { |
| 570 | return typeof input === "object" && input !== null && key in input |
| 571 | ? (input as Record<string, unknown>)[key] |
| 572 | : undefined; |
| 573 | } |
| 574 | |
| 575 | function recordString(input: unknown, ...keys: ReadonlyArray<string>): string | undefined { |
| 576 | for (const key of keys) { |
| 577 | const value = nonEmptyString(recordValue(input, key)); |
| 578 | if (value !== undefined) return value; |
| 579 | } |
| 580 | return undefined; |
| 581 | } |
| 582 | |
| 583 | function sdkResponseForRawLog(value: unknown): unknown { |
| 584 | if (typeof value !== "object" || value === null) return value; |
| 585 | if ("data" in value) return { data: (value as { readonly data?: unknown }).data ?? null }; |
| 586 | if ("stream" in value) return { subscribed: true }; |
| 587 | return value; |
| 588 | } |
| 589 | |
| 590 | type OpenCodePermissionRequestKind = Extract< |
| 591 | ProviderRequestKind, |
| 592 | "command" | "file-read" | "file-change" |
| 593 | >; |
| 594 | |
| 595 | export function openCodePermissionRequestKind( |
| 596 | permission: string, |
| 597 | toolName?: string, |
| 598 | ): OpenCodePermissionRequestKind { |
| 599 | const normalized = permission.toLowerCase(); |
| 600 | const normalizedTool = toolName?.toLowerCase() ?? ""; |
| 601 | if ( |
| 602 | normalized === "edit" || |
| 603 | normalized === "write" || |
| 604 | normalized === "patch" || |
| 605 | normalized === "apply_patch" || |
| 606 | normalizedTool === "edit" || |
| 607 | normalizedTool === "write" || |
| 608 | normalizedTool === "patch" || |
| 609 | normalizedTool === "apply_patch" |
| 610 | ) { |
| 611 | return "file-change"; |
| 612 | } |
| 613 | if ( |
| 614 | normalized === "read" || |
| 615 | normalized === "glob" || |
| 616 | normalized === "grep" || |
| 617 | normalized === "lsp" || |
| 618 | normalized === "external_directory" || |
| 619 | normalizedTool === "read" || |
| 620 | normalizedTool.includes("glob") || |
| 621 | normalizedTool.includes("grep") || |
| 622 | normalizedTool.includes("search") |
| 623 | ) { |
| 624 | return "file-read"; |
| 625 | } |
| 626 | return "command"; |
| 627 | } |
| 628 | |
| 629 | const OPENCODE_ALWAYS_ALLOWED_PERMISSIONS = [ |
| 630 | "question", |
| 631 | "read", |
| 632 | "glob", |
| 633 | "grep", |
| 634 | "lsp", |
| 635 | "todowrite", |
| 636 | "task", |
| 637 | "skill", |
| 638 | ] as const; |
| 639 | |
| 640 | const OPENCODE_RESTRICTED_PERMISSIONS = [ |
| 641 | "bash", |
| 642 | "edit", |
| 643 | "webfetch", |
| 644 | "websearch", |
| 645 | "codesearch", |
| 646 | "external_directory", |
| 647 | "doom_loop", |
| 648 | ] as const; |
| 649 | |
| 650 | /** OpenCode has no OS sandbox; permission rules must enforce non-interactive policies too. */ |
| 651 | export function openCodePermissionRules( |
| 652 | runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, |
| 653 | ): PermissionRuleset { |
| 654 | const sandboxPolicy = recordValue(runtimePolicy, "sandboxPolicy"); |
| 655 | const sandboxType = recordString(sandboxPolicy, "type"); |
| 656 | const rawApprovalPolicy = runtimePolicy.approvalPolicy; |
| 657 | const approvalPolicy = nonEmptyString(rawApprovalPolicy); |
| 658 | const requiresApproval = |
| 659 | approvalPolicy === undefined |
| 660 | ? (typeof rawApprovalPolicy === "object" && rawApprovalPolicy !== null) || |
| 661 | runtimePolicy.runtimeMode !== "full-access" |
| 662 | : approvalPolicy !== "never"; |
| 663 | const externallySandboxed = sandboxType === "externalSandbox"; |
| 664 | const dangerFullAccess = sandboxType === "dangerFullAccess"; |
| 665 | const implicitFullAccess = |
| 666 | sandboxType === undefined && runtimePolicy.runtimeMode === "full-access"; |
| 667 | |
| 668 | if (!requiresApproval && (externallySandboxed || dangerFullAccess || implicitFullAccess)) { |
| 669 | // Task children copy only external_directory and deny rules before their first tool call. |
| 670 | return [ |
| 671 | { permission: "*", pattern: "*", action: "allow" }, |
| 672 | { permission: "external_directory", pattern: "*", action: "allow" }, |
| 673 | ]; |
| 674 | } |
| 675 | |
| 676 | // Children initially inherit only denies; seed them before overrides to protect the policy-install gap. |
| 677 | const rules: PermissionRuleset = [ |
| 678 | { permission: "*", pattern: "*", action: "deny" }, |
| 679 | ...OPENCODE_RESTRICTED_PERMISSIONS.map((permission) => ({ |
| 680 | permission, |
| 681 | pattern: "*", |
| 682 | action: "deny" as const, |
| 683 | })), |
| 684 | ]; |
| 685 | |
| 686 | if (requiresApproval) { |
| 687 | rules.push({ permission: "*", pattern: "*", action: "ask" }); |
| 688 | for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) { |
| 689 | rules.push({ permission, pattern: "*", action: "ask" }); |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | rules.push( |
| 694 | ...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({ |
| 695 | permission, |
| 696 | pattern: "*", |
| 697 | action: "allow" as const, |
| 698 | })), |
| 699 | ); |
| 700 | |
| 701 | rules.push( |
| 702 | { permission: "read", pattern: "*.env", action: requiresApproval ? "ask" : "deny" }, |
| 703 | { permission: "read", pattern: "*.env.*", action: requiresApproval ? "ask" : "deny" }, |
| 704 | { permission: "read", pattern: "*.env.example", action: "allow" }, |
| 705 | ); |
| 706 | |
| 707 | if ( |
| 708 | runtimePolicy.runtimeMode === "auto-accept-edits" || |
| 709 | (!requiresApproval && sandboxType === "workspaceWrite") |
| 710 | ) { |
| 711 | rules.push({ permission: "edit", pattern: "*", action: "allow" }); |
| 712 | } |
| 713 | |
| 714 | if (!requiresApproval && recordValue(sandboxPolicy, "networkAccess") === true) { |
| 715 | for (const permission of ["webfetch", "websearch", "codesearch"] as const) { |
| 716 | rules.push({ permission, pattern: "*", action: "allow" }); |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | if (!requiresApproval && sandboxType === "readOnly") { |
| 721 | const access = recordValue(sandboxPolicy, "access"); |
| 722 | if (recordString(access, "type") === "fullAccess") { |
| 723 | rules.push({ permission: "external_directory", pattern: "*", action: "allow" }); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | if (!requiresApproval && sandboxType === "workspaceWrite") { |
| 728 | const writableRoots = recordValue(sandboxPolicy, "writableRoots"); |
| 729 | if (Array.isArray(writableRoots)) { |
| 730 | for (const root of writableRoots) { |
| 731 | if (typeof root === "string" && root.trim().length > 0) { |
| 732 | rules.push({ |
| 733 | permission: "external_directory", |
| 734 | pattern: `${root.replace(/\/$/, "")}/*`, |
| 735 | action: "allow", |
| 736 | }); |
| 737 | } |
| 738 | } |
| 739 | } |
| 740 | } |
| 741 | |
| 742 | return rules; |
| 743 | } |
| 744 | |
| 745 | function permissionRuleEquals( |
| 746 | left: PermissionRuleset[number], |
| 747 | right: PermissionRuleset[number], |
| 748 | ): boolean { |
| 749 | return ( |
| 750 | left.permission === right.permission && |
| 751 | left.pattern === right.pattern && |
| 752 | left.action === right.action |
| 753 | ); |
| 754 | } |
| 755 | |
| 756 | /** |
| 757 | * Children inherit only deny/external-directory rules; restore parent policy while retaining agent restrictions. |
| 758 | * `previousParentRules` are the parent rules already written into `childRules`. |
| 759 | */ |
| 760 | export function openCodeChildPermissionRules( |
| 761 | runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, |
| 762 | childRules: PermissionRuleset, |
| 763 | previousParentRules: PermissionRuleset = [], |
| 764 | ): PermissionRuleset { |
| 765 | const parentRules = openCodePermissionRules(runtimePolicy); |
| 766 | const inheritedRules = [ |
| 767 | ...parentRules.filter( |
| 768 | (rule) => rule.permission === "external_directory" || rule.action === "deny", |
| 769 | ), |
| 770 | ...previousParentRules, |
| 771 | ]; |
| 772 | const childSpecificRules = childRules.filter( |
| 773 | (childRule) => |
| 774 | !inheritedRules.some((inheritedRule) => permissionRuleEquals(childRule, inheritedRule)), |
| 775 | ); |
| 776 | return [...parentRules, ...childSpecificRules]; |
| 777 | } |
| 778 | |
| 779 | /** Boundaries are exclusive: use the next user message, or omit at head to retain the selected turn. */ |
| 780 | export function openCodeBoundaryAfterProviderTurn( |
| 781 | providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>, |
| 782 | selectedProviderTurnId: OrchestrationV2ProviderTurn["id"], |
| 783 | ): string | undefined { |
| 784 | const selected = providerTurns.find((turn) => turn.id === selectedProviderTurnId); |
| 785 | if (selected === undefined) return undefined; |
| 786 | return providerTurns |
| 787 | .filter((turn) => turn.ordinal > selected.ordinal) |
| 788 | .toSorted((left, right) => left.ordinal - right.ordinal) |
| 789 | .map((turn) => turn.nativeTurnRef?.nativeId) |
| 790 | .find((nativeId): nativeId is string => nativeId !== null && nativeId !== undefined); |
| 791 | } |
| 792 | |
| 793 | function toolStatus(part: ToolPart): { |
| 794 | readonly node: OrchestrationV2ExecutionNode["status"]; |
| 795 | readonly item: OrchestrationV2TurnItem["status"]; |
| 796 | } { |
| 797 | switch (part.state.status) { |
| 798 | case "pending": |
| 799 | return { node: "pending", item: "pending" }; |
| 800 | case "running": |
| 801 | return { node: "running", item: "running" }; |
| 802 | case "completed": |
| 803 | return openCodeCommandFailed(part.tool, part.state.metadata) |
| 804 | ? { node: "failed", item: "failed" } |
| 805 | : { node: "completed", item: "completed" }; |
| 806 | case "error": |
| 807 | // Stop marks in-flight tools this way; OpenCode's own UI shows them as cancelled. |
| 808 | return part.state.metadata?.["interrupted"] === true || |
| 809 | part.state.error === "Tool execution aborted" || |
| 810 | (part.tool === "task" && part.state.error === "Task cancelled") |
| 811 | ? { node: "interrupted", item: "interrupted" } |
| 812 | : { node: "failed", item: "failed" }; |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | function toolInput(part: ToolPart): Record<string, unknown> { |
| 817 | return part.state.input; |
| 818 | } |
| 819 | |
| 820 | function toolOutput(part: ToolPart): string | undefined { |
| 821 | if (part.state.status === "completed") return part.state.output; |
| 822 | if (part.state.status === "error") return part.state.error; |
| 823 | return undefined; |
| 824 | } |
| 825 | |
| 826 | function toolStartedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc { |
| 827 | return dateTimeFromEpoch( |
| 828 | part.state.status === "pending" ? undefined : part.state.time.start, |
| 829 | now, |
| 830 | ); |
| 831 | } |
| 832 | |
| 833 | function toolCompletedAt(part: ToolPart, now: DateTime.Utc): DateTime.Utc | null { |
| 834 | return part.state.status === "completed" || part.state.status === "error" |
| 835 | ? dateTimeFromEpoch(part.state.time.end, now) |
| 836 | : null; |
| 837 | } |
| 838 | |
| 839 | function toolTitle(part: ToolPart): string | null { |
| 840 | return part.state.status === "running" || part.state.status === "completed" |
| 841 | ? (part.state.title ?? null) |
| 842 | : null; |
| 843 | } |
| 844 | |
| 845 | function toolModel(part: ToolPart): string | null { |
| 846 | const metadata = |
| 847 | part.state.status === "running" || |
| 848 | part.state.status === "completed" || |
| 849 | part.state.status === "error" |
| 850 | ? part.state.metadata |
| 851 | : undefined; |
| 852 | const model = recordValue(metadata, "model"); |
| 853 | const providerId = recordString(model, "providerID", "providerId"); |
| 854 | const modelId = recordString(model, "modelID", "modelId", "id"); |
| 855 | return providerId !== undefined && modelId !== undefined ? `${providerId}/${modelId}` : null; |
| 856 | } |
| 857 | |
| 858 | function taskSessionId(part: ToolPart): string | null { |
| 859 | const metadata = |
| 860 | part.state.status === "running" || |
| 861 | part.state.status === "completed" || |
| 862 | part.state.status === "error" |
| 863 | ? part.state.metadata |
| 864 | : undefined; |
| 865 | return recordString(metadata, "sessionId", "sessionID") ?? null; |
| 866 | } |
| 867 | |
| 868 | function makeProviderThread(input: { |
| 869 | readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; |
| 870 | readonly providerInstanceId: ProviderInstanceId; |
| 871 | readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; |
| 872 | readonly appThreadId: OrchestrationV2ProviderThread["appThreadId"]; |
| 873 | readonly ownerNodeId?: OrchestrationV2ProviderThread["ownerNodeId"]; |
| 874 | readonly nativeSession: OpenCodeSession; |
| 875 | readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"]; |
| 876 | readonly now: DateTime.Utc; |
| 877 | }): OrchestrationV2ProviderThread { |
| 878 | const createdAt = dateTimeFromEpoch(input.nativeSession.time.created, input.now); |
| 879 | return { |
| 880 | id: input.idAllocator.derive.providerThread({ |
| 881 | driver: OPENCODE_PROVIDER, |
| 882 | nativeThreadId: input.nativeSession.id, |
| 883 | }), |
| 884 | driver: OPENCODE_PROVIDER, |
| 885 | providerInstanceId: input.providerInstanceId, |
| 886 | providerSessionId: input.providerSessionId, |
| 887 | appThreadId: input.appThreadId, |
| 888 | ownerNodeId: input.ownerNodeId ?? null, |
| 889 | nativeThreadRef: { |
| 890 | driver: OPENCODE_PROVIDER, |
| 891 | nativeId: input.nativeSession.id, |
| 892 | strength: "strong", |
| 893 | }, |
| 894 | nativeConversationHeadRef: null, |
| 895 | status: "idle", |
| 896 | firstRunOrdinal: null, |
| 897 | lastRunOrdinal: null, |
| 898 | handoffIds: [], |
| 899 | forkedFrom: input.forkedFrom ?? null, |
| 900 | createdAt, |
| 901 | updatedAt: dateTimeFromEpoch(input.nativeSession.time.updated, input.now), |
| 902 | }; |
| 903 | } |
| 904 | |
| 905 | function providerRef(nativeId: string, strength: "strong" | "weak" = "strong") { |
| 906 | return { |
| 907 | driver: OPENCODE_PROVIDER, |
| 908 | nativeId, |
| 909 | strength, |
| 910 | } satisfies OrchestrationV2ProviderRef; |
| 911 | } |
| 912 | |
| 913 | function openCodeErrorMessage(event: Extract<OpenCodeEvent, { type: "session.error" }>): string { |
| 914 | const error = event.properties.error; |
| 915 | if (error === undefined) return "OpenCode session failed without an error payload."; |
| 916 | const statusCode = recordValue(error.data, "statusCode"); |
| 917 | return ( |
| 918 | readableProviderErrorMessage( |
| 919 | recordString(error.data, "message"), |
| 920 | typeof statusCode === "number" ? statusCode : undefined, |
| 921 | recordString(error.data, "responseBody"), |
| 922 | ) ?? error.name |
| 923 | ); |
| 924 | } |
| 925 | |
| 926 | function terminalStatusForError( |
| 927 | event: Extract<OpenCodeEvent, { type: "session.error" }>, |
| 928 | turn: ActiveOpenCodeTurn, |
| 929 | ): TerminalTurnStatus { |
| 930 | return turn.interrupted || isMessageAbortedError(event) ? "interrupted" : "failed"; |
| 931 | } |
| 932 | |
| 933 | // Events of one session's work; other events update adapter bookkeeping and are never held. |
| 934 | function sessionWorkEventSessionId(event: OpenCodeEvent): string | undefined { |
| 935 | switch (event.type) { |
| 936 | case "message.part.updated": |
| 937 | return event.properties.part.sessionID; |
| 938 | case "message.updated": |
| 939 | case "message.part.delta": |
| 940 | case "todo.updated": |
| 941 | case "session.compacted": |
| 942 | case "session.status": |
| 943 | case "session.idle": |
| 944 | case "session.error": |
| 945 | case "permission.asked": |
| 946 | case "question.asked": |
| 947 | return event.properties.sessionID; |
| 948 | default: |
| 949 | return undefined; |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | function isMessageAbortedError(event: Extract<OpenCodeEvent, { type: "session.error" }>): boolean { |
| 954 | return event.properties.error?.name === "MessageAbortedError"; |
| 955 | } |
| 956 | |
| 957 | // Node's fetch reports these when the connection failed before the request was sent. |
| 958 | const OPENCODE_UNSENT_REQUEST_CODES = new Set([ |
| 959 | "ECONNREFUSED", |
| 960 | "ENOTFOUND", |
| 961 | "EAI_AGAIN", |
| 962 | "EHOSTUNREACH", |
| 963 | "ENETUNREACH", |
| 964 | "UND_ERR_CONNECT_TIMEOUT", |
| 965 | ]); |
| 966 | |
| 967 | // Only an HTTP error reply (the SDK puts its status on `cause`) or an unsent request |
| 968 | // proves OpenCode did not take a prompt; a reset or timeout after sending is ambiguous. |
| 969 | function isOpenCodePromptRejected(error: unknown): boolean { |
| 970 | const cause = OpenCodeRuntime.isOpenCodeRuntimeError(error) ? error.cause : error; |
| 971 | if (!(cause instanceof Error)) return false; |
| 972 | const reason = cause.cause as { readonly status?: unknown; readonly code?: unknown } | undefined; |
| 973 | return ( |
| 974 | typeof reason?.status === "number" || |
| 975 | (typeof reason?.code === "string" && OPENCODE_UNSENT_REQUEST_CODES.has(reason.code)) |
| 976 | ); |
| 977 | } |
| 978 | |
| 979 | function isOpenCodeNotFound(cause: unknown): boolean { |
| 980 | const seen = new Set<unknown>(); |
| 981 | const queue: Array<unknown> = [cause]; |
| 982 | for (let steps = 0; queue.length > 0 && steps < 32; steps += 1) { |
| 983 | const node = queue.shift(); |
| 984 | if (node === null || typeof node !== "object" || seen.has(node)) { |
| 985 | continue; |
| 986 | } |
| 987 | seen.add(node); |
| 988 | const record = node as Record<string, unknown>; |
| 989 | |
| 990 | const response = record.response; |
| 991 | const statuses = [ |
| 992 | record.status, |
| 993 | record.statusCode, |
| 994 | response !== null && typeof response === "object" |
| 995 | ? (response as { readonly status?: unknown }).status |
| 996 | : undefined, |
| 997 | ].filter((status): status is number => typeof status === "number"); |
| 998 | if (statuses.includes(404)) { |
| 999 | return true; |
| 1000 | } |
| 1001 | if (statuses.length > 0) { |
| 1002 | continue; |
| 1003 | } |
| 1004 | |
| 1005 | const name = record.name; |
| 1006 | if (typeof name === "string" && name.toLowerCase() === "notfounderror") { |
| 1007 | return true; |
| 1008 | } |
| 1009 | |
| 1010 | for (const key of ["cause", "body", "error", "data"] as const) { |
| 1011 | if (record[key] !== undefined) { |
| 1012 | queue.push(record[key]); |
| 1013 | } |
| 1014 | } |
| 1015 | } |
| 1016 | return false; |
| 1017 | } |
| 1018 | |
| 1019 | function unwrapData<A>(operation: string, result: { readonly data?: A }): NonNullable<A> { |
| 1020 | if (result.data === undefined) { |
| 1021 | throw new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 1022 | operation, |
| 1023 | detail: `OpenCode ${operation} returned no response payload.`, |
| 1024 | }); |
| 1025 | } |
| 1026 | return result.data as NonNullable<A>; |
| 1027 | } |
| 1028 | |
| 1029 | export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function* ( |
| 1030 | options: OpenCodeAdapterV2Options, |
| 1031 | ) { |
| 1032 | const runtime = yield* OpenCodeRuntime.OpenCodeRuntime; |
| 1033 | const idAllocator = yield* IdAllocator.IdAllocatorV2; |
| 1034 | const host = yield* ProviderHost.ProviderHost; |
| 1035 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 1036 | const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; |
| 1037 | const messageIdClock = yield* Ref.make({ epochMillis: -1, counter: 0 }); |
| 1038 | |
| 1039 | return ProviderAdapter.ProviderAdapterV2.of({ |
| 1040 | instanceId: options.instanceId, |
| 1041 | driver: OPENCODE_PROVIDER, |
| 1042 | checksVersionAtHandshake: true, |
| 1043 | getCapabilities: Effect.fn("OpencodeAdapter.getCapabilities")(function () { |
| 1044 | return Effect.succeed(OpenCodeProviderCapabilitiesV2); |
| 1045 | }), |
| 1046 | planSelectionTransition: Effect.fn("OpencodeAdapter.planSelectionTransition")(function () { |
| 1047 | return Effect.succeed(turnScopedSelectionTransition()); |
| 1048 | }), |
| 1049 | openSession: Effect.fn("OpenCodeAdapterV2.openSession")( |
| 1050 | function* (input: ProviderAdapter.ProviderAdapterV2OpenSessionInput) { |
| 1051 | const scope = yield* Effect.scope; |
| 1052 | const cwd = input.runtimePolicy.cwd ?? host.paths.cwd; |
| 1053 | const connection = yield* runtime.connectToOpenCodeServer({ |
| 1054 | binaryPath: options.settings.binaryPath, |
| 1055 | directory: cwd, |
| 1056 | serverUrl: options.settings.serverUrl, |
| 1057 | ...(settingsSecretLiteral(options.settings.serverPassword) |
| 1058 | ? { serverPassword: settingsSecretLiteral(options.settings.serverPassword) } |
| 1059 | : {}), |
| 1060 | environment: options.environment, |
| 1061 | }); |
| 1062 | const broken = brokenVersionDetail({ |
| 1063 | name: "OpenCode", |
| 1064 | version: connection.version, |
| 1065 | advisory: yield* host.compatibility(OPENCODE_PROVIDER, connection.version), |
| 1066 | }); |
| 1067 | if (broken !== undefined) { |
| 1068 | return yield* new ProviderSetupError({ |
| 1069 | instanceId: options.instanceId, |
| 1070 | operation: "runtime", |
| 1071 | detail: broken, |
| 1072 | }); |
| 1073 | } |
| 1074 | const client = runtime.createOpenCodeSdkClient({ |
| 1075 | baseUrl: connection.url, |
| 1076 | directory: cwd, |
| 1077 | ...(connection.serverPassword !== undefined |
| 1078 | ? { serverPassword: connection.serverPassword } |
| 1079 | : {}), |
| 1080 | }); |
| 1081 | |
| 1082 | const mcpSession = yield* mcpSessions.read(input.threadId); |
| 1083 | const hasT3Mcp = mcpSession !== undefined && !connection.external; |
| 1084 | const orchestrationSystemPrompt = t3OrchestrationSystemPrompt( |
| 1085 | hasT3Mcp, |
| 1086 | mcpSession?.capabilities?.has("device") === true, |
| 1087 | ); |
| 1088 | if (hasT3Mcp) { |
| 1089 | yield* OpenCodeRuntime.runOpenCodeSdk("mcp.add", () => |
| 1090 | client.mcp.add({ |
| 1091 | name: "t3-code", |
| 1092 | config: { |
| 1093 | type: "remote", |
| 1094 | url: mcpSession.endpoint, |
| 1095 | headers: { Authorization: mcpSession.authorizationHeader }, |
| 1096 | oauth: false, |
| 1097 | }, |
| 1098 | }), |
| 1099 | ); |
| 1100 | } |
| 1101 | |
| 1102 | const now = yield* DateTime.now; |
| 1103 | let sessionEntity: OrchestrationV2ProviderSession = { |
| 1104 | id: input.providerSessionId, |
| 1105 | driver: OPENCODE_PROVIDER, |
| 1106 | providerInstanceId: options.instanceId, |
| 1107 | status: "ready", |
| 1108 | cwd, |
| 1109 | model: input.modelSelection.model, |
| 1110 | capabilities: OpenCodeProviderCapabilitiesV2, |
| 1111 | createdAt: now, |
| 1112 | updatedAt: now, |
| 1113 | lastError: null, |
| 1114 | }; |
| 1115 | const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>(); |
| 1116 | let nativeStreamFailure: OrchestrationV2ProviderFailure | null = null; |
| 1117 | const threads = new Map<string, OpenCodeThreadState>(); |
| 1118 | const variantCache: OpenCodeRuntime.OpenCodeVariantCache = new Map(); |
| 1119 | const commandReceipts = new Map<string, Deferred.Deferred<void>>(); |
| 1120 | const commandControllers = new Map<string, Set<AbortController>>(); |
| 1121 | const pendingRequests = new Map<string, PendingOpenCodeRequest>(); |
| 1122 | const pendingRequestsByNativeId = new Map<string, PendingOpenCodeRequest>(); |
| 1123 | const subagentsByNativeItemId = new Map<string, OpenCodeSubagentContext>(); |
| 1124 | const subagentsByChildSessionId = new Map<string, OpenCodeSubagentContext>(); |
| 1125 | const relatedSessionOwners = new Map<string, OpenCodeThreadState>(); |
| 1126 | // Busy children outlive parent settlement; keep their server open. |
| 1127 | const busySessionIds = new Set<string>(); |
| 1128 | // A background task returns before its new child session reports busy. |
| 1129 | const unstartedSessionIds = new Set<string>(); |
| 1130 | // A child can error before any turn of it is projected; its next idle settles the launch. |
| 1131 | const sessionErrorOutcomes = new Map<string, TerminalTurnStatus>(); |
| 1132 | // Remember settled requests across routing retries to prevent resurrection; only recent IDs matter. |
| 1133 | const settledNativeRequestIds = new Set<string>(); |
| 1134 | const pendingChildRequestRoutes = new Set<string>(); |
| 1135 | const rememberSettledRequest = (nativeRequestId: string) => { |
| 1136 | if (settledNativeRequestIds.size >= 2_048) settledNativeRequestIds.clear(); |
| 1137 | settledNativeRequestIds.add(nativeRequestId); |
| 1138 | }; |
| 1139 | // @effect-diagnostics-next-line abortControllerInEffect:off - Session closure aborts this stream independently of the creation fiber. |
| 1140 | const abortController = new AbortController(); |
| 1141 | let closing = false; |
| 1142 | let hasConnected = false; |
| 1143 | // Orders native events with turn installation, so a held wake replays before later events. |
| 1144 | const eventPermit = Semaphore.makeUnsafe(1); |
| 1145 | |
| 1146 | const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => |
| 1147 | Queue.offer(events, event).pipe(Effect.asVoid); |
| 1148 | |
| 1149 | const logProtocolEvent = makeOpenCodeProtocolLogger({ |
| 1150 | nativeEventLogger: options.nativeEventLogger, |
| 1151 | idAllocator, |
| 1152 | providerInstanceId: options.instanceId, |
| 1153 | providerSessionId: input.providerSessionId, |
| 1154 | threadId: input.threadId, |
| 1155 | }); |
| 1156 | |
| 1157 | const sdkCall = <A>( |
| 1158 | method: string, |
| 1159 | payload: unknown, |
| 1160 | call: (signal: AbortSignal) => Promise<A>, |
| 1161 | ): Effect.Effect<A, OpenCodeRuntime.OpenCodeRuntimeError> => |
| 1162 | logProtocolEvent({ |
| 1163 | direction: "outgoing", |
| 1164 | messageKind: "request", |
| 1165 | method, |
| 1166 | payload, |
| 1167 | }).pipe( |
| 1168 | Effect.andThen(OpenCodeRuntime.runOpenCodeSdk(method, call)), |
| 1169 | Effect.tap((response) => |
| 1170 | logProtocolEvent({ |
| 1171 | direction: "incoming", |
| 1172 | messageKind: "response", |
| 1173 | method, |
| 1174 | payload: sdkResponseForRawLog(response), |
| 1175 | }), |
| 1176 | ), |
| 1177 | ); |
| 1178 | |
| 1179 | const abortDescendants = Effect.fn("OpencodeAdapter.abortDescendants")(function* ( |
| 1180 | rootId: string, |
| 1181 | ) { |
| 1182 | const visited = new Set([rootId]); |
| 1183 | const semaphore = Semaphore.makeUnsafe(8); |
| 1184 | const visit = Effect.fn("OpencodeAdapter.visit")(function* ( |
| 1185 | sessionId: string, |
| 1186 | abort: boolean, |
| 1187 | ): Effect.fn.Return<OpenCodeRuntime.OpenCodeRuntimeError | undefined> { |
| 1188 | const abortResult = abort |
| 1189 | ? yield* sdkCall("session.abort", { sessionID: sessionId }, (signal) => |
| 1190 | client.session.abort({ sessionID: sessionId }, { signal }), |
| 1191 | ).pipe( |
| 1192 | semaphore.withPermit, |
| 1193 | Effect.catchIf(isOpenCodeNotFound, () => Effect.void), |
| 1194 | Effect.result, |
| 1195 | ) |
| 1196 | : undefined; |
| 1197 | const childrenResult = yield* sdkCall( |
| 1198 | "session.children", |
| 1199 | { sessionID: sessionId }, |
| 1200 | (signal) => client.session.children({ sessionID: sessionId }, { signal }), |
| 1201 | ).pipe( |
| 1202 | semaphore.withPermit, |
| 1203 | Effect.catchIf(isOpenCodeNotFound, () => Effect.void), |
| 1204 | Effect.result, |
| 1205 | ); |
| 1206 | const firstFailure = abortResult?._tag === "Failure" ? abortResult.failure : undefined; |
| 1207 | if (childrenResult._tag === "Failure") return firstFailure ?? childrenResult.failure; |
| 1208 | const fresh = (childrenResult.success?.data ?? []).filter((child) => { |
| 1209 | if (visited.has(child.id)) return false; |
| 1210 | visited.add(child.id); |
| 1211 | return true; |
| 1212 | }); |
| 1213 | const failures = yield* Effect.forEach(fresh, (child) => visit(child.id, true), { |
| 1214 | concurrency: 8, |
| 1215 | }); |
| 1216 | return firstFailure ?? failures.find((failure) => failure !== undefined); |
| 1217 | }); |
| 1218 | const failure = yield* visit(rootId, false); |
| 1219 | if (failure) return yield* failure; |
| 1220 | }, Effect.timeout("15 seconds")); |
| 1221 | |
| 1222 | const updateProviderSession = |
| 1223 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 1224 | Effect.fnUntraced(function* ( |
| 1225 | status: OrchestrationV2ProviderSession["status"], |
| 1226 | lastError: string | null = sessionEntity.lastError, |
| 1227 | ) { |
| 1228 | const updatedAt = yield* DateTime.now; |
| 1229 | sessionEntity = { ...sessionEntity, status, lastError, updatedAt }; |
| 1230 | yield* emitProviderEvent({ |
| 1231 | type: "provider_session.updated", |
| 1232 | driver: OPENCODE_PROVIDER, |
| 1233 | providerSession: sessionEntity, |
| 1234 | }); |
| 1235 | }); |
| 1236 | |
| 1237 | const updateProviderThread = |
| 1238 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 1239 | Effect.fnUntraced(function* ( |
| 1240 | state: OpenCodeThreadState, |
| 1241 | patch: Partial<OrchestrationV2ProviderThread>, |
| 1242 | ) { |
| 1243 | const updatedAt = yield* DateTime.now; |
| 1244 | state.providerThread = { ...state.providerThread, ...patch, updatedAt }; |
| 1245 | yield* emitProviderEvent({ |
| 1246 | type: "provider_thread.updated", |
| 1247 | driver: OPENCODE_PROVIDER, |
| 1248 | providerThread: state.providerThread, |
| 1249 | }); |
| 1250 | }); |
| 1251 | |
| 1252 | const itemOrdinal = (turn: ActiveOpenCodeTurn, nativeItemId: string): number => { |
| 1253 | const existing = turn.itemOrdinals.get(nativeItemId); |
| 1254 | if (existing !== undefined) return existing; |
| 1255 | const ordinal = turn.nextItemOrdinal++; |
| 1256 | turn.itemOrdinals.set(nativeItemId, ordinal); |
| 1257 | return ordinal; |
| 1258 | }; |
| 1259 | |
| 1260 | const emitProviderTurn = ( |
| 1261 | state: OpenCodeThreadState, |
| 1262 | turn: ActiveOpenCodeTurn, |
| 1263 | status: OrchestrationV2ProviderTurn["status"], |
| 1264 | completedAt: DateTime.Utc | null, |
| 1265 | ) => { |
| 1266 | const providerTurn: OrchestrationV2ProviderTurn = { |
| 1267 | ...turn.providerTurn, |
| 1268 | nativeTurnRef: |
| 1269 | turn.nativeUserMessageId === null |
| 1270 | ? turn.providerTurn.nativeTurnRef |
| 1271 | : providerRef(turn.nativeUserMessageId, "weak"), |
| 1272 | status, |
| 1273 | completedAt, |
| 1274 | ...(completedAt === null |
| 1275 | ? {} |
| 1276 | : { |
| 1277 | turnTokenUsage: |
| 1278 | turn.usage.partIds.size === 0 |
| 1279 | ? { |
| 1280 | usageScope: "main_agent" as const, |
| 1281 | usageStatus: "unavailable" as const, |
| 1282 | hasSubagents: turn.usage.hasSubagents, |
| 1283 | } |
| 1284 | : { |
| 1285 | usageScope: "main_agent" as const, |
| 1286 | usageStatus: |
| 1287 | status === "completed" && |
| 1288 | turn.usage.complete && |
| 1289 | turn.usage.unresolvedStepsByMessageId.size === 0 |
| 1290 | ? ("complete" as const) |
| 1291 | : ("partial" as const), |
| 1292 | inputTokens: turn.usage.inputTokens, |
| 1293 | cachedInputTokens: turn.usage.cachedInputTokens, |
| 1294 | cacheCreationTokens: turn.usage.cacheCreationTokens, |
| 1295 | outputTokens: turn.usage.outputTokens, |
| 1296 | reasoningTokens: turn.usage.reasoningTokens, |
| 1297 | hasSubagents: turn.usage.hasSubagents, |
| 1298 | }, |
| 1299 | ...openCodeContextUsage( |
| 1300 | turn.usage.lastStep, |
| 1301 | variantCache.get(turn.modelSelection.model.trim())?.contextWindow, |
| 1302 | completedAt, |
| 1303 | ), |
| 1304 | }), |
| 1305 | }; |
| 1306 | Object.assign(turn.providerTurn, providerTurn); |
| 1307 | state.providerTurns.set(String(providerTurn.id), providerTurn); |
| 1308 | return emitProviderEvent({ |
| 1309 | type: "provider_turn.updated", |
| 1310 | driver: OPENCODE_PROVIDER, |
| 1311 | threadId: turn.threadId, |
| 1312 | providerTurn, |
| 1313 | }); |
| 1314 | }; |
| 1315 | |
| 1316 | const emitTextPart = Effect.fnUntraced(function* ( |
| 1317 | state: OpenCodeThreadState, |
| 1318 | turn: ActiveOpenCodeTurn, |
| 1319 | part: Extract<OpenCodePart, { type: "text" | "reasoning" }>, |
| 1320 | forceCompleted = false, |
| 1321 | ) { |
| 1322 | if (part.type === "text" && (part.ignored === true || part.synthetic === true)) return; |
| 1323 | if (part.text.length === 0) return; |
| 1324 | const emittedAt = yield* DateTime.now; |
| 1325 | const isCompleted = forceCompleted || part.time?.end !== undefined; |
| 1326 | const startedAt = dateTimeFromEpoch(part.time?.start, emittedAt); |
| 1327 | const completedAt = isCompleted ? dateTimeFromEpoch(part.time?.end, emittedAt) : null; |
| 1328 | const nativeItemRef = providerRef(part.id); |
| 1329 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 1330 | driver: OPENCODE_PROVIDER, |
| 1331 | nativeItemId: part.id, |
| 1332 | }); |
| 1333 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 1334 | driver: OPENCODE_PROVIDER, |
| 1335 | nativeItemId: part.id, |
| 1336 | }); |
| 1337 | const ordinal = itemOrdinal(turn, part.id); |
| 1338 | yield* emitProviderEvent({ |
| 1339 | type: "node.updated", |
| 1340 | driver: OPENCODE_PROVIDER, |
| 1341 | node: { |
| 1342 | id: nodeId, |
| 1343 | threadId: turn.threadId, |
| 1344 | runId: turn.runId, |
| 1345 | parentNodeId: turn.rootNodeId, |
| 1346 | rootNodeId: turn.rootNodeId, |
| 1347 | kind: part.type === "text" ? "assistant_message" : "reasoning", |
| 1348 | status: isCompleted ? "completed" : "running", |
| 1349 | countsForRun: false, |
| 1350 | providerThreadId: state.providerThread.id, |
| 1351 | providerTurnId: turn.providerTurnId, |
| 1352 | nativeItemRef, |
| 1353 | runtimeRequestId: null, |
| 1354 | checkpointScopeId: null, |
| 1355 | startedAt, |
| 1356 | completedAt, |
| 1357 | }, |
| 1358 | }); |
| 1359 | if (part.type === "text") { |
| 1360 | const messageId = idAllocator.derive.messageFromProviderItem({ |
| 1361 | driver: OPENCODE_PROVIDER, |
| 1362 | nativeItemId: part.id, |
| 1363 | }); |
| 1364 | const message: OrchestrationV2ConversationMessage = { |
| 1365 | createdBy: "agent", |
| 1366 | creationSource: "provider", |
| 1367 | id: messageId, |
| 1368 | threadId: turn.threadId, |
| 1369 | runId: turn.runId, |
| 1370 | nodeId, |
| 1371 | role: "assistant", |
| 1372 | text: part.text, |
| 1373 | attachments: [], |
| 1374 | streaming: !isCompleted, |
| 1375 | createdAt: startedAt, |
| 1376 | updatedAt: emittedAt, |
| 1377 | }; |
| 1378 | yield* emitProviderEvent({ |
| 1379 | type: "message.updated", |
| 1380 | driver: OPENCODE_PROVIDER, |
| 1381 | message, |
| 1382 | }); |
| 1383 | yield* emitProviderEvent({ |
| 1384 | type: "turn_item.updated", |
| 1385 | driver: OPENCODE_PROVIDER, |
| 1386 | turnItem: { |
| 1387 | id: turnItemId, |
| 1388 | threadId: turn.threadId, |
| 1389 | runId: turn.runId, |
| 1390 | nodeId, |
| 1391 | providerThreadId: state.providerThread.id, |
| 1392 | providerTurnId: turn.providerTurnId, |
| 1393 | nativeItemRef, |
| 1394 | parentItemId: null, |
| 1395 | ordinal, |
| 1396 | status: isCompleted ? "completed" : "running", |
| 1397 | title: null, |
| 1398 | startedAt, |
| 1399 | completedAt, |
| 1400 | updatedAt: emittedAt, |
| 1401 | type: "assistant_message", |
| 1402 | messageId, |
| 1403 | text: part.text, |
| 1404 | streaming: !isCompleted, |
| 1405 | }, |
| 1406 | }); |
| 1407 | return; |
| 1408 | } |
| 1409 | yield* emitProviderEvent({ |
| 1410 | type: "turn_item.updated", |
| 1411 | driver: OPENCODE_PROVIDER, |
| 1412 | turnItem: { |
| 1413 | id: turnItemId, |
| 1414 | threadId: turn.threadId, |
| 1415 | runId: turn.runId, |
| 1416 | nodeId, |
| 1417 | providerThreadId: state.providerThread.id, |
| 1418 | providerTurnId: turn.providerTurnId, |
| 1419 | nativeItemRef, |
| 1420 | parentItemId: null, |
| 1421 | ordinal, |
| 1422 | status: isCompleted ? "completed" : "running", |
| 1423 | title: null, |
| 1424 | startedAt, |
| 1425 | completedAt, |
| 1426 | updatedAt: emittedAt, |
| 1427 | type: "reasoning", |
| 1428 | text: part.text, |
| 1429 | streaming: !isCompleted, |
| 1430 | }, |
| 1431 | }); |
| 1432 | }); |
| 1433 | |
| 1434 | // A child turn's ordinal never exceeds its user message's position in the session, and that |
| 1435 | // position survives restarts, so it stays above every ordinal allocated before. |
| 1436 | const storedUserMessagePosition = Effect.fnUntraced(function* ( |
| 1437 | childSessionId: string, |
| 1438 | messageId: string, |
| 1439 | ) { |
| 1440 | const response = yield* sdkCall("session.messages", { sessionID: childSessionId }, () => |
| 1441 | client.session.messages({ sessionID: childSessionId }), |
| 1442 | ); |
| 1443 | const userMessageIds = unwrapData("session.messages", response).flatMap((entry) => |
| 1444 | entry.info.role === "user" ? [entry.info.id] : [], |
| 1445 | ); |
| 1446 | const index = userMessageIds.indexOf(messageId); |
| 1447 | return (index === -1 ? userMessageIds.length : index) + 1; |
| 1448 | }); |
| 1449 | |
| 1450 | const emitSubagent = Effect.fnUntraced(function* ( |
| 1451 | state: OpenCodeThreadState, |
| 1452 | turn: ActiveOpenCodeTurn, |
| 1453 | part: ToolPart, |
| 1454 | childOutcome?: TerminalTurnStatus, |
| 1455 | ) { |
| 1456 | const now = yield* DateTime.now; |
| 1457 | const nativeItemRef = providerRef(part.id); |
| 1458 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 1459 | driver: OPENCODE_PROVIDER, |
| 1460 | nativeItemId: part.id, |
| 1461 | }); |
| 1462 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 1463 | driver: OPENCODE_PROVIDER, |
| 1464 | nativeItemId: part.id, |
| 1465 | }); |
| 1466 | turn.usage.hasSubagents = true; |
| 1467 | const input = toolInput(part); |
| 1468 | const prompt = recordString(input, "prompt") ?? ""; |
| 1469 | const title = toolTitle(part) ?? recordString(input, "description") ?? null; |
| 1470 | let context = subagentsByNativeItemId.get(part.id); |
| 1471 | if (context === undefined) { |
| 1472 | context = { |
| 1473 | nativeItemId: part.id, |
| 1474 | nodeId, |
| 1475 | parentState: state, |
| 1476 | parentTurn: turn, |
| 1477 | prompt, |
| 1478 | title, |
| 1479 | startedAt: toolStartedAt(part, now), |
| 1480 | childSessionId: null, |
| 1481 | childThreadId: null, |
| 1482 | childProviderThreadId: null, |
| 1483 | model: null, |
| 1484 | result: null, |
| 1485 | launch: null, |
| 1486 | }; |
| 1487 | subagentsByNativeItemId.set(part.id, context); |
| 1488 | } |
| 1489 | context.model = toolModel(part) ?? context.model; |
| 1490 | const childSessionId = taskSessionId(part); |
| 1491 | if (childSessionId !== null && context.childSessionId === null) { |
| 1492 | context.childSessionId = childSessionId; |
| 1493 | context.childThreadId = idAllocator.derive.subagentThread({ |
| 1494 | driver: OPENCODE_PROVIDER, |
| 1495 | nativeThreadId: childSessionId, |
| 1496 | }); |
| 1497 | context.childProviderThreadId = idAllocator.derive.providerThread({ |
| 1498 | driver: OPENCODE_PROVIDER, |
| 1499 | nativeThreadId: childSessionId, |
| 1500 | }); |
| 1501 | subagentsByChildSessionId.set(childSessionId, context); |
| 1502 | relatedSessionOwners.set(childSessionId, state); |
| 1503 | const childModelSelection: ModelSelection = { |
| 1504 | instanceId: options.instanceId, |
| 1505 | model: context.model ?? turn.modelSelection.model, |
| 1506 | }; |
| 1507 | const childThread = makeSubagentChildThread({ |
| 1508 | parentThread: turn.appThread, |
| 1509 | childThreadId: context.childThreadId, |
| 1510 | parentNodeId: nodeId, |
| 1511 | activeProviderThreadId: context.childProviderThreadId, |
| 1512 | providerInstanceId: options.instanceId, |
| 1513 | modelSelection: childModelSelection, |
| 1514 | title: subagentThreadTitle({ |
| 1515 | parentTitle: turn.appThread.title, |
| 1516 | title, |
| 1517 | prompt, |
| 1518 | ordinal: itemOrdinal(turn, part.id), |
| 1519 | }), |
| 1520 | now, |
| 1521 | createdBy: "agent", |
| 1522 | creationSource: "provider", |
| 1523 | }); |
| 1524 | const childProviderThread: OrchestrationV2ProviderThread = { |
| 1525 | id: context.childProviderThreadId, |
| 1526 | driver: OPENCODE_PROVIDER, |
| 1527 | providerInstanceId: options.instanceId, |
| 1528 | providerSessionId: inputProviderSessionId, |
| 1529 | appThreadId: context.childThreadId, |
| 1530 | ownerNodeId: nodeId, |
| 1531 | nativeThreadRef: providerRef(childSessionId), |
| 1532 | nativeConversationHeadRef: null, |
| 1533 | status: "active", |
| 1534 | firstRunOrdinal: null, |
| 1535 | lastRunOrdinal: null, |
| 1536 | handoffIds: [], |
| 1537 | forkedFrom: null, |
| 1538 | createdAt: now, |
| 1539 | updatedAt: now, |
| 1540 | }; |
| 1541 | const childSessionResponse = yield* sdkCall( |
| 1542 | "session.get", |
| 1543 | { sessionID: childSessionId }, |
| 1544 | () => client.session.get({ sessionID: childSessionId }), |
| 1545 | ); |
| 1546 | const nativeChildSession = unwrapData("session.get", childSessionResponse); |
| 1547 | const childPermission = openCodeChildPermissionRules( |
| 1548 | turn.runtimePolicy, |
| 1549 | nativeChildSession.permission ?? [], |
| 1550 | ); |
| 1551 | yield* sdkCall( |
| 1552 | "session.update", |
| 1553 | { sessionID: childSessionId, permission: childPermission }, |
| 1554 | () => |
| 1555 | client.session.update({ |
| 1556 | sessionID: childSessionId, |
| 1557 | permission: childPermission, |
| 1558 | }), |
| 1559 | ); |
| 1560 | // A Task call with task_id resumes the child, whose earlier turns already hold ordinals. |
| 1561 | const knownChild = threads.get(childSessionId); |
| 1562 | const resumedChild = knownChild?.parentSubagent == null ? undefined : knownChild; |
| 1563 | const nextChildTurnOrdinal = |
| 1564 | resumedChild === undefined |
| 1565 | ? recordString(input, "task_id") === childSessionId |
| 1566 | ? null |
| 1567 | : 1 |
| 1568 | : resumedChild.nextChildTurnOrdinal; |
| 1569 | threads.set(childSessionId, { |
| 1570 | nativeSessionId: childSessionId, |
| 1571 | providerThread: childProviderThread, |
| 1572 | appThread: childThread, |
| 1573 | activeTurn: null, |
| 1574 | providerTurns: new Map(), |
| 1575 | runtimeRequests: new Map(), |
| 1576 | messageRoles: resumedChild?.messageRoles ?? new Map(), |
| 1577 | userMessageIds: resumedChild?.userMessageIds ?? [], |
| 1578 | parentSubagent: context, |
| 1579 | nextChildTurnOrdinal, |
| 1580 | nextAdmissionGeneration: 1, |
| 1581 | wake: null, |
| 1582 | lifecyclePermit: Semaphore.makeUnsafe(1), |
| 1583 | permission: childPermission, |
| 1584 | inheritedPermission: openCodePermissionRules(turn.runtimePolicy), |
| 1585 | }); |
| 1586 | yield* emitProviderEvent({ |
| 1587 | type: "app_thread.created", |
| 1588 | driver: OPENCODE_PROVIDER, |
| 1589 | appThread: childThread, |
| 1590 | }); |
| 1591 | yield* emitProviderEvent({ |
| 1592 | type: "provider_thread.updated", |
| 1593 | driver: OPENCODE_PROVIDER, |
| 1594 | providerThread: childProviderThread, |
| 1595 | }); |
| 1596 | } |
| 1597 | const output = toolOutput(part); |
| 1598 | if (part.state.status === "completed" && output !== undefined) context.result = output; |
| 1599 | const launchStatus = toolStatus(part); |
| 1600 | context.launch = |
| 1601 | childOutcome === undefined && |
| 1602 | launchStatus.item === "completed" && |
| 1603 | context.childSessionId !== null && |
| 1604 | (busySessionIds.has(context.childSessionId) || |
| 1605 | unstartedSessionIds.has(context.childSessionId)) |
| 1606 | ? part |
| 1607 | : null; |
| 1608 | const status = |
| 1609 | context.launch !== null |
| 1610 | ? ({ node: "running", item: "running" } as const) |
| 1611 | : childOutcome === undefined |
| 1612 | ? launchStatus |
| 1613 | : { node: childOutcome, item: childOutcome }; |
| 1614 | const completedAt = |
| 1615 | context.launch !== null |
| 1616 | ? null |
| 1617 | : childOutcome === undefined |
| 1618 | ? toolCompletedAt(part, now) |
| 1619 | : now; |
| 1620 | const subagentStatus: OrchestrationV2Subagent["status"] = status.item; |
| 1621 | const subagent: OrchestrationV2Subagent = { |
| 1622 | id: nodeId, |
| 1623 | threadId: turn.threadId, |
| 1624 | runId: turn.runId, |
| 1625 | parentNodeId: turn.rootNodeId, |
| 1626 | origin: "provider_native", |
| 1627 | createdBy: "agent", |
| 1628 | driver: OPENCODE_PROVIDER, |
| 1629 | providerInstanceId: options.instanceId, |
| 1630 | providerThreadId: context.childProviderThreadId, |
| 1631 | childThreadId: context.childThreadId, |
| 1632 | nativeTaskRef: nativeItemRef, |
| 1633 | prompt, |
| 1634 | title, |
| 1635 | model: context.model, |
| 1636 | status: subagentStatus, |
| 1637 | result: context.result, |
| 1638 | startedAt: context.startedAt, |
| 1639 | completedAt, |
| 1640 | updatedAt: now, |
| 1641 | }; |
| 1642 | yield* emitProviderEvent({ |
| 1643 | type: "node.updated", |
| 1644 | driver: OPENCODE_PROVIDER, |
| 1645 | node: { |
| 1646 | id: nodeId, |
| 1647 | threadId: turn.threadId, |
| 1648 | runId: turn.runId, |
| 1649 | parentNodeId: turn.rootNodeId, |
| 1650 | rootNodeId: turn.rootNodeId, |
| 1651 | kind: "subagent", |
| 1652 | status: status.node, |
| 1653 | countsForRun: false, |
| 1654 | providerThreadId: context.childProviderThreadId ?? state.providerThread.id, |
| 1655 | providerTurnId: turn.providerTurnId, |
| 1656 | nativeItemRef, |
| 1657 | runtimeRequestId: null, |
| 1658 | checkpointScopeId: null, |
| 1659 | startedAt: context.startedAt, |
| 1660 | completedAt, |
| 1661 | }, |
| 1662 | }); |
| 1663 | yield* emitProviderEvent({ |
| 1664 | type: "subagent.updated", |
| 1665 | driver: OPENCODE_PROVIDER, |
| 1666 | subagent, |
| 1667 | }); |
| 1668 | yield* emitProviderEvent({ |
| 1669 | type: "turn_item.updated", |
| 1670 | driver: OPENCODE_PROVIDER, |
| 1671 | turnItem: { |
| 1672 | id: turnItemId, |
| 1673 | threadId: turn.threadId, |
| 1674 | runId: turn.runId, |
| 1675 | nodeId, |
| 1676 | providerThreadId: state.providerThread.id, |
| 1677 | providerTurnId: turn.providerTurnId, |
| 1678 | nativeItemRef, |
| 1679 | parentItemId: null, |
| 1680 | ordinal: itemOrdinal(turn, part.id), |
| 1681 | status: status.item, |
| 1682 | title, |
| 1683 | startedAt: context.startedAt, |
| 1684 | completedAt, |
| 1685 | updatedAt: now, |
| 1686 | type: "subagent", |
| 1687 | subagentId: nodeId, |
| 1688 | origin: "provider_native", |
| 1689 | driver: OPENCODE_PROVIDER, |
| 1690 | providerInstanceId: options.instanceId, |
| 1691 | childThreadId: context.childThreadId, |
| 1692 | prompt, |
| 1693 | result: context.result, |
| 1694 | }, |
| 1695 | }); |
| 1696 | }); |
| 1697 | |
| 1698 | const settleLaunchedSubagents = Effect.fnUntraced(function* ( |
| 1699 | childSessionId: string, |
| 1700 | outcome?: TerminalTurnStatus, |
| 1701 | ) { |
| 1702 | const lastTurn = Array.from(threads.get(childSessionId)?.providerTurns.values() ?? []).at( |
| 1703 | -1, |
| 1704 | )?.status; |
| 1705 | const errorOutcome = sessionErrorOutcomes.get(childSessionId); |
| 1706 | sessionErrorOutcomes.delete(childSessionId); |
| 1707 | const childOutcome = |
| 1708 | outcome ?? |
| 1709 | errorOutcome ?? |
| 1710 | (lastTurn === "interrupted" || lastTurn === "failed" || lastTurn === "cancelled" |
| 1711 | ? lastTurn |
| 1712 | : "completed"); |
| 1713 | for (const context of subagentsByNativeItemId.values()) { |
| 1714 | if (context.childSessionId === childSessionId && context.launch !== null) { |
| 1715 | yield* emitSubagent( |
| 1716 | context.parentState, |
| 1717 | context.parentTurn, |
| 1718 | context.launch, |
| 1719 | childOutcome, |
| 1720 | ); |
| 1721 | } |
| 1722 | } |
| 1723 | }); |
| 1724 | |
| 1725 | // No idle event settles a launched child that Stop aborts before it reports busy. |
| 1726 | const interruptLaunchedSubagents = Effect.fnUntraced(function* (rootSessionId: string) { |
| 1727 | for (const context of subagentsByNativeItemId.values()) { |
| 1728 | let owner = context.parentState; |
| 1729 | while (owner.parentSubagent !== null) owner = owner.parentSubagent.parentState; |
| 1730 | if (owner.nativeSessionId === rootSessionId && context.launch !== null) { |
| 1731 | yield* emitSubagent( |
| 1732 | context.parentState, |
| 1733 | context.parentTurn, |
| 1734 | context.launch, |
| 1735 | "interrupted", |
| 1736 | ); |
| 1737 | } |
| 1738 | } |
| 1739 | }); |
| 1740 | |
| 1741 | const emitToolPart = Effect.fnUntraced(function* ( |
| 1742 | state: OpenCodeThreadState, |
| 1743 | turn: ActiveOpenCodeTurn, |
| 1744 | part: ToolPart, |
| 1745 | ) { |
| 1746 | const normalizedTool = part.tool.toLowerCase(); |
| 1747 | if (normalizedTool === "task") { |
| 1748 | yield* emitSubagent(state, turn, part); |
| 1749 | return; |
| 1750 | } |
| 1751 | if (normalizedTool === "question") return; |
| 1752 | const now = yield* DateTime.now; |
| 1753 | const status = toolStatus(part); |
| 1754 | const startedAt = toolStartedAt(part, now); |
| 1755 | const completedAt = toolCompletedAt(part, now); |
| 1756 | const nativeItemRef = providerRef(part.id); |
| 1757 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 1758 | driver: OPENCODE_PROVIDER, |
| 1759 | nativeItemId: part.id, |
| 1760 | }); |
| 1761 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 1762 | driver: OPENCODE_PROVIDER, |
| 1763 | nativeItemId: part.id, |
| 1764 | }); |
| 1765 | const base = { |
| 1766 | id: turnItemId, |
| 1767 | threadId: turn.threadId, |
| 1768 | runId: turn.runId, |
| 1769 | nodeId, |
| 1770 | providerThreadId: state.providerThread.id, |
| 1771 | providerTurnId: turn.providerTurnId, |
| 1772 | nativeItemRef, |
| 1773 | parentItemId: null, |
| 1774 | ordinal: itemOrdinal(turn, part.id), |
| 1775 | status: status.item, |
| 1776 | title: toolTitle(part), |
| 1777 | startedAt, |
| 1778 | completedAt, |
| 1779 | updatedAt: now, |
| 1780 | } satisfies Pick< |
| 1781 | OrchestrationV2TurnItem, |
| 1782 | | "id" |
| 1783 | | "threadId" |
| 1784 | | "runId" |
| 1785 | | "nodeId" |
| 1786 | | "providerThreadId" |
| 1787 | | "providerTurnId" |
| 1788 | | "nativeItemRef" |
| 1789 | | "parentItemId" |
| 1790 | | "ordinal" |
| 1791 | | "status" |
| 1792 | | "title" |
| 1793 | | "startedAt" |
| 1794 | | "completedAt" |
| 1795 | | "updatedAt" |
| 1796 | >; |
| 1797 | const input = toolInput(part); |
| 1798 | const output = toolOutput(part); |
| 1799 | const isNativeTool = part.tool === "code_search" || part.tool === "apply_patch"; |
| 1800 | if (!isNativeTool && part.tool.includes("_") && turn.mcpServerNames === undefined) { |
| 1801 | const serverNames = yield* OpenCodeRuntime.runOpenCodeSdk("mcp.status", (signal) => |
| 1802 | client.mcp.status(undefined, { signal, throwOnError: true }), |
| 1803 | ).pipe( |
| 1804 | Effect.timeout("1 second"), |
| 1805 | Effect.map((response) => Object.keys(response.data ?? {})), |
| 1806 | Effect.catch(() => Effect.void), |
| 1807 | ); |
| 1808 | if (serverNames !== undefined) turn.mcpServerNames = serverNames; |
| 1809 | } |
| 1810 | const matchingServers = turn.mcpServerNames?.filter( |
| 1811 | (name) => |
| 1812 | !isNativeTool && part.tool.startsWith(`${name.replace(/[^a-zA-Z0-9_-]/g, "_")}_`), |
| 1813 | ); |
| 1814 | const serverName = matchingServers?.length === 1 ? matchingServers[0] : undefined; |
| 1815 | const presentation = |
| 1816 | serverName === undefined |
| 1817 | ? {} |
| 1818 | : mcpToolPresentation({ |
| 1819 | serverName, |
| 1820 | toolName: part.tool.slice(serverName.replace(/[^a-zA-Z0-9_-]/g, "_").length + 1), |
| 1821 | title: toolTitle(part) === part.tool ? undefined : toolTitle(part), |
| 1822 | }); |
| 1823 | const files = |
| 1824 | part.state.status === "completed" |
| 1825 | ? part.state.attachments?.map((file) => ({ uri: file.url, mime: file.mime })) |
| 1826 | : undefined; |
| 1827 | const turnItem: OrchestrationV2TurnItem = matchingServers?.length |
| 1828 | ? { |
| 1829 | ...base, |
| 1830 | type: "dynamic_tool", |
| 1831 | ...presentation, |
| 1832 | toolName: part.tool, |
| 1833 | input, |
| 1834 | ...(output === undefined && !files?.length |
| 1835 | ? {} |
| 1836 | : { output: openCodeToolOutput(output, files) }), |
| 1837 | } |
| 1838 | : openCodeToolTurnItem(base, { |
| 1839 | name: part.tool, |
| 1840 | input, |
| 1841 | output, |
| 1842 | files, |
| 1843 | completedMetadata: |
| 1844 | part.state.status === "completed" ? part.state.metadata : undefined, |
| 1845 | }); |
| 1846 | yield* emitProviderEvent({ |
| 1847 | type: "node.updated", |
| 1848 | driver: OPENCODE_PROVIDER, |
| 1849 | node: { |
| 1850 | id: nodeId, |
| 1851 | threadId: turn.threadId, |
| 1852 | runId: turn.runId, |
| 1853 | parentNodeId: turn.rootNodeId, |
| 1854 | rootNodeId: turn.rootNodeId, |
| 1855 | kind: "tool_call", |
| 1856 | status: status.node, |
| 1857 | countsForRun: false, |
| 1858 | providerThreadId: state.providerThread.id, |
| 1859 | providerTurnId: turn.providerTurnId, |
| 1860 | nativeItemRef, |
| 1861 | runtimeRequestId: null, |
| 1862 | checkpointScopeId: null, |
| 1863 | startedAt, |
| 1864 | completedAt, |
| 1865 | }, |
| 1866 | }); |
| 1867 | yield* emitProviderEvent({ |
| 1868 | type: "turn_item.updated", |
| 1869 | driver: OPENCODE_PROVIDER, |
| 1870 | turnItem, |
| 1871 | }); |
| 1872 | }); |
| 1873 | |
| 1874 | const emitTodo = Effect.fnUntraced(function* ( |
| 1875 | state: OpenCodeThreadState, |
| 1876 | turn: ActiveOpenCodeTurn, |
| 1877 | todos: ReadonlyArray<OpenCodeTodo>, |
| 1878 | ) { |
| 1879 | const now = yield* DateTime.now; |
| 1880 | if (turn.planId === null) { |
| 1881 | turn.planId = yield* idAllocator.allocate.plan({ |
| 1882 | threadId: turn.threadId, |
| 1883 | ...(turn.runId === null ? {} : { runId: turn.runId }), |
| 1884 | driver: OPENCODE_PROVIDER, |
| 1885 | }); |
| 1886 | } |
| 1887 | const planId = turn.planId; |
| 1888 | const nativeItemId = `${state.nativeSessionId}:todo:${turn.providerTurnId}`; |
| 1889 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 1890 | driver: OPENCODE_PROVIDER, |
| 1891 | nativeItemId, |
| 1892 | }); |
| 1893 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 1894 | driver: OPENCODE_PROVIDER, |
| 1895 | nativeItemId, |
| 1896 | }); |
| 1897 | // A cancelled todo is not outstanding work, and plan steps have no |
| 1898 | // cancelled status, so drop it rather than show it as pending. |
| 1899 | const steps: Array<OrchestrationV2PlanStep> = todos.flatMap((todo, index) => |
| 1900 | todo.status === "cancelled" |
| 1901 | ? [] |
| 1902 | : [ |
| 1903 | { |
| 1904 | id: `${nativeItemId}:${index + 1}`, |
| 1905 | text: todo.content.trim() || `Todo ${index + 1}`, |
| 1906 | status: |
| 1907 | todo.status === "completed" |
| 1908 | ? "completed" |
| 1909 | : todo.status === "in_progress" |
| 1910 | ? "running" |
| 1911 | : "pending", |
| 1912 | }, |
| 1913 | ], |
| 1914 | ); |
| 1915 | const completed = todos.length > 0 && steps.every((step) => step.status === "completed"); |
| 1916 | yield* emitProviderEvent({ |
| 1917 | type: "node.updated", |
| 1918 | driver: OPENCODE_PROVIDER, |
| 1919 | node: { |
| 1920 | id: nodeId, |
| 1921 | threadId: turn.threadId, |
| 1922 | runId: turn.runId, |
| 1923 | parentNodeId: turn.rootNodeId, |
| 1924 | rootNodeId: turn.rootNodeId, |
| 1925 | kind: "todo_list", |
| 1926 | status: completed ? "completed" : "running", |
| 1927 | countsForRun: false, |
| 1928 | providerThreadId: state.providerThread.id, |
| 1929 | providerTurnId: turn.providerTurnId, |
| 1930 | nativeItemRef: providerRef(nativeItemId, "weak"), |
| 1931 | runtimeRequestId: null, |
| 1932 | checkpointScopeId: null, |
| 1933 | startedAt: turn.startedAt, |
| 1934 | completedAt: completed ? now : null, |
| 1935 | }, |
| 1936 | }); |
| 1937 | yield* emitProviderEvent({ |
| 1938 | type: "plan.updated", |
| 1939 | driver: OPENCODE_PROVIDER, |
| 1940 | plan: { |
| 1941 | id: planId, |
| 1942 | threadId: turn.threadId, |
| 1943 | runId: turn.runId, |
| 1944 | nodeId, |
| 1945 | status: completed ? "completed" : "active", |
| 1946 | kind: "todo_list", |
| 1947 | steps, |
| 1948 | }, |
| 1949 | }); |
| 1950 | yield* emitProviderEvent({ |
| 1951 | type: "turn_item.updated", |
| 1952 | driver: OPENCODE_PROVIDER, |
| 1953 | turnItem: { |
| 1954 | id: turnItemId, |
| 1955 | threadId: turn.threadId, |
| 1956 | runId: turn.runId, |
| 1957 | nodeId, |
| 1958 | providerThreadId: state.providerThread.id, |
| 1959 | providerTurnId: turn.providerTurnId, |
| 1960 | nativeItemRef: providerRef(nativeItemId, "weak"), |
| 1961 | parentItemId: null, |
| 1962 | ordinal: itemOrdinal(turn, nativeItemId), |
| 1963 | status: completed ? "completed" : "running", |
| 1964 | title: "Todo list", |
| 1965 | startedAt: turn.startedAt, |
| 1966 | completedAt: completed ? now : null, |
| 1967 | updatedAt: now, |
| 1968 | type: "todo_list", |
| 1969 | planId, |
| 1970 | steps, |
| 1971 | }, |
| 1972 | }); |
| 1973 | }); |
| 1974 | |
| 1975 | const requestQuestions = (request: QuestionRequest) => |
| 1976 | request.questions.map((question, index) => ({ |
| 1977 | id: OpenCodeRuntime.openCodeQuestionId(index, question), |
| 1978 | header: question.header.trim() || `Question ${index + 1}`, |
| 1979 | question: question.question.trim() || question.header.trim() || `Question ${index + 1}`, |
| 1980 | ...(question.multiple === undefined ? {} : { multiSelect: question.multiple }), |
| 1981 | ...(question.custom === undefined ? {} : { allowCustomAnswer: question.custom }), |
| 1982 | options: question.options.map((option) => ({ |
| 1983 | label: option.label.trim() || "Option", |
| 1984 | description: option.description.trim() || option.label.trim() || "Option", |
| 1985 | })), |
| 1986 | })); |
| 1987 | |
| 1988 | const runtimeRequestTurnItem = ( |
| 1989 | pending: PendingOpenCodeRequest, |
| 1990 | status: OrchestrationV2TurnItem["status"], |
| 1991 | completedAt: DateTime.Utc | null, |
| 1992 | updatedAt: DateTime.Utc, |
| 1993 | ): OrchestrationV2TurnItem => { |
| 1994 | const base = { |
| 1995 | id: pending.turnItemId, |
| 1996 | threadId: pending.turn.threadId, |
| 1997 | runId: pending.turn.runId, |
| 1998 | nodeId: pending.nodeId, |
| 1999 | providerThreadId: pending.state.providerThread.id, |
| 2000 | providerTurnId: pending.turn.providerTurnId, |
| 2001 | nativeItemRef: providerRef(pending.nativeRequestId), |
| 2002 | parentItemId: null, |
| 2003 | ordinal: itemOrdinal(pending.turn, pending.nativeRequestId), |
| 2004 | status, |
| 2005 | startedAt: pending.createdAt, |
| 2006 | completedAt, |
| 2007 | updatedAt, |
| 2008 | }; |
| 2009 | if (pending.question !== undefined) { |
| 2010 | return { |
| 2011 | ...base, |
| 2012 | title: "User input", |
| 2013 | type: "user_input_request", |
| 2014 | requestId: pending.requestId, |
| 2015 | questions: requestQuestions(pending.question), |
| 2016 | }; |
| 2017 | } |
| 2018 | const permission = pending.permission; |
| 2019 | if (permission === undefined) { |
| 2020 | throw protocolError(`OpenCode request ${pending.requestId} has no native payload`); |
| 2021 | } |
| 2022 | return { |
| 2023 | ...base, |
| 2024 | title: permission.permission, |
| 2025 | type: "approval_request", |
| 2026 | requestId: pending.requestId, |
| 2027 | requestKind: pending.requestKind === "user_input" ? "command" : pending.requestKind, |
| 2028 | prompt: |
| 2029 | permission.patterns.length === 0 |
| 2030 | ? permission.permission |
| 2031 | : permission.patterns.join("\n"), |
| 2032 | }; |
| 2033 | }; |
| 2034 | |
| 2035 | const emitRuntimeRequest = Effect.fnUntraced(function* ( |
| 2036 | owner: OpenCodeRequestOwner, |
| 2037 | nativeRequestId: string, |
| 2038 | request: |
| 2039 | | { readonly type: "permission"; readonly value: PermissionRequest } |
| 2040 | | { readonly type: "question"; readonly value: QuestionRequest }, |
| 2041 | ) { |
| 2042 | if (pendingRequestsByNativeId.has(nativeRequestId)) return; |
| 2043 | const { state, turn, subagent } = owner; |
| 2044 | const now = yield* DateTime.now; |
| 2045 | const requestId = yield* idAllocator.allocate.runtimeRequest({ |
| 2046 | driver: OPENCODE_PROVIDER, |
| 2047 | providerTurnId: turn.providerTurnId, |
| 2048 | nativeRequestId, |
| 2049 | }); |
| 2050 | const nodeId = idAllocator.derive.approvalNode({ requestId }); |
| 2051 | const turnItemId = idAllocator.derive.approvalTurnItem({ requestId }); |
| 2052 | const permissionToolName = |
| 2053 | request.type === "permission" && request.value.tool !== undefined |
| 2054 | ? threads |
| 2055 | .get(request.value.sessionID) |
| 2056 | ?.activeTurn?.toolNamesByCallId.get(request.value.tool.callID) |
| 2057 | : undefined; |
| 2058 | const permissionRequestKind = |
| 2059 | request.type === "permission" |
| 2060 | ? openCodePermissionRequestKind(request.value.permission, permissionToolName) |
| 2061 | : undefined; |
| 2062 | const requestKind: OrchestrationV2RuntimeRequest["kind"] = |
| 2063 | permissionRequestKind ?? "user_input"; |
| 2064 | const pending: PendingOpenCodeRequest = { |
| 2065 | requestId, |
| 2066 | nativeRequestId, |
| 2067 | nativeSessionId: request.value.sessionID, |
| 2068 | turn, |
| 2069 | state, |
| 2070 | nodeId, |
| 2071 | parentNodeId: subagent?.nodeId ?? turn.rootNodeId, |
| 2072 | turnItemId, |
| 2073 | requestKind, |
| 2074 | createdAt: now, |
| 2075 | ...(request.type === "permission" |
| 2076 | ? { permission: request.value } |
| 2077 | : { question: request.value }), |
| 2078 | }; |
| 2079 | pendingRequests.set(String(requestId), pending); |
| 2080 | pendingRequestsByNativeId.set(nativeRequestId, pending); |
| 2081 | const runtimeRequest: OrchestrationV2RuntimeRequest = { |
| 2082 | id: requestId, |
| 2083 | nodeId, |
| 2084 | providerTurnId: turn.providerTurnId, |
| 2085 | nativeRequestRef: providerRef(nativeRequestId), |
| 2086 | kind: requestKind, |
| 2087 | status: "pending", |
| 2088 | responseCapability: { |
| 2089 | type: "live", |
| 2090 | providerSessionId: inputProviderSessionId, |
| 2091 | }, |
| 2092 | createdAt: now, |
| 2093 | resolvedAt: null, |
| 2094 | }; |
| 2095 | state.runtimeRequests.set(String(requestId), runtimeRequest); |
| 2096 | yield* emitProviderEvent({ |
| 2097 | type: "node.updated", |
| 2098 | driver: OPENCODE_PROVIDER, |
| 2099 | node: { |
| 2100 | id: nodeId, |
| 2101 | threadId: turn.threadId, |
| 2102 | runId: turn.runId, |
| 2103 | parentNodeId: pending.parentNodeId, |
| 2104 | rootNodeId: turn.rootNodeId, |
| 2105 | kind: request.type === "question" ? "user_input_request" : "approval_request", |
| 2106 | status: "waiting", |
| 2107 | countsForRun: false, |
| 2108 | providerThreadId: state.providerThread.id, |
| 2109 | providerTurnId: turn.providerTurnId, |
| 2110 | nativeItemRef: providerRef(nativeRequestId), |
| 2111 | runtimeRequestId: requestId, |
| 2112 | checkpointScopeId: null, |
| 2113 | startedAt: now, |
| 2114 | completedAt: null, |
| 2115 | }, |
| 2116 | }); |
| 2117 | yield* emitProviderEvent({ |
| 2118 | type: "turn_item.updated", |
| 2119 | driver: OPENCODE_PROVIDER, |
| 2120 | turnItem: runtimeRequestTurnItem(pending, "waiting", null, now), |
| 2121 | }); |
| 2122 | // A response can commit as soon as the actionable request is published. |
| 2123 | yield* emitProviderEvent({ |
| 2124 | type: "runtime_request.updated", |
| 2125 | driver: OPENCODE_PROVIDER, |
| 2126 | threadId: turn.threadId, |
| 2127 | runtimeRequest, |
| 2128 | }); |
| 2129 | yield* updateProviderSession("waiting", null); |
| 2130 | }); |
| 2131 | |
| 2132 | const resolveRuntimeRequest = Effect.fnUntraced(function* ( |
| 2133 | nativeRequestId: string, |
| 2134 | status: "resolved" | "cancelled", |
| 2135 | ) { |
| 2136 | const pending = pendingRequestsByNativeId.get(nativeRequestId); |
| 2137 | if (pending === undefined) return; |
| 2138 | const now = yield* DateTime.now; |
| 2139 | const current = pending.state.runtimeRequests.get(String(pending.requestId)); |
| 2140 | if (current !== undefined) { |
| 2141 | const resolved: OrchestrationV2RuntimeRequest = { |
| 2142 | ...current, |
| 2143 | status, |
| 2144 | resolvedAt: now, |
| 2145 | }; |
| 2146 | pending.state.runtimeRequests.set(String(pending.requestId), resolved); |
| 2147 | yield* emitProviderEvent({ |
| 2148 | type: "runtime_request.updated", |
| 2149 | driver: OPENCODE_PROVIDER, |
| 2150 | threadId: pending.turn.threadId, |
| 2151 | runtimeRequest: resolved, |
| 2152 | }); |
| 2153 | } |
| 2154 | yield* emitProviderEvent({ |
| 2155 | type: "node.updated", |
| 2156 | driver: OPENCODE_PROVIDER, |
| 2157 | node: { |
| 2158 | id: pending.nodeId, |
| 2159 | threadId: pending.turn.threadId, |
| 2160 | runId: pending.turn.runId, |
| 2161 | parentNodeId: pending.parentNodeId, |
| 2162 | rootNodeId: pending.turn.rootNodeId, |
| 2163 | kind: pending.question === undefined ? "approval_request" : "user_input_request", |
| 2164 | status: status === "resolved" ? "completed" : "cancelled", |
| 2165 | countsForRun: false, |
| 2166 | providerThreadId: pending.state.providerThread.id, |
| 2167 | providerTurnId: pending.turn.providerTurnId, |
| 2168 | nativeItemRef: providerRef(nativeRequestId), |
| 2169 | runtimeRequestId: pending.requestId, |
| 2170 | checkpointScopeId: null, |
| 2171 | startedAt: pending.createdAt, |
| 2172 | completedAt: now, |
| 2173 | }, |
| 2174 | }); |
| 2175 | yield* emitProviderEvent({ |
| 2176 | type: "turn_item.updated", |
| 2177 | driver: OPENCODE_PROVIDER, |
| 2178 | turnItem: runtimeRequestTurnItem( |
| 2179 | pending, |
| 2180 | status === "resolved" ? "completed" : "cancelled", |
| 2181 | now, |
| 2182 | now, |
| 2183 | ), |
| 2184 | }); |
| 2185 | pendingRequests.delete(String(pending.requestId)); |
| 2186 | pendingRequestsByNativeId.delete(nativeRequestId); |
| 2187 | const hasOtherPending = Array.from(pendingRequests.values()).some( |
| 2188 | (candidate) => candidate.turn.isRoot, |
| 2189 | ); |
| 2190 | if (!hasOtherPending) yield* updateProviderSession("running", null); |
| 2191 | }); |
| 2192 | |
| 2193 | const resolveSessionOwner = Effect.fnUntraced(function* (sessionId: string) { |
| 2194 | const known = threads.get(sessionId) ?? relatedSessionOwners.get(sessionId); |
| 2195 | if (known !== undefined) return known; |
| 2196 | let cursor = sessionId; |
| 2197 | const hops: string[] = []; |
| 2198 | for (let depth = 0; depth < 5; depth += 1) { |
| 2199 | const response = yield* sdkCall("session.get", { sessionID: cursor }, () => |
| 2200 | client.session.get({ sessionID: cursor }), |
| 2201 | ).pipe(Effect.option); |
| 2202 | const info = Option.getOrUndefined(response)?.data; |
| 2203 | const parentId = info?.parentID; |
| 2204 | if (parentId === undefined) return undefined; |
| 2205 | hops.push(cursor); |
| 2206 | const owner = threads.get(parentId) ?? relatedSessionOwners.get(parentId); |
| 2207 | if (owner !== undefined) { |
| 2208 | for (const hop of hops) relatedSessionOwners.set(hop, owner); |
| 2209 | return owner; |
| 2210 | } |
| 2211 | cursor = parentId; |
| 2212 | } |
| 2213 | return undefined; |
| 2214 | }); |
| 2215 | |
| 2216 | const routeRuntimeRequest = Effect.fnUntraced(function* ( |
| 2217 | nativeRequestId: string, |
| 2218 | sessionId: string, |
| 2219 | request: |
| 2220 | | { readonly type: "permission"; readonly value: PermissionRequest } |
| 2221 | | { readonly type: "question"; readonly value: QuestionRequest }, |
| 2222 | ) { |
| 2223 | if (pendingChildRequestRoutes.has(nativeRequestId)) return; |
| 2224 | const attempt = Effect.gen(function* () { |
| 2225 | if ( |
| 2226 | settledNativeRequestIds.has(nativeRequestId) || |
| 2227 | pendingRequestsByNativeId.has(nativeRequestId) |
| 2228 | ) { |
| 2229 | return true; |
| 2230 | } |
| 2231 | const state = yield* resolveSessionOwner(sessionId); |
| 2232 | const owner = state === undefined ? undefined : topLevelRequestOwner(state); |
| 2233 | if (owner === undefined) return false; |
| 2234 | yield* emitRuntimeRequest(owner, nativeRequestId, request); |
| 2235 | return true; |
| 2236 | }); |
| 2237 | if (yield* attempt) return; |
| 2238 | pendingChildRequestRoutes.add(nativeRequestId); |
| 2239 | yield* Effect.gen(function* () { |
| 2240 | for (let retry = 0; retry < 5; retry += 1) { |
| 2241 | yield* Effect.sleep(Duration.millis(Math.min(200 * 2 ** retry, 2_000))); |
| 2242 | if (yield* attempt) return; |
| 2243 | } |
| 2244 | }).pipe( |
| 2245 | Effect.ensuring(Effect.sync(() => pendingChildRequestRoutes.delete(nativeRequestId))), |
| 2246 | Effect.forkIn(scope), |
| 2247 | ); |
| 2248 | }); |
| 2249 | |
| 2250 | const finalizeTurn = Effect.fnUntraced(function* ( |
| 2251 | state: OpenCodeThreadState, |
| 2252 | turn: ActiveOpenCodeTurn, |
| 2253 | status: TerminalTurnStatus, |
| 2254 | terminal?: { |
| 2255 | readonly failure?: OrchestrationV2ProviderFailure; |
| 2256 | readonly threadDisposition?: "reusable" | "broken"; |
| 2257 | }, |
| 2258 | ) { |
| 2259 | // Once claimed, terminal publication must finish even if the routing budget expires. |
| 2260 | return yield* Effect.uninterruptibleMask((restore) => |
| 2261 | Effect.gen(function* () { |
| 2262 | if (turn.finalized) return; |
| 2263 | if (nativeStreamFailure !== null) { |
| 2264 | status = "failed"; |
| 2265 | terminal = { failure: nativeStreamFailure, threadDisposition: "broken" }; |
| 2266 | } |
| 2267 | let lastError = sessionEntity.lastError; |
| 2268 | if (status === "completed" && turn.contextOverflow !== null) { |
| 2269 | status = "failed"; |
| 2270 | terminal = { failure: turn.contextOverflow }; |
| 2271 | lastError = turn.contextOverflow.message; |
| 2272 | } |
| 2273 | turn.finalized = true; |
| 2274 | if (turn.priorWakeSettled !== null) |
| 2275 | yield* Deferred.succeed(turn.priorWakeSettled, undefined); |
| 2276 | const completedAt = yield* DateTime.now; |
| 2277 | for (const part of turn.parts.values()) { |
| 2278 | if (part.type === "text" || part.type === "reasoning") { |
| 2279 | yield* emitTextPart(state, turn, part, true); |
| 2280 | } |
| 2281 | } |
| 2282 | for (const pending of Array.from(pendingRequests.values())) { |
| 2283 | if ( |
| 2284 | pending.turn.providerTurnId === turn.providerTurnId || |
| 2285 | pending.nativeSessionId === state.nativeSessionId |
| 2286 | ) { |
| 2287 | yield* resolveRuntimeRequest(pending.nativeRequestId, "cancelled"); |
| 2288 | } |
| 2289 | } |
| 2290 | // Prompts read the catalog only for variants; a completed turn needs its context window. |
| 2291 | const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model); |
| 2292 | if (status === "completed" && turn.usage.lastStep !== null && parsedModel !== null) { |
| 2293 | yield* restore( |
| 2294 | OpenCodeRuntime.readOpenCodeCatalogModel( |
| 2295 | client, |
| 2296 | parsedModel, |
| 2297 | undefined, |
| 2298 | variantCache, |
| 2299 | ), |
| 2300 | ).pipe(Effect.exit); |
| 2301 | } |
| 2302 | yield* emitProviderTurn(state, turn, status, completedAt); |
| 2303 | const threadDisposition = terminal?.threadDisposition ?? "reusable"; |
| 2304 | yield* updateProviderThread(state, { |
| 2305 | status: turn.isRoot ? "active" : threadDisposition === "broken" ? "error" : "idle", |
| 2306 | nativeConversationHeadRef: |
| 2307 | turn.nativeUserMessageId === null |
| 2308 | ? state.providerThread.nativeConversationHeadRef |
| 2309 | : providerRef(turn.nativeUserMessageId, "weak"), |
| 2310 | }); |
| 2311 | state.activeTurn = null; |
| 2312 | if (!turn.isRoot) { |
| 2313 | yield* emitProviderEvent({ |
| 2314 | type: "node.updated", |
| 2315 | driver: OPENCODE_PROVIDER, |
| 2316 | node: { |
| 2317 | id: turn.rootNodeId, |
| 2318 | threadId: turn.threadId, |
| 2319 | runId: null, |
| 2320 | parentNodeId: null, |
| 2321 | rootNodeId: turn.rootNodeId, |
| 2322 | kind: "root_turn", |
| 2323 | status, |
| 2324 | countsForRun: false, |
| 2325 | providerThreadId: state.providerThread.id, |
| 2326 | providerTurnId: turn.providerTurnId, |
| 2327 | nativeItemRef: providerRef(state.nativeSessionId), |
| 2328 | runtimeRequestId: null, |
| 2329 | checkpointScopeId: null, |
| 2330 | startedAt: turn.startedAt, |
| 2331 | completedAt, |
| 2332 | }, |
| 2333 | }); |
| 2334 | return; |
| 2335 | } |
| 2336 | const anotherTurnIsActive = Array.from(threads.values()).some( |
| 2337 | (candidate) => candidate.activeTurn?.isRoot === true, |
| 2338 | ); |
| 2339 | yield* updateProviderSession( |
| 2340 | anotherTurnIsActive ? "running" : status === "failed" ? "error" : "ready", |
| 2341 | status === "failed" ? lastError : null, |
| 2342 | ); |
| 2343 | yield* emitProviderEvent( |
| 2344 | status === "failed" |
| 2345 | ? { |
| 2346 | type: "turn.terminal", |
| 2347 | driver: OPENCODE_PROVIDER, |
| 2348 | providerThreadId: turn.providerThreadId, |
| 2349 | providerTurnId: turn.providerTurnId, |
| 2350 | runOrdinal: turn.runOrdinal, |
| 2351 | failureItemOrdinal: itemOrdinal( |
| 2352 | turn, |
| 2353 | `terminal-failure:${turn.providerTurnId}`, |
| 2354 | ), |
| 2355 | status, |
| 2356 | failure: |
| 2357 | terminal?.failure ?? |
| 2358 | makeProviderFailure({ |
| 2359 | message: sessionEntity.lastError ?? undefined, |
| 2360 | class: "provider_error", |
| 2361 | }), |
| 2362 | threadDisposition, |
| 2363 | } |
| 2364 | : { |
| 2365 | type: "turn.terminal", |
| 2366 | driver: OPENCODE_PROVIDER, |
| 2367 | providerThreadId: turn.providerThreadId, |
| 2368 | providerTurnId: turn.providerTurnId, |
| 2369 | runOrdinal: turn.runOrdinal, |
| 2370 | status, |
| 2371 | failure: null, |
| 2372 | threadDisposition, |
| 2373 | }, |
| 2374 | ); |
| 2375 | }), |
| 2376 | ); |
| 2377 | }); |
| 2378 | |
| 2379 | // A call, not inline checks: TS keeps earlier narrowing of these mutable fields across yields. |
| 2380 | const turnIsLive = (state: OpenCodeThreadState, turn: ActiveOpenCodeTurn) => |
| 2381 | state.activeTurn === turn && !turn.finalized && !turn.interrupted; |
| 2382 | |
| 2383 | const promptAdmissionIsCurrent = ( |
| 2384 | state: OpenCodeThreadState, |
| 2385 | turn: ActiveOpenCodeTurn, |
| 2386 | generation: number, |
| 2387 | ) => |
| 2388 | state.activeTurn === turn && |
| 2389 | !turn.finalized && |
| 2390 | !turn.interrupted && |
| 2391 | turn.admissionPending && |
| 2392 | turn.admissionGeneration === generation; |
| 2393 | |
| 2394 | const runPromptAdmissionReconciliation = Effect.fnUntraced(function* ( |
| 2395 | state: OpenCodeThreadState, |
| 2396 | turn: ActiveOpenCodeTurn, |
| 2397 | generation: number, |
| 2398 | ) { |
| 2399 | while (promptAdmissionIsCurrent(state, turn, generation)) { |
| 2400 | const statusSequence = turn.admissionStatusSequence; |
| 2401 | const status = yield* reconcileOpenCodePromptAdmissionStatus( |
| 2402 | turn, |
| 2403 | generation, |
| 2404 | sdkCall( |
| 2405 | "session.status", |
| 2406 | { sessionID: state.nativeSessionId, generation }, |
| 2407 | (signal) => client.session.status(undefined, { signal }), |
| 2408 | ).pipe( |
| 2409 | Effect.match({ |
| 2410 | onFailure: () => "unknown" as const, |
| 2411 | onSuccess: (response) => { |
| 2412 | const statuses = unwrapData("session.status", response); |
| 2413 | const sessionStatus = statuses[state.nativeSessionId]; |
| 2414 | return sessionStatus === undefined || sessionStatus.type === "idle" |
| 2415 | ? ("idle" as const) |
| 2416 | : ("busy" as const); |
| 2417 | }, |
| 2418 | }), |
| 2419 | ), |
| 2420 | ); |
| 2421 | if ( |
| 2422 | state.activeTurn !== turn || |
| 2423 | status === "stale" || |
| 2424 | turn.finalized || |
| 2425 | turn.interrupted || |
| 2426 | turn.admissionGeneration !== generation |
| 2427 | ) { |
| 2428 | return; |
| 2429 | } |
| 2430 | if (turn.admissionStatusSequence !== statusSequence) { |
| 2431 | turn.admissionPending = true; |
| 2432 | continue; |
| 2433 | } |
| 2434 | if (status === "idle") { |
| 2435 | yield* finalizeTurn(state, turn, "completed"); |
| 2436 | return; |
| 2437 | } |
| 2438 | if (status === "busy") return; |
| 2439 | yield* Effect.sleep("250 millis"); |
| 2440 | } |
| 2441 | }); |
| 2442 | |
| 2443 | const reconcilePromptAdmission = Effect.fnUntraced(function* ( |
| 2444 | state: OpenCodeThreadState, |
| 2445 | turn: ActiveOpenCodeTurn, |
| 2446 | ) { |
| 2447 | const generation = turn.admissionGeneration; |
| 2448 | if ( |
| 2449 | !promptAdmissionIsCurrent(state, turn, generation) || |
| 2450 | turn.admissionReconciliationGeneration === generation |
| 2451 | ) { |
| 2452 | return; |
| 2453 | } |
| 2454 | turn.admissionReconciliationGeneration = generation; |
| 2455 | yield* runPromptAdmissionReconciliation(state, turn, generation).pipe( |
| 2456 | Effect.ensuring( |
| 2457 | Effect.sync(() => { |
| 2458 | if (turn.admissionReconciliationGeneration === generation) { |
| 2459 | turn.admissionReconciliationGeneration = null; |
| 2460 | } |
| 2461 | }), |
| 2462 | ), |
| 2463 | Effect.forkIn(scope), |
| 2464 | ); |
| 2465 | }); |
| 2466 | |
| 2467 | const createChildTurn = Effect.fnUntraced(function* ( |
| 2468 | state: OpenCodeThreadState, |
| 2469 | message: Extract<OpenCodeMessage, { role: "user" }>, |
| 2470 | ) { |
| 2471 | if (state.appThread === null || state.parentSubagent === null) return null; |
| 2472 | const ordinal = |
| 2473 | state.nextChildTurnOrdinal ?? |
| 2474 | (yield* storedUserMessagePosition(state.nativeSessionId, message.id)); |
| 2475 | state.nextChildTurnOrdinal = ordinal + 1; |
| 2476 | const now = yield* DateTime.now; |
| 2477 | const startedAt = dateTimeFromEpoch(message.time.created, now); |
| 2478 | const rootNodeId = idAllocator.derive.nodeFromProviderItem({ |
| 2479 | driver: OPENCODE_PROVIDER, |
| 2480 | nativeItemId: `${state.nativeSessionId}:root:${message.id}`, |
| 2481 | }); |
| 2482 | const providerTurnId = idAllocator.derive.providerTurn({ |
| 2483 | driver: OPENCODE_PROVIDER, |
| 2484 | nativeTurnId: message.id, |
| 2485 | }); |
| 2486 | const providerTurn: OrchestrationV2ProviderTurn = { |
| 2487 | id: providerTurnId, |
| 2488 | providerThreadId: state.providerThread.id, |
| 2489 | nodeId: rootNodeId, |
| 2490 | runAttemptId: null, |
| 2491 | nativeTurnRef: providerRef(message.id, "weak"), |
| 2492 | ordinal, |
| 2493 | status: "running", |
| 2494 | startedAt, |
| 2495 | completedAt: null, |
| 2496 | }; |
| 2497 | const turn: ActiveOpenCodeTurn = { |
| 2498 | isRoot: false, |
| 2499 | threadId: state.appThread.id, |
| 2500 | runId: null, |
| 2501 | rootNodeId, |
| 2502 | appThread: state.appThread, |
| 2503 | modelSelection: state.appThread.modelSelection, |
| 2504 | runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy, |
| 2505 | providerTurnId, |
| 2506 | providerThreadId: providerTurn.providerThreadId, |
| 2507 | runOrdinal: state.parentSubagent.parentTurn.runOrdinal, |
| 2508 | startedAt, |
| 2509 | itemOrdinals: new Map(), |
| 2510 | usage: makeOpenCodeTurnTokenUsageAccumulator(), |
| 2511 | parts: new Map(), |
| 2512 | partIdsByMessage: new Map(), |
| 2513 | toolNamesByCallId: new Map(), |
| 2514 | providerTurn, |
| 2515 | nextItemOrdinal: 1, |
| 2516 | nativeUserMessageId: message.id, |
| 2517 | admissionMessageId: null, |
| 2518 | priorWakePromptIds: new Set(), |
| 2519 | priorWakeSettled: null, |
| 2520 | interrupted: false, |
| 2521 | finalized: false, |
| 2522 | contextOverflow: null, |
| 2523 | planId: null, |
| 2524 | admissionGeneration: 0, |
| 2525 | admissionReconciliationGeneration: null, |
| 2526 | admissionPending: false, |
| 2527 | admissionAccepted: true, |
| 2528 | admissionMessageObserved: true, |
| 2529 | idleDuringAdmission: false, |
| 2530 | admissionUncertain: false, |
| 2531 | admissionStatusSequence: 0, |
| 2532 | admissionSettled: Deferred.makeUnsafe<void>(), |
| 2533 | admissionAbortController: null, |
| 2534 | }; |
| 2535 | state.activeTurn = turn; |
| 2536 | state.providerTurns.set(String(providerTurnId), providerTurn); |
| 2537 | yield* emitProviderEvent({ |
| 2538 | type: "node.updated", |
| 2539 | driver: OPENCODE_PROVIDER, |
| 2540 | node: { |
| 2541 | id: rootNodeId, |
| 2542 | threadId: turn.threadId, |
| 2543 | runId: null, |
| 2544 | parentNodeId: null, |
| 2545 | rootNodeId, |
| 2546 | kind: "root_turn", |
| 2547 | status: "running", |
| 2548 | countsForRun: false, |
| 2549 | providerThreadId: state.providerThread.id, |
| 2550 | providerTurnId, |
| 2551 | nativeItemRef: providerRef(message.id, "weak"), |
| 2552 | runtimeRequestId: null, |
| 2553 | checkpointScopeId: null, |
| 2554 | startedAt, |
| 2555 | completedAt: null, |
| 2556 | }, |
| 2557 | }); |
| 2558 | yield* emitProviderTurn(state, turn, "running", null); |
| 2559 | return turn; |
| 2560 | }); |
| 2561 | |
| 2562 | const projectChildUserPart = Effect.fnUntraced(function* ( |
| 2563 | state: OpenCodeThreadState, |
| 2564 | turn: ActiveOpenCodeTurn, |
| 2565 | part: Extract<OpenCodePart, { type: "text" }>, |
| 2566 | ) { |
| 2567 | const now = yield* DateTime.now; |
| 2568 | const messageId = idAllocator.derive.messageFromProviderItem({ |
| 2569 | driver: OPENCODE_PROVIDER, |
| 2570 | nativeItemId: part.messageID, |
| 2571 | }); |
| 2572 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 2573 | driver: OPENCODE_PROVIDER, |
| 2574 | nativeItemId: part.messageID, |
| 2575 | }); |
| 2576 | const projected: OrchestrationV2ConversationMessage = { |
| 2577 | createdBy: "agent", |
| 2578 | creationSource: "provider", |
| 2579 | id: messageId, |
| 2580 | threadId: turn.threadId, |
| 2581 | runId: null, |
| 2582 | nodeId: turn.rootNodeId, |
| 2583 | role: "user", |
| 2584 | text: part.text, |
| 2585 | attachments: [], |
| 2586 | streaming: false, |
| 2587 | createdAt: turn.startedAt, |
| 2588 | updatedAt: now, |
| 2589 | }; |
| 2590 | yield* emitProviderEvent({ |
| 2591 | type: "message.updated", |
| 2592 | driver: OPENCODE_PROVIDER, |
| 2593 | message: projected, |
| 2594 | }); |
| 2595 | yield* emitProviderEvent({ |
| 2596 | type: "turn_item.updated", |
| 2597 | driver: OPENCODE_PROVIDER, |
| 2598 | turnItem: { |
| 2599 | createdBy: "agent", |
| 2600 | creationSource: "provider", |
| 2601 | id: turnItemId, |
| 2602 | threadId: turn.threadId, |
| 2603 | runId: null, |
| 2604 | nodeId: turn.rootNodeId, |
| 2605 | providerThreadId: state.providerThread.id, |
| 2606 | providerTurnId: turn.providerTurnId, |
| 2607 | nativeItemRef: providerRef(part.messageID), |
| 2608 | parentItemId: null, |
| 2609 | ordinal: itemOrdinal(turn, part.messageID), |
| 2610 | status: "completed", |
| 2611 | title: null, |
| 2612 | startedAt: projected.createdAt, |
| 2613 | completedAt: now, |
| 2614 | updatedAt: now, |
| 2615 | type: "user_message", |
| 2616 | messageId, |
| 2617 | inputIntent: "turn_start", |
| 2618 | text: part.text, |
| 2619 | attachments: [], |
| 2620 | }, |
| 2621 | }); |
| 2622 | }); |
| 2623 | |
| 2624 | const emitCompactionItem = Effect.fn("OpenCodeAdapterV2.emitCompactionItem")(function* ( |
| 2625 | state: OpenCodeThreadState, |
| 2626 | turn: ActiveOpenCodeTurn, |
| 2627 | ) { |
| 2628 | const nativeItemId = `${turn.providerTurnId}:compaction`; |
| 2629 | if (turn.itemOrdinals.has(nativeItemId)) return; |
| 2630 | const now = yield* DateTime.now; |
| 2631 | yield* emitProviderEvent({ |
| 2632 | type: "turn_item.updated", |
| 2633 | driver: OPENCODE_PROVIDER, |
| 2634 | turnItem: { |
| 2635 | id: idAllocator.derive.turnItemFromProviderItem({ |
| 2636 | driver: OPENCODE_PROVIDER, |
| 2637 | nativeItemId, |
| 2638 | }), |
| 2639 | threadId: turn.threadId, |
| 2640 | runId: turn.runId, |
| 2641 | nodeId: turn.rootNodeId, |
| 2642 | providerThreadId: state.providerThread.id, |
| 2643 | providerTurnId: turn.providerTurnId, |
| 2644 | nativeItemRef: providerRef(nativeItemId, "weak"), |
| 2645 | parentItemId: null, |
| 2646 | ordinal: itemOrdinal(turn, nativeItemId), |
| 2647 | type: "compaction", |
| 2648 | driver: OPENCODE_PROVIDER, |
| 2649 | status: "completed", |
| 2650 | title: "Context compacted", |
| 2651 | startedAt: turn.startedAt, |
| 2652 | completedAt: now, |
| 2653 | updatedAt: now, |
| 2654 | }, |
| 2655 | }); |
| 2656 | // The pre-compaction step would otherwise settle the turn as its newest usage. |
| 2657 | turn.usage.lastStep = null; |
| 2658 | if (state.providerThread.contextUsage !== null) { |
| 2659 | yield* updateProviderThread(state, { contextUsage: null }); |
| 2660 | } |
| 2661 | }); |
| 2662 | |
| 2663 | const handleMessageUpdated = Effect.fnUntraced(function* ( |
| 2664 | event: Extract<OpenCodeEvent, { type: "message.updated" }>, |
| 2665 | ) { |
| 2666 | const state = threads.get(event.properties.sessionID); |
| 2667 | if (state === undefined) return; |
| 2668 | const message = event.properties.info; |
| 2669 | state.messageRoles.set(message.id, message.role); |
| 2670 | if (message.role === "assistant") { |
| 2671 | const usage = state.activeTurn?.usage; |
| 2672 | if (usage === undefined) return; |
| 2673 | const prior = usage.assistantOwnershipByMessageId.get(message.id); |
| 2674 | const ownership = |
| 2675 | prior !== undefined && prior !== "unknown" |
| 2676 | ? prior |
| 2677 | : !message.parentID |
| 2678 | ? "unknown" |
| 2679 | : usage.promptMessageIds.has(message.parentID) |
| 2680 | ? "owned" |
| 2681 | : "other"; |
| 2682 | usage.assistantOwnershipByMessageId.set(message.id, ownership); |
| 2683 | if (ownership !== "unknown") { |
| 2684 | if (ownership === "owned") { |
| 2685 | for (const step of usage.unresolvedStepsByMessageId.get(message.id)?.values() ?? |
| 2686 | []) { |
| 2687 | accumulateOpenCodeStepUsage(usage, step); |
| 2688 | } |
| 2689 | } |
| 2690 | usage.unresolvedStepsByMessageId.delete(message.id); |
| 2691 | } |
| 2692 | return; |
| 2693 | } |
| 2694 | const commandReceipt = commandReceipts.get(message.id); |
| 2695 | if (commandReceipt) yield* Deferred.succeed(commandReceipt, undefined); |
| 2696 | const isNewUserMessage = !state.userMessageIds.includes(message.id); |
| 2697 | if (isNewUserMessage) state.userMessageIds.push(message.id); |
| 2698 | let turn = state.activeTurn; |
| 2699 | if (turn === null && state.parentSubagent !== null && isNewUserMessage) { |
| 2700 | turn = yield* createChildTurn(state, message); |
| 2701 | } |
| 2702 | const matchesAdmission = |
| 2703 | turn !== null && |
| 2704 | (turn.admissionMessageId === null || turn.admissionMessageId === message.id); |
| 2705 | if (turn !== null && matchesAdmission) turn.usage.promptMessageIds.add(message.id); |
| 2706 | if (turn !== null && matchesAdmission && turn.nativeUserMessageId === null) { |
| 2707 | turn.nativeUserMessageId = message.id; |
| 2708 | yield* emitProviderTurn(state, turn, "running", null); |
| 2709 | } |
| 2710 | if (turn !== null && matchesAdmission && turn.admissionPending) { |
| 2711 | if (advanceOpenCodePromptAdmission(turn, "user-message") === "reconcile-idle") { |
| 2712 | yield* reconcilePromptAdmission(state, turn); |
| 2713 | } |
| 2714 | } |
| 2715 | }); |
| 2716 | |
| 2717 | const handlePartUpdated = Effect.fnUntraced(function* ( |
| 2718 | event: Extract<OpenCodeEvent, { type: "message.part.updated" }>, |
| 2719 | ) { |
| 2720 | const part = event.properties.part; |
| 2721 | const state = threads.get(part.sessionID); |
| 2722 | const turn = state?.activeTurn; |
| 2723 | if (state === undefined || turn === null || turn === undefined || turn.finalized) return; |
| 2724 | if (part.type === "text" && state.messageRoles.get(part.messageID) === "user") { |
| 2725 | if (!turn.isRoot) yield* projectChildUserPart(state, turn, part); |
| 2726 | return; |
| 2727 | } |
| 2728 | if (part.type === "step-finish") { |
| 2729 | const usage = turn.usage; |
| 2730 | const ownership = usage.assistantOwnershipByMessageId.get(part.messageID); |
| 2731 | if (ownership === "owned") accumulateOpenCodeStepUsage(usage, part); |
| 2732 | else if ( |
| 2733 | ownership === "unknown" || |
| 2734 | (ownership === undefined && !state.messageRoles.has(part.messageID)) |
| 2735 | ) { |
| 2736 | const steps = |
| 2737 | usage.unresolvedStepsByMessageId.get(part.messageID) ?? |
| 2738 | new Map<string, OpenCodeStepUsage>(); |
| 2739 | steps.set(part.id, { id: part.id, tokens: part.tokens }); |
| 2740 | usage.unresolvedStepsByMessageId.set(part.messageID, steps); |
| 2741 | } |
| 2742 | return; |
| 2743 | } |
| 2744 | if (part.type === "tool") { |
| 2745 | turn.toolNamesByCallId.set(part.callID, part.tool); |
| 2746 | } else { |
| 2747 | turn.parts.set(part.id, part); |
| 2748 | const ids = turn.partIdsByMessage.get(part.messageID) ?? new Set<string>(); |
| 2749 | ids.add(part.id); |
| 2750 | turn.partIdsByMessage.set(part.messageID, ids); |
| 2751 | } |
| 2752 | switch (part.type) { |
| 2753 | case "text": |
| 2754 | case "reasoning": |
| 2755 | yield* emitTextPart(state, turn, part); |
| 2756 | return; |
| 2757 | case "tool": |
| 2758 | yield* emitToolPart(state, turn, part); |
| 2759 | return; |
| 2760 | default: |
| 2761 | return; |
| 2762 | } |
| 2763 | }); |
| 2764 | |
| 2765 | const handlePartDelta = Effect.fnUntraced(function* ( |
| 2766 | event: Extract<OpenCodeEvent, { type: "message.part.delta" }>, |
| 2767 | ) { |
| 2768 | if (event.properties.field !== "text") return; |
| 2769 | const state = threads.get(event.properties.sessionID); |
| 2770 | const turn = state?.activeTurn; |
| 2771 | const current = turn?.parts.get(event.properties.partID); |
| 2772 | if ( |
| 2773 | state === undefined || |
| 2774 | turn === null || |
| 2775 | turn === undefined || |
| 2776 | current === undefined || |
| 2777 | (current.type !== "text" && current.type !== "reasoning") |
| 2778 | ) { |
| 2779 | return; |
| 2780 | } |
| 2781 | const updated = { ...current, text: current.text + event.properties.delta }; |
| 2782 | turn.parts.set(updated.id, updated); |
| 2783 | yield* emitTextPart(state, turn, updated); |
| 2784 | }); |
| 2785 | |
| 2786 | const handleAssistantCompleted = Effect.fnUntraced(function* ( |
| 2787 | event: Extract<OpenCodeEvent, { type: "message.updated" }>, |
| 2788 | admitsPrompt = true, |
| 2789 | ) { |
| 2790 | const message = event.properties.info; |
| 2791 | if (message.role !== "assistant" || message.time.completed === undefined) return; |
| 2792 | const state = threads.get(message.sessionID); |
| 2793 | const turn = state?.activeTurn; |
| 2794 | if (state === undefined || turn === null || turn === undefined) return; |
| 2795 | // Versions may ignore supplied message IDs; completed assistant output admits settlement on idle. |
| 2796 | if (admitsPrompt && !turn.priorWakePromptIds.has(message.parentID ?? "")) { |
| 2797 | advanceOpenCodePromptAdmission(turn, "assistant-completed"); |
| 2798 | } |
| 2799 | for (const partId of turn.partIdsByMessage.get(message.id) ?? []) { |
| 2800 | const part = turn.parts.get(partId); |
| 2801 | if (part?.type === "text" || part?.type === "reasoning") { |
| 2802 | yield* emitTextPart(state, turn, part, true); |
| 2803 | } |
| 2804 | } |
| 2805 | }); |
| 2806 | |
| 2807 | const abortRootSession = (state: OpenCodeThreadState) => |
| 2808 | sdkCall("session.abort", { sessionID: state.nativeSessionId }, (signal) => |
| 2809 | client.session.abort({ sessionID: state.nativeSessionId }, { signal }), |
| 2810 | ).pipe(Effect.timeout("10 seconds")); |
| 2811 | |
| 2812 | // Native aborts target the whole session, so replacement admission waits for all cleanup. |
| 2813 | const cleanupSessionWork = Effect.fn("OpencodeAdapter.cleanupSessionWork")(function* ( |
| 2814 | state: OpenCodeThreadState, |
| 2815 | rootAbort: Effect.Effect< |
| 2816 | unknown, |
| 2817 | | Effect.Error<ReturnType<typeof abortRootSession>> |
| 2818 | | ProviderAdapter.ProviderAdapterInterruptTimeoutError |
| 2819 | >, |
| 2820 | ) { |
| 2821 | const root = yield* rootAbort.pipe(Effect.result); |
| 2822 | const descendants = yield* abortDescendants(state.nativeSessionId).pipe(Effect.result); |
| 2823 | yield* interruptLaunchedSubagents(state.nativeSessionId); |
| 2824 | if (root._tag === "Failure") return yield* root.failure; |
| 2825 | if (descendants._tag === "Failure") return yield* descendants.failure; |
| 2826 | }); |
| 2827 | |
| 2828 | const cancelWake = Effect.fn("OpencodeAdapter.cancelWake")( |
| 2829 | function* (state: OpenCodeThreadState, wake: OpenCodeWake) { |
| 2830 | if (closing || nativeStreamFailure !== null || state.wake !== wake) return; |
| 2831 | wake.cancelling = true; |
| 2832 | // prompt.ts publishes its user message before run-state.ts registers a cancellable runner. |
| 2833 | // A noReply prompt saves one and never runs, so an undecided wake is aborted anyway. |
| 2834 | const running = |
| 2835 | wake.offered || |
| 2836 | (yield* Deferred.await(wake.admission).pipe( |
| 2837 | Effect.timeoutOption("10 seconds"), |
| 2838 | Effect.map(Option.getOrElse(() => true)), |
| 2839 | )); |
| 2840 | yield* cleanupSessionWork(state, running ? abortRootSession(state) : Effect.void).pipe( |
| 2841 | Effect.tapError(() => |
| 2842 | Effect.gen(function* () { |
| 2843 | if (yield* Deferred.isDone(wake.settled)) return; |
| 2844 | nativeStreamFailure = makeProviderFailure({ |
| 2845 | message: |
| 2846 | "OpenCode cancellation failed before native idle; reconnect the provider session.", |
| 2847 | class: "transport_error", |
| 2848 | }); |
| 2849 | yield* updateProviderSession("error", nativeStreamFailure.message); |
| 2850 | }), |
| 2851 | ), |
| 2852 | ); |
| 2853 | }, |
| 2854 | (effect, state, wake) => |
| 2855 | effect.pipe( |
| 2856 | Effect.ensuring( |
| 2857 | Effect.sync(() => { |
| 2858 | if (state.wake === wake) state.wake = null; |
| 2859 | }), |
| 2860 | ), |
| 2861 | ), |
| 2862 | ); |
| 2863 | |
| 2864 | const stopWake = (state: OpenCodeThreadState, wake: OpenCodeWake) => |
| 2865 | state.lifecyclePermit.withPermit( |
| 2866 | cancelWake(state, wake).pipe(Effect.ignore({ log: true })), |
| 2867 | ); |
| 2868 | |
| 2869 | const offerWake = (state: OpenCodeThreadState, wake: OpenCodeWake, threadId: ThreadId) => |
| 2870 | continuationRequests.offer({ |
| 2871 | threadId, |
| 2872 | providerThreadId: state.providerThread.id, |
| 2873 | driver: OPENCODE_PROVIDER, |
| 2874 | detail: null, |
| 2875 | delivery: "adapter_buffered", |
| 2876 | dispatchIfCurrent: (dispatch) => |
| 2877 | eventPermit.withPermit( |
| 2878 | Effect.suspend(() => |
| 2879 | state.wake === wake && |
| 2880 | !wake.cancelling && |
| 2881 | !closing && |
| 2882 | nativeStreamFailure === null |
| 2883 | ? Effect.asSome(dispatch) |
| 2884 | : Effect.succeedNone, |
| 2885 | ), |
| 2886 | ), |
| 2887 | clearIfCurrent: () => stopWake(state, wake), |
| 2888 | onRunEndedWithoutStarting: () => stopWake(state, wake), |
| 2889 | }); |
| 2890 | |
| 2891 | // Callers hold eventPermit. A root user message with no T3 turn starts a wake; its work stays |
| 2892 | // held, with that of children no turn has claimed yet, until startTurn takes it. |
| 2893 | const acceptEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) { |
| 2894 | const sessionId = sessionWorkEventSessionId(event); |
| 2895 | const owner = |
| 2896 | sessionId === undefined |
| 2897 | ? undefined |
| 2898 | : (threads.get(sessionId) ?? relatedSessionOwners.get(sessionId)); |
| 2899 | if (owner === undefined || sessionId === undefined) return yield* routeEvent(event); |
| 2900 | const wake = owner.wake; |
| 2901 | const isRoot = sessionId === owner.nativeSessionId; |
| 2902 | const rootStatus = |
| 2903 | isRoot && event.type === "session.status" ? event.properties.status.type : undefined; |
| 2904 | // A later execution buffered into the same wake is unsettled until its own idle. Its new |
| 2905 | // user message comes before busy, while prompt.ts may still be registering it. |
| 2906 | const newRootUserMessage = |
| 2907 | wake !== null && |
| 2908 | isRoot && |
| 2909 | event.type === "message.updated" && |
| 2910 | event.properties.info.role === "user" && |
| 2911 | !wake.events.some( |
| 2912 | (held) => |
| 2913 | held.type === "message.updated" && |
| 2914 | held.properties.info.id === event.properties.info.id, |
| 2915 | ); |
| 2916 | if ( |
| 2917 | wake !== null && |
| 2918 | (rootStatus === "busy" || rootStatus === "retry" || newRootUserMessage) && |
| 2919 | (yield* Deferred.isDone(wake.settled)) |
| 2920 | ) { |
| 2921 | wake.settled = Deferred.makeUnsafe<void>(); |
| 2922 | } |
| 2923 | if (wake?.cancelling) { |
| 2924 | if (!isRoot) return yield* routeEvent(event); |
| 2925 | wake.events.push(event); |
| 2926 | if (isRoot && (rootStatus === "busy" || rootStatus === "retry")) { |
| 2927 | wake.offered = true; |
| 2928 | yield* Deferred.succeed(wake.admission, true); |
| 2929 | } else if ( |
| 2930 | isRoot && |
| 2931 | (rootStatus === "idle" || |
| 2932 | event.type === "session.idle" || |
| 2933 | // OpenCode stays busy and auto-compacts after an overflow. |
| 2934 | (event.type === "session.error" && |
| 2935 | event.properties.error?.name !== "ContextOverflowError")) |
| 2936 | ) { |
| 2937 | yield* Deferred.succeed(wake.admission, false); |
| 2938 | yield* Deferred.succeed(wake.settled, undefined); |
| 2939 | } |
| 2940 | return; |
| 2941 | } |
| 2942 | if (wake !== null && isRoot && (rootStatus === "idle" || event.type === "session.idle")) { |
| 2943 | yield* Deferred.succeed(wake.settled, undefined); |
| 2944 | } |
| 2945 | // Idle before busy: nothing ran, so the held user message was only an update. |
| 2946 | if ( |
| 2947 | wake !== null && |
| 2948 | !wake.offered && |
| 2949 | isRoot && |
| 2950 | (rootStatus === "idle" || |
| 2951 | event.type === "session.idle" || |
| 2952 | event.type === "session.error") |
| 2953 | ) { |
| 2954 | yield* Deferred.succeed(wake.admission, false); |
| 2955 | owner.wake = null; |
| 2956 | } else if (wake !== null && (wake.offered || isRoot)) { |
| 2957 | wake.events.push(event); |
| 2958 | if (!wake.offered && (rootStatus === "busy" || rootStatus === "retry")) { |
| 2959 | wake.offered = true; |
| 2960 | yield* Deferred.succeed(wake.admission, true); |
| 2961 | const threadId = owner.providerThread.appThreadId; |
| 2962 | if (threadId !== null) yield* offerWake(owner, wake, threadId); |
| 2963 | } |
| 2964 | return; |
| 2965 | } |
| 2966 | if ( |
| 2967 | event.type === "message.updated" && |
| 2968 | event.properties.info.role === "user" && |
| 2969 | isRoot && |
| 2970 | owner.parentSubagent === null && |
| 2971 | owner.activeTurn === null && |
| 2972 | owner.providerThread.appThreadId !== null && |
| 2973 | !owner.userMessageIds.includes(event.properties.info.id) && |
| 2974 | !closing && |
| 2975 | nativeStreamFailure === null |
| 2976 | ) { |
| 2977 | owner.userMessageIds.push(event.properties.info.id); |
| 2978 | owner.wake = { |
| 2979 | events: [event], |
| 2980 | offered: false, |
| 2981 | cancelling: false, |
| 2982 | admission: Deferred.makeUnsafe<boolean>(), |
| 2983 | settled: Deferred.makeUnsafe<void>(), |
| 2984 | }; |
| 2985 | return; |
| 2986 | } |
| 2987 | yield* routeEvent(event); |
| 2988 | }); |
| 2989 | |
| 2990 | const handleEvent = Effect.fnUntraced(function* (event: OpenCodeEvent) { |
| 2991 | yield* logProtocolEvent({ |
| 2992 | direction: "incoming", |
| 2993 | messageKind: "notification", |
| 2994 | method: event.type, |
| 2995 | payload: event, |
| 2996 | }); |
| 2997 | // A slow native call only delays events, as on main; Stop goes through lifecyclePermit. |
| 2998 | yield* eventPermit.withPermit(acceptEvent(event)); |
| 2999 | }); |
| 3000 | |
| 3001 | const routeEvent = Effect.fnUntraced(function* ( |
| 3002 | event: OpenCodeEvent, |
| 3003 | historicalRootSessionId?: string, |
| 3004 | ) { |
| 3005 | const historicalRoot = |
| 3006 | historicalRootSessionId !== undefined && |
| 3007 | sessionWorkEventSessionId(event) === historicalRootSessionId; |
| 3008 | // A foreground prompt inherits held output, but has not submitted its own native work yet. |
| 3009 | if ( |
| 3010 | historicalRoot && |
| 3011 | (event.type === "session.status" || |
| 3012 | event.type === "session.idle" || |
| 3013 | event.type === "session.error") |
| 3014 | ) |
| 3015 | return; |
| 3016 | switch (event.type) { |
| 3017 | case "server.connected": |
| 3018 | if (hasConnected) { |
| 3019 | for (const state of threads.values()) { |
| 3020 | if (state.activeTurn !== null) state.activeTurn.usage.complete = false; |
| 3021 | } |
| 3022 | } |
| 3023 | hasConnected = true; |
| 3024 | return; |
| 3025 | case "message.updated": |
| 3026 | yield* handleMessageUpdated(event); |
| 3027 | yield* handleAssistantCompleted(event, !historicalRoot); |
| 3028 | return; |
| 3029 | case "session.compacted": { |
| 3030 | const state = threads.get(event.properties.sessionID); |
| 3031 | if (state?.activeTurn !== undefined && state.activeTurn !== null) { |
| 3032 | state.activeTurn.contextOverflow = null; |
| 3033 | yield* emitCompactionItem(state, state.activeTurn); |
| 3034 | } |
| 3035 | return; |
| 3036 | } |
| 3037 | case "message.part.updated": |
| 3038 | yield* handlePartUpdated(event); |
| 3039 | return; |
| 3040 | case "message.part.delta": |
| 3041 | yield* handlePartDelta(event); |
| 3042 | return; |
| 3043 | case "todo.updated": { |
| 3044 | const state = threads.get(event.properties.sessionID); |
| 3045 | if (state?.activeTurn !== null && state?.activeTurn !== undefined) { |
| 3046 | yield* emitTodo(state, state.activeTurn, event.properties.todos); |
| 3047 | } |
| 3048 | return; |
| 3049 | } |
| 3050 | case "permission.asked": |
| 3051 | yield* routeRuntimeRequest(event.properties.id, event.properties.sessionID, { |
| 3052 | type: "permission", |
| 3053 | value: event.properties, |
| 3054 | }); |
| 3055 | return; |
| 3056 | case "question.asked": |
| 3057 | yield* routeRuntimeRequest(event.properties.id, event.properties.sessionID, { |
| 3058 | type: "question", |
| 3059 | value: event.properties, |
| 3060 | }); |
| 3061 | return; |
| 3062 | case "permission.replied": |
| 3063 | case "question.replied": |
| 3064 | rememberSettledRequest(event.properties.requestID); |
| 3065 | yield* resolveRuntimeRequest(event.properties.requestID, "resolved"); |
| 3066 | return; |
| 3067 | case "question.rejected": |
| 3068 | rememberSettledRequest(event.properties.requestID); |
| 3069 | yield* resolveRuntimeRequest(event.properties.requestID, "cancelled"); |
| 3070 | return; |
| 3071 | case "session.created": |
| 3072 | case "session.updated": { |
| 3073 | const info = event.properties.info; |
| 3074 | if (event.type === "session.created" && info.parentID !== undefined) { |
| 3075 | unstartedSessionIds.add(info.id); |
| 3076 | } |
| 3077 | if (info.parentID !== undefined && !threads.has(info.id)) { |
| 3078 | const owner = threads.get(info.parentID) ?? relatedSessionOwners.get(info.parentID); |
| 3079 | if (owner !== undefined) { |
| 3080 | relatedSessionOwners.set(info.id, owner); |
| 3081 | } |
| 3082 | } |
| 3083 | return; |
| 3084 | } |
| 3085 | case "session.deleted": |
| 3086 | relatedSessionOwners.delete(event.properties.info.id); |
| 3087 | busySessionIds.delete(event.properties.info.id); |
| 3088 | unstartedSessionIds.delete(event.properties.info.id); |
| 3089 | yield* settleLaunchedSubagents(event.properties.info.id, "interrupted"); |
| 3090 | return; |
| 3091 | case "session.status": { |
| 3092 | const sessionId = event.properties.sessionID; |
| 3093 | unstartedSessionIds.delete(sessionId); |
| 3094 | switch (event.properties.status.type) { |
| 3095 | case "busy": |
| 3096 | case "retry": |
| 3097 | if (threads.has(sessionId) || relatedSessionOwners.has(sessionId)) { |
| 3098 | busySessionIds.add(sessionId); |
| 3099 | } |
| 3100 | break; |
| 3101 | case "idle": |
| 3102 | busySessionIds.delete(sessionId); |
| 3103 | break; |
| 3104 | } |
| 3105 | const state = threads.get(sessionId); |
| 3106 | if (state === undefined) return; |
| 3107 | if (state.activeTurn?.admissionPending) { |
| 3108 | state.activeTurn.admissionStatusSequence++; |
| 3109 | } |
| 3110 | if (event.properties.status.type === "busy") { |
| 3111 | yield* updateProviderThread(state, { status: "active" }); |
| 3112 | return; |
| 3113 | } |
| 3114 | if (event.properties.status.type === "idle" && state.activeTurn !== null) { |
| 3115 | if (state.activeTurn.priorWakeSettled !== null) { |
| 3116 | if (state.activeTurn.contextOverflow !== null) { |
| 3117 | yield* finalizeTurn(state, state.activeTurn, "completed"); |
| 3118 | } else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined); |
| 3119 | return; |
| 3120 | } |
| 3121 | if (state.activeTurn.admissionPending) { |
| 3122 | advanceOpenCodePromptAdmission(state.activeTurn, "idle"); |
| 3123 | return; |
| 3124 | } |
| 3125 | yield* finalizeTurn( |
| 3126 | state, |
| 3127 | state.activeTurn, |
| 3128 | state.activeTurn.interrupted ? "interrupted" : "completed", |
| 3129 | ); |
| 3130 | } |
| 3131 | if (event.properties.status.type === "idle") { |
| 3132 | yield* settleLaunchedSubagents(sessionId); |
| 3133 | } |
| 3134 | return; |
| 3135 | } |
| 3136 | case "session.idle": { |
| 3137 | busySessionIds.delete(event.properties.sessionID); |
| 3138 | unstartedSessionIds.delete(event.properties.sessionID); |
| 3139 | const state = threads.get(event.properties.sessionID); |
| 3140 | if (state?.activeTurn !== null && state?.activeTurn !== undefined) { |
| 3141 | if (state.activeTurn.priorWakeSettled !== null) { |
| 3142 | if (state.activeTurn.contextOverflow !== null) { |
| 3143 | yield* finalizeTurn(state, state.activeTurn, "completed"); |
| 3144 | } else yield* Deferred.succeed(state.activeTurn.priorWakeSettled, undefined); |
| 3145 | return; |
| 3146 | } |
| 3147 | if (state.activeTurn.admissionPending) { |
| 3148 | state.activeTurn.admissionStatusSequence++; |
| 3149 | advanceOpenCodePromptAdmission(state.activeTurn, "idle"); |
| 3150 | return; |
| 3151 | } |
| 3152 | yield* finalizeTurn( |
| 3153 | state, |
| 3154 | state.activeTurn, |
| 3155 | state.activeTurn.interrupted ? "interrupted" : "completed", |
| 3156 | ); |
| 3157 | } |
| 3158 | yield* settleLaunchedSubagents(event.properties.sessionID); |
| 3159 | return; |
| 3160 | } |
| 3161 | case "session.error": { |
| 3162 | const overflowTurn = |
| 3163 | event.properties.error?.name === "ContextOverflowError" && |
| 3164 | event.properties.sessionID !== undefined |
| 3165 | ? threads.get(event.properties.sessionID)?.activeTurn |
| 3166 | : undefined; |
| 3167 | if (overflowTurn !== undefined && overflowTurn !== null) { |
| 3168 | // OpenCode stays busy and auto-compacts; the turn fails only if it idles uncompacted. |
| 3169 | overflowTurn.contextOverflow = makeProviderFailure({ |
| 3170 | message: openCodeErrorMessage(event), |
| 3171 | code: "ContextOverflowError", |
| 3172 | class: "provider_error", |
| 3173 | }); |
| 3174 | return; |
| 3175 | } |
| 3176 | if (event.properties.sessionID !== undefined) { |
| 3177 | sessionErrorOutcomes.set( |
| 3178 | event.properties.sessionID, |
| 3179 | isMessageAbortedError(event) ? "interrupted" : "failed", |
| 3180 | ); |
| 3181 | } |
| 3182 | const states = |
| 3183 | event.properties.sessionID === undefined |
| 3184 | ? Array.from(threads.values()).filter((state) => state.activeTurn !== null) |
| 3185 | : [threads.get(event.properties.sessionID)].filter( |
| 3186 | (state): state is OpenCodeThreadState => state !== undefined, |
| 3187 | ); |
| 3188 | const error = event.properties.error; |
| 3189 | const usageLimit = error?.name === "APIError" && error.data.statusCode === 429; |
| 3190 | const failure = makeProviderFailure({ |
| 3191 | message: openCodeErrorMessage(event), |
| 3192 | code: error?.name ?? null, |
| 3193 | class: usageLimit ? "usage_limit" : "provider_error", |
| 3194 | }); |
| 3195 | if ( |
| 3196 | !isMessageAbortedError(event) && |
| 3197 | (event.properties.sessionID === undefined || |
| 3198 | states.some((state) => state.parentSubagent === null)) |
| 3199 | ) { |
| 3200 | yield* updateProviderSession("error", failure.message); |
| 3201 | } |
| 3202 | for (const state of states) { |
| 3203 | if (state.activeTurn !== null) { |
| 3204 | yield* finalizeTurn( |
| 3205 | state, |
| 3206 | state.activeTurn, |
| 3207 | terminalStatusForError(event, state.activeTurn), |
| 3208 | { |
| 3209 | failure, |
| 3210 | threadDisposition: |
| 3211 | event.properties.sessionID === undefined ? "broken" : "reusable", |
| 3212 | }, |
| 3213 | ); |
| 3214 | } |
| 3215 | } |
| 3216 | return; |
| 3217 | } |
| 3218 | default: |
| 3219 | return; |
| 3220 | } |
| 3221 | }); |
| 3222 | |
| 3223 | const inputProviderSessionId = input.providerSessionId; |
| 3224 | |
| 3225 | const subscription = yield* sdkCall("event.subscribe", {}, () => |
| 3226 | client.event.subscribe(undefined, { signal: abortController.signal }), |
| 3227 | ); |
| 3228 | yield* Scope.addFinalizer( |
| 3229 | scope, |
| 3230 | Effect.sync(() => abortController.abort()), |
| 3231 | ); |
| 3232 | yield* Stream.fromAsyncIterable( |
| 3233 | subscription.stream, |
| 3234 | (cause) => |
| 3235 | new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 3236 | operation: "event.subscribe", |
| 3237 | detail: OpenCodeRuntime.openCodeRuntimeErrorDetail(cause), |
| 3238 | cause, |
| 3239 | }), |
| 3240 | ).pipe( |
| 3241 | Stream.runForEach(handleEvent), |
| 3242 | Effect.exit, |
| 3243 | Effect.flatMap((exit) => |
| 3244 | Effect.gen(function* () { |
| 3245 | busySessionIds.clear(); |
| 3246 | unstartedSessionIds.clear(); |
| 3247 | sessionErrorOutcomes.clear(); |
| 3248 | if (closing || abortController.signal.aborted) return; |
| 3249 | const detail = Exit.isSuccess(exit) |
| 3250 | ? "OpenCode event stream ended unexpectedly." |
| 3251 | : OpenCodeRuntime.openCodeRuntimeErrorDetail(Cause.squash(exit.cause)); |
| 3252 | nativeStreamFailure = makeProviderFailure({ |
| 3253 | message: detail, |
| 3254 | class: "transport_error", |
| 3255 | }); |
| 3256 | yield* updateProviderSession("error", detail); |
| 3257 | for (const state of threads.values()) { |
| 3258 | // No continuation can admit a wake this stream will never finish. |
| 3259 | state.wake = null; |
| 3260 | if (state.activeTurn !== null) |
| 3261 | yield* finalizeTurn(state, state.activeTurn, "failed", { |
| 3262 | failure: makeProviderFailure({ message: detail, class: "transport_error" }), |
| 3263 | threadDisposition: "broken", |
| 3264 | }); |
| 3265 | yield* settleLaunchedSubagents(state.nativeSessionId, "failed"); |
| 3266 | } |
| 3267 | yield* Queue.end(events); |
| 3268 | }), |
| 3269 | ), |
| 3270 | Effect.forkIn(scope), |
| 3271 | ); |
| 3272 | |
| 3273 | if (!connection.external && connection.exitCode !== null) { |
| 3274 | yield* connection.exitCode.pipe( |
| 3275 | Effect.flatMap((code) => |
| 3276 | abortController.signal.aborted |
| 3277 | ? Effect.void |
| 3278 | : Effect.gen(function* () { |
| 3279 | const detail = `OpenCode server exited unexpectedly (${code}).`; |
| 3280 | nativeStreamFailure = makeProviderFailure({ |
| 3281 | message: detail, |
| 3282 | class: "transport_error", |
| 3283 | }); |
| 3284 | yield* updateProviderSession("error", detail); |
| 3285 | for (const state of threads.values()) { |
| 3286 | state.wake = null; |
| 3287 | if (state.activeTurn !== null) { |
| 3288 | yield* finalizeTurn(state, state.activeTurn, "failed", { |
| 3289 | failure: makeProviderFailure({ |
| 3290 | message: detail, |
| 3291 | class: "transport_error", |
| 3292 | }), |
| 3293 | threadDisposition: "broken", |
| 3294 | }); |
| 3295 | } |
| 3296 | } |
| 3297 | }), |
| 3298 | ), |
| 3299 | Effect.forkIn(scope), |
| 3300 | ); |
| 3301 | } |
| 3302 | |
| 3303 | if (connection.external) { |
| 3304 | yield* Scope.addFinalizer( |
| 3305 | scope, |
| 3306 | Effect.suspend(() => |
| 3307 | Effect.forEach( |
| 3308 | Array.from(threads.values()).filter((state) => state.parentSubagent === null), |
| 3309 | (state) => |
| 3310 | sdkCall("session.abort", { sessionID: state.nativeSessionId }, (signal) => |
| 3311 | client.session.abort({ sessionID: state.nativeSessionId }, { signal }), |
| 3312 | ).pipe( |
| 3313 | Effect.timeout("1 second"), |
| 3314 | Effect.ignore({ log: true }), |
| 3315 | Effect.andThen( |
| 3316 | abortDescendants(state.nativeSessionId).pipe( |
| 3317 | Effect.timeout("1 second"), |
| 3318 | Effect.ignore({ log: true }), |
| 3319 | ), |
| 3320 | ), |
| 3321 | ), |
| 3322 | { concurrency: 8, discard: true }, |
| 3323 | ), |
| 3324 | ), |
| 3325 | ); |
| 3326 | } |
| 3327 | |
| 3328 | yield* Scope.addFinalizer( |
| 3329 | scope, |
| 3330 | Effect.sync(() => { |
| 3331 | closing = true; |
| 3332 | for (const state of threads.values()) state.wake = null; |
| 3333 | }), |
| 3334 | ); |
| 3335 | |
| 3336 | const registerThread = ( |
| 3337 | nativeSession: OpenCodeSession, |
| 3338 | providerThread: OrchestrationV2ProviderThread, |
| 3339 | appThread: OrchestrationV2AppThread | null, |
| 3340 | ): OpenCodeThreadState => { |
| 3341 | const existing = threads.get(nativeSession.id); |
| 3342 | if (existing !== undefined) { |
| 3343 | existing.providerThread = providerThread; |
| 3344 | if (appThread !== null) existing.appThread = appThread; |
| 3345 | if (nativeSession.permission !== undefined) |
| 3346 | existing.permission = nativeSession.permission; |
| 3347 | return existing; |
| 3348 | } |
| 3349 | const parentSubagent = subagentsByChildSessionId.get(nativeSession.id) ?? null; |
| 3350 | const state: OpenCodeThreadState = { |
| 3351 | nativeSessionId: nativeSession.id, |
| 3352 | providerThread, |
| 3353 | appThread, |
| 3354 | activeTurn: null, |
| 3355 | providerTurns: new Map(), |
| 3356 | runtimeRequests: new Map(), |
| 3357 | messageRoles: new Map(), |
| 3358 | userMessageIds: [], |
| 3359 | parentSubagent, |
| 3360 | nextChildTurnOrdinal: 1, |
| 3361 | nextAdmissionGeneration: 1, |
| 3362 | wake: null, |
| 3363 | lifecyclePermit: Semaphore.makeUnsafe(1), |
| 3364 | permission: nativeSession.permission ?? [], |
| 3365 | inheritedPermission: parentSubagent?.parentState.permission ?? [], |
| 3366 | }; |
| 3367 | threads.set(nativeSession.id, state); |
| 3368 | return state; |
| 3369 | }; |
| 3370 | |
| 3371 | // OpenCode copies parent rules into a child only at creation, so children are updated here too. |
| 3372 | const applyPermissionRules = Effect.fnUntraced(function* ( |
| 3373 | state: OpenCodeThreadState, |
| 3374 | policy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, |
| 3375 | ) { |
| 3376 | const parentRules = openCodePermissionRules(policy); |
| 3377 | const pending = [state]; |
| 3378 | for (let target = pending.pop(); target !== undefined; target = pending.pop()) { |
| 3379 | const previous = target.permission; |
| 3380 | const permission = |
| 3381 | target.parentSubagent === null |
| 3382 | ? parentRules |
| 3383 | : openCodeChildPermissionRules(policy, previous, target.inheritedPermission); |
| 3384 | if ( |
| 3385 | permission.length !== previous.length || |
| 3386 | !permission.every((rule, index) => permissionRuleEquals(rule, previous[index]!)) |
| 3387 | ) { |
| 3388 | const sessionID = target.nativeSessionId; |
| 3389 | yield* sdkCall("session.update", { sessionID, permission }, () => |
| 3390 | client.session.update({ sessionID, permission }), |
| 3391 | ); |
| 3392 | target.permission = permission; |
| 3393 | } |
| 3394 | if (target.parentSubagent !== null) target.inheritedPermission = parentRules; |
| 3395 | for (const child of threads.values()) { |
| 3396 | if (child.parentSubagent?.parentState === target) pending.push(child); |
| 3397 | } |
| 3398 | } |
| 3399 | }); |
| 3400 | |
| 3401 | const resolvePromptParts = Effect.fnUntraced(function* ( |
| 3402 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 3403 | ) { |
| 3404 | if (turnInput.resume) return []; |
| 3405 | const text = (yield* providerMessageTextWithAttachmentPaths({ |
| 3406 | text: turnInput.message.text, |
| 3407 | attachments: turnInput.message.attachments, |
| 3408 | resolveAttachmentPath: host.resolveAttachmentPath, |
| 3409 | resolveExtractedTextPath: host.resolveExtractedTextPath, |
| 3410 | })).trim(); |
| 3411 | const files = OpenCodeRuntime.toOpenCodeFileParts({ |
| 3412 | attachments: turnInput.message.attachments, |
| 3413 | resolveAttachmentPath: host.resolveAttachmentPath, |
| 3414 | }); |
| 3415 | if (text.length === 0 && files.length === 0) { |
| 3416 | throw protocolError("OpenCode turns require text or at least one valid attachment"); |
| 3417 | } |
| 3418 | return [...(text.length === 0 ? [] : [{ type: "text" as const, text }]), ...files]; |
| 3419 | }); |
| 3420 | |
| 3421 | const readSnapshot = Effect.fnUntraced(function* ( |
| 3422 | providerThread: OrchestrationV2ProviderThread, |
| 3423 | ) { |
| 3424 | const sessionId = nativeThreadId(providerThread); |
| 3425 | const sessionResponse = yield* sdkCall("session.get", { sessionID: sessionId }, () => |
| 3426 | client.session.get({ sessionID: sessionId }), |
| 3427 | ); |
| 3428 | const nativeSession = unwrapData("session.get", sessionResponse); |
| 3429 | const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () => |
| 3430 | client.session.messages({ sessionID: sessionId }), |
| 3431 | ); |
| 3432 | const nativeMessages = []; |
| 3433 | for (const entry of unwrapData("session.messages", response)) { |
| 3434 | // Reverted records remain in messages; stop at the revert marker to avoid resurrecting work. |
| 3435 | if (entry.info.id === nativeSession.revert?.messageID) break; |
| 3436 | nativeMessages.push(entry); |
| 3437 | } |
| 3438 | const state = threads.get(sessionId); |
| 3439 | const snapshotNow = yield* DateTime.now; |
| 3440 | const messages: Array<OrchestrationV2ConversationMessage> = nativeMessages.flatMap( |
| 3441 | ({ info, parts }) => { |
| 3442 | const text = parts |
| 3443 | .filter( |
| 3444 | (part): part is Extract<OpenCodePart, { type: "text" }> => part.type === "text", |
| 3445 | ) |
| 3446 | .filter((part) => part.ignored !== true && part.synthetic !== true) |
| 3447 | .map((part) => part.text) |
| 3448 | .join("\n"); |
| 3449 | if (text.length === 0) return []; |
| 3450 | const createdAt = dateTimeFromEpoch(info.time.created, snapshotNow); |
| 3451 | return [ |
| 3452 | { |
| 3453 | createdBy: info.role === "user" ? "user" : "agent", |
| 3454 | creationSource: "provider", |
| 3455 | id: idAllocator.derive.messageFromProviderItem({ |
| 3456 | driver: OPENCODE_PROVIDER, |
| 3457 | nativeItemId: info.id, |
| 3458 | }), |
| 3459 | threadId: providerThread.appThreadId ?? input.threadId, |
| 3460 | runId: null, |
| 3461 | nodeId: null, |
| 3462 | role: info.role, |
| 3463 | text, |
| 3464 | attachments: [], |
| 3465 | streaming: false, |
| 3466 | createdAt, |
| 3467 | updatedAt: |
| 3468 | info.role === "assistant" |
| 3469 | ? dateTimeFromEpoch(info.time.completed, createdAt) |
| 3470 | : createdAt, |
| 3471 | }, |
| 3472 | ]; |
| 3473 | }, |
| 3474 | ); |
| 3475 | const lastUser = nativeMessages.findLast(({ info }) => info.role === "user")?.info.id; |
| 3476 | return { |
| 3477 | providerThread: { |
| 3478 | ...providerThread, |
| 3479 | providerSessionId: input.providerSessionId, |
| 3480 | nativeConversationHeadRef: |
| 3481 | lastUser === undefined ? null : providerRef(lastUser, "weak"), |
| 3482 | status: "idle" as const, |
| 3483 | updatedAt: snapshotNow, |
| 3484 | }, |
| 3485 | providerTurns: state === undefined ? [] : [...state.providerTurns.values()], |
| 3486 | messages, |
| 3487 | runtimeRequests: state === undefined ? [] : [...state.runtimeRequests.values()], |
| 3488 | providerPayload: nativeMessages, |
| 3489 | }; |
| 3490 | }); |
| 3491 | |
| 3492 | // OpenCode runs each step with the agent and system prompt of the latest |
| 3493 | // user message, so every prompt in a turn, steers included, repeats them. |
| 3494 | const turnPromptOptions = (turn: ActiveOpenCodeTurn) => { |
| 3495 | const agent = |
| 3496 | getModelSelectionStringOptionValue(turn.modelSelection, "agent") ?? |
| 3497 | (turn.runtimePolicy.interactionMode === "plan" ? "plan" : undefined); |
| 3498 | const variant = getModelSelectionStringOptionValue(turn.modelSelection, "variant"); |
| 3499 | return { |
| 3500 | ...(agent === undefined ? {} : { agent }), |
| 3501 | ...(variant === undefined ? {} : { variant }), |
| 3502 | system: [ |
| 3503 | orchestrationSystemPrompt, |
| 3504 | buildRuntimeInstructions({ harness: "OpenCode", model: turn.modelSelection.model }), |
| 3505 | ] |
| 3506 | .filter(Boolean) |
| 3507 | .join("\n\n"), |
| 3508 | }; |
| 3509 | }; |
| 3510 | |
| 3511 | // Native commands await generation; user-message receipts admit their background requests. |
| 3512 | const submitPrompt = Effect.fn("OpenCode.submitPrompt")(function* ( |
| 3513 | state: OpenCodeThreadState, |
| 3514 | turn: ActiveOpenCodeTurn, |
| 3515 | inputPayload: Parameters<typeof client.session.promptAsync>[0] & { |
| 3516 | messageID: string; |
| 3517 | sessionID: string; |
| 3518 | }, |
| 3519 | abortController: AbortController, |
| 3520 | messageText: string, |
| 3521 | ) { |
| 3522 | const { variant, ...payloadWithoutVariant } = inputPayload; |
| 3523 | const selectedVariant = yield* OpenCodeRuntime.resolveOpenCodeVariant( |
| 3524 | client, |
| 3525 | inputPayload.model, |
| 3526 | variant, |
| 3527 | abortController.signal, |
| 3528 | variantCache, |
| 3529 | ); |
| 3530 | const payload = { |
| 3531 | ...payloadWithoutVariant, |
| 3532 | ...(selectedVariant === undefined ? {} : { variant: selectedVariant }), |
| 3533 | }; |
| 3534 | const match = messageText.trim().match(/^\/(\S+)(?:\s+([\s\S]*))?$/); |
| 3535 | const command = match |
| 3536 | ? (yield* OpenCodeRuntime.loadOpenCodeCommands(client).pipe( |
| 3537 | Effect.timeout("10 seconds"), |
| 3538 | Effect.orElseSucceed(() => []), |
| 3539 | )).find((entry) => entry.name === match[1]) |
| 3540 | : undefined; |
| 3541 | if (!command) { |
| 3542 | return yield* sdkCall("session.promptAsync", payload, (signal) => |
| 3543 | client.session.promptAsync(payload, { |
| 3544 | signal: AbortSignal.any([signal, abortController.signal]), |
| 3545 | }), |
| 3546 | ).pipe(Effect.asVoid); |
| 3547 | } |
| 3548 | const receipt = Deferred.makeUnsafe<void>(); |
| 3549 | commandReceipts.set(payload.messageID, receipt); |
| 3550 | const controllers = |
| 3551 | commandControllers.get(payload.sessionID) ?? new Set<AbortController>(); |
| 3552 | controllers.add(abortController); |
| 3553 | commandControllers.set(payload.sessionID, controllers); |
| 3554 | const generation = turn.admissionGeneration; |
| 3555 | const commandPayload = { |
| 3556 | sessionID: payload.sessionID, |
| 3557 | messageID: payload.messageID, |
| 3558 | command: command.name, |
| 3559 | arguments: match?.[2] ?? "", |
| 3560 | ...(payload.model |
| 3561 | ? { model: `${payload.model.providerID}/${payload.model.modelID}` } |
| 3562 | : {}), |
| 3563 | ...(payload.agent ? { agent: payload.agent } : {}), |
| 3564 | ...(payload.variant ? { variant: payload.variant } : {}), |
| 3565 | parts: payload.parts?.filter((part) => part.type === "file") ?? [], |
| 3566 | }; |
| 3567 | const request = yield* sdkCall("session.command", commandPayload, (signal) => |
| 3568 | client.session.command(commandPayload, { |
| 3569 | signal: AbortSignal.any([signal, abortController.signal]), |
| 3570 | }), |
| 3571 | ).pipe( |
| 3572 | Effect.asVoid, |
| 3573 | // OpenCode answers only when generation ends; once admitted, the event stream owns the outcome. |
| 3574 | Effect.tapError((cause) => |
| 3575 | Deferred.isDoneUnsafe(receipt) || |
| 3576 | abortController.signal.aborted || |
| 3577 | turn.finalized || |
| 3578 | turn.admissionGeneration !== generation |
| 3579 | ? Effect.void |
| 3580 | : finalizeTurn(state, turn, "failed", { |
| 3581 | failure: makeProviderFailure({ cause, class: "provider_error" }), |
| 3582 | }), |
| 3583 | ), |
| 3584 | Effect.ensuring( |
| 3585 | Effect.sync(() => { |
| 3586 | commandReceipts.delete(payload.messageID); |
| 3587 | controllers.delete(abortController); |
| 3588 | if (controllers.size === 0) commandControllers.delete(payload.sessionID); |
| 3589 | }), |
| 3590 | ), |
| 3591 | Effect.forkIn(scope), |
| 3592 | ); |
| 3593 | yield* Effect.raceFirst(Fiber.join(request), Deferred.await(receipt)).pipe( |
| 3594 | Effect.timeout("10 seconds"), |
| 3595 | Effect.catchTags({ |
| 3596 | TimeoutError: (cause) => { |
| 3597 | const error = new OpenCodeRuntime.OpenCodeRuntimeError({ |
| 3598 | operation: "session.command", |
| 3599 | detail: "OpenCode command admission did not complete within 10 seconds.", |
| 3600 | cause, |
| 3601 | }); |
| 3602 | abortController.abort(); |
| 3603 | return finalizeTurn(state, turn, "failed", { |
| 3604 | failure: makeProviderFailure({ cause: error, class: "provider_error" }), |
| 3605 | }).pipe(Effect.andThen(Effect.fail(error))); |
| 3606 | }, |
| 3607 | }), |
| 3608 | ); |
| 3609 | }); |
| 3610 | |
| 3611 | const runtimeSession: ProviderAdapter.ProviderAdapterV2SessionRuntime = { |
| 3612 | instanceId: options.instanceId, |
| 3613 | driver: OPENCODE_PROVIDER, |
| 3614 | providerSessionId: input.providerSessionId, |
| 3615 | providerSession: sessionEntity, |
| 3616 | events: Stream.fromEffectRepeat(Queue.take(events)), |
| 3617 | hasPendingBackgroundWork: Effect.sync( |
| 3618 | () => |
| 3619 | busySessionIds.size > 0 || |
| 3620 | Array.from(threads.values()).some((state) => state.wake?.offered === true), |
| 3621 | ), |
| 3622 | ensureThread: Effect.fn("OpencodeAdapter.ensureThread")( |
| 3623 | function* (threadInput) { |
| 3624 | if (threadInput.existingProviderThread?.nativeThreadRef != null) { |
| 3625 | return yield* runtimeSession.resumeThread({ |
| 3626 | providerThread: threadInput.existingProviderThread, |
| 3627 | }); |
| 3628 | } |
| 3629 | const permission = openCodePermissionRules(threadInput.runtimePolicy); |
| 3630 | // OpenCode generates a title only when session.create leaves it unset. |
| 3631 | const response = yield* sdkCall("session.create", { permission }, () => |
| 3632 | client.session.create({ permission }), |
| 3633 | ); |
| 3634 | const nativeSession = unwrapData("session.create", response); |
| 3635 | const createdAt = yield* DateTime.now; |
| 3636 | const created = makeProviderThread({ |
| 3637 | idAllocator, |
| 3638 | providerInstanceId: options.instanceId, |
| 3639 | providerSessionId: input.providerSessionId, |
| 3640 | appThreadId: threadInput.threadId, |
| 3641 | nativeSession, |
| 3642 | now: createdAt, |
| 3643 | }); |
| 3644 | const existing = threadInput.existingProviderThread; |
| 3645 | const providerThread = |
| 3646 | existing === undefined |
| 3647 | ? created |
| 3648 | : { |
| 3649 | ...existing, |
| 3650 | providerSessionId: input.providerSessionId, |
| 3651 | nativeThreadRef: created.nativeThreadRef, |
| 3652 | nativeConversationHeadRef: created.nativeConversationHeadRef, |
| 3653 | status: created.status, |
| 3654 | updatedAt: created.updatedAt, |
| 3655 | }; |
| 3656 | registerThread(nativeSession, providerThread, null).permission = permission; |
| 3657 | return providerThread; |
| 3658 | }, |
| 3659 | (effect, threadInput) => |
| 3660 | effect.pipe( |
| 3661 | Effect.mapError( |
| 3662 | (cause) => |
| 3663 | new ProviderAdapter.ProviderAdapterEnsureThreadError({ |
| 3664 | driver: OPENCODE_PROVIDER, |
| 3665 | threadId: threadInput.threadId, |
| 3666 | cause, |
| 3667 | }), |
| 3668 | ), |
| 3669 | ), |
| 3670 | ), |
| 3671 | resumeThread: Effect.fn("OpencodeAdapter.resumeThread")( |
| 3672 | function* (threadInput) { |
| 3673 | const sessionId = nativeThreadId(threadInput.providerThread); |
| 3674 | const response = yield* sdkCall("session.get", { sessionID: sessionId }, () => |
| 3675 | client.session.get({ sessionID: sessionId }), |
| 3676 | ); |
| 3677 | const nativeSession = unwrapData("session.get", response); |
| 3678 | const resumedAt = yield* DateTime.now; |
| 3679 | const providerThread = { |
| 3680 | ...threadInput.providerThread, |
| 3681 | providerSessionId: input.providerSessionId, |
| 3682 | status: "idle" as const, |
| 3683 | updatedAt: dateTimeFromEpoch(nativeSession.time.updated, resumedAt), |
| 3684 | }; |
| 3685 | const state = registerThread(nativeSession, providerThread, null); |
| 3686 | if (threadInput.runtimePolicy !== undefined) { |
| 3687 | yield* applyPermissionRules(state, threadInput.runtimePolicy); |
| 3688 | } |
| 3689 | return providerThread; |
| 3690 | }, |
| 3691 | (effect, threadInput) => |
| 3692 | effect.pipe( |
| 3693 | Effect.mapError( |
| 3694 | (cause) => |
| 3695 | new ProviderAdapter.ProviderAdapterResumeThreadError({ |
| 3696 | driver: OPENCODE_PROVIDER, |
| 3697 | providerSessionId: input.providerSessionId, |
| 3698 | providerThreadId: threadInput.providerThread.id, |
| 3699 | cause, |
| 3700 | }), |
| 3701 | ), |
| 3702 | ), |
| 3703 | ), |
| 3704 | compactThread: (turnInput) => |
| 3705 | runtimeSession.startTurn({ |
| 3706 | ...turnInput, |
| 3707 | message: { ...turnInput.message, text: "/compact" }, |
| 3708 | }), |
| 3709 | resumeTurn: (input) => runtimeSession.startTurn(ProviderAdapter.resumeTurnInput(input)), |
| 3710 | startTurn: Effect.fn("OpencodeAdapter.startTurn")( |
| 3711 | function* (turnInput) { |
| 3712 | if (closing || nativeStreamFailure !== null) { |
| 3713 | return yield* protocolError( |
| 3714 | "OpenCode event stream has ended; reconnect the provider session before starting another turn.", |
| 3715 | ); |
| 3716 | } |
| 3717 | const sessionId = nativeThreadId(turnInput.providerThread); |
| 3718 | const state = threads.get(sessionId); |
| 3719 | if (state === undefined) { |
| 3720 | return yield* protocolError(`OpenCode session ${sessionId} is not registered`); |
| 3721 | } |
| 3722 | if (state.activeTurn !== null) { |
| 3723 | return yield* new ProviderAdapter.ProviderAdapterProtocolError({ |
| 3724 | driver: OPENCODE_PROVIDER, |
| 3725 | detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`, |
| 3726 | reason: "previous_turn_active", |
| 3727 | }); |
| 3728 | } |
| 3729 | const continuation = |
| 3730 | turnInput.message.createdBy === "agent" && |
| 3731 | turnInput.message.creationSource === "provider"; |
| 3732 | const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug( |
| 3733 | turnInput.modelSelection.model, |
| 3734 | ); |
| 3735 | if (parsedModel === null) { |
| 3736 | return yield* protocolError( |
| 3737 | `OpenCode model '${turnInput.modelSelection.model}' must use provider/model format`, |
| 3738 | ); |
| 3739 | } |
| 3740 | yield* applyPermissionRules(state, turnInput.runtimePolicy); |
| 3741 | // A continuation admits a wake OpenCode is already running, so it sends no prompt. |
| 3742 | const isCompaction = |
| 3743 | !continuation && |
| 3744 | turnInput.message.text.trim() === "/compact" && |
| 3745 | turnInput.message.attachments.length === 0; |
| 3746 | const parts = |
| 3747 | isCompaction || continuation ? [] : yield* resolvePromptParts(turnInput); |
| 3748 | const startedAt = yield* DateTime.now; |
| 3749 | const syntheticNativeTurnId = `${sessionId}:attempt:${turnInput.attemptId}`; |
| 3750 | const providerTurnId = idAllocator.derive.providerTurn({ |
| 3751 | driver: OPENCODE_PROVIDER, |
| 3752 | nativeTurnId: syntheticNativeTurnId, |
| 3753 | }); |
| 3754 | const providerTurn: OrchestrationV2ProviderTurn = { |
| 3755 | id: providerTurnId, |
| 3756 | providerThreadId: turnInput.providerThread.id, |
| 3757 | nodeId: turnInput.rootNodeId, |
| 3758 | runAttemptId: turnInput.attemptId, |
| 3759 | nativeTurnRef: providerRef(syntheticNativeTurnId, "weak"), |
| 3760 | ordinal: turnInput.providerTurnOrdinal, |
| 3761 | status: "running", |
| 3762 | startedAt, |
| 3763 | completedAt: null, |
| 3764 | }; |
| 3765 | const admissionMessageId = continuation |
| 3766 | ? null |
| 3767 | : yield* makeOpenCodeMessageId(messageIdClock); |
| 3768 | const turn: ActiveOpenCodeTurn = { |
| 3769 | isRoot: true, |
| 3770 | threadId: turnInput.threadId, |
| 3771 | runId: turnInput.runId, |
| 3772 | rootNodeId: turnInput.rootNodeId, |
| 3773 | appThread: turnInput.appThread, |
| 3774 | modelSelection: turnInput.modelSelection, |
| 3775 | runtimePolicy: turnInput.runtimePolicy, |
| 3776 | providerTurnId, |
| 3777 | providerThreadId: turnInput.providerThread.id, |
| 3778 | runOrdinal: turnInput.runOrdinal, |
| 3779 | startedAt, |
| 3780 | itemOrdinals: new Map(), |
| 3781 | usage: makeOpenCodeTurnTokenUsageAccumulator(), |
| 3782 | parts: new Map(), |
| 3783 | partIdsByMessage: new Map(), |
| 3784 | toolNamesByCallId: new Map(), |
| 3785 | providerTurn, |
| 3786 | nextItemOrdinal: turnInput.providerTurnOrdinal * 100 + 1, |
| 3787 | nativeUserMessageId: null, |
| 3788 | admissionMessageId, |
| 3789 | priorWakePromptIds: new Set(), |
| 3790 | priorWakeSettled: null, |
| 3791 | interrupted: false, |
| 3792 | finalized: false, |
| 3793 | contextOverflow: null, |
| 3794 | planId: null, |
| 3795 | admissionGeneration: state.nextAdmissionGeneration++, |
| 3796 | admissionReconciliationGeneration: null, |
| 3797 | admissionPending: !isCompaction && !continuation, |
| 3798 | admissionAccepted: isCompaction || continuation, |
| 3799 | admissionMessageObserved: false, |
| 3800 | idleDuringAdmission: false, |
| 3801 | admissionUncertain: false, |
| 3802 | admissionStatusSequence: 0, |
| 3803 | admissionSettled: Deferred.makeUnsafe<void>(), |
| 3804 | admissionAbortController: continuation |
| 3805 | ? null |
| 3806 | : // @effect-diagnostics-next-line abortControllerInEffect:off - Turn interruption owns prompt admission cancellation. |
| 3807 | new AbortController(), |
| 3808 | }; |
| 3809 | if (turn.admissionMessageId !== null) |
| 3810 | turn.usage.promptMessageIds.add(turn.admissionMessageId); |
| 3811 | const admissionSettled = turn.admissionSettled; |
| 3812 | const admissionAbortController = turn.admissionAbortController; |
| 3813 | yield* state.lifecyclePermit.withPermit( |
| 3814 | Effect.gen(function* () { |
| 3815 | const candidate = state.wake; |
| 3816 | if (!continuation && candidate !== null && !candidate.offered) { |
| 3817 | // A noReply prompt saves a user message and never runs; OpenCode queues a |
| 3818 | // prompt behind a loop that did start, so the foreground submits either way. |
| 3819 | const admission = yield* Deferred.await(candidate.admission).pipe( |
| 3820 | Effect.timeoutOption("10 seconds"), |
| 3821 | ); |
| 3822 | if (Option.isNone(admission) && state.wake === candidate) state.wake = null; |
| 3823 | } |
| 3824 | yield* eventPermit.withPermit( |
| 3825 | Effect.gen(function* () { |
| 3826 | // Do not yield before turn installation; EOF may otherwise finish scanning before registration. |
| 3827 | if (closing || nativeStreamFailure !== null) { |
| 3828 | return yield* protocolError( |
| 3829 | "OpenCode event stream has ended; reconnect the provider session before starting another turn.", |
| 3830 | ); |
| 3831 | } |
| 3832 | if (state.activeTurn !== null) { |
| 3833 | return yield* new ProviderAdapter.ProviderAdapterProtocolError({ |
| 3834 | driver: OPENCODE_PROVIDER, |
| 3835 | detail: `OpenCode provider thread ${turnInput.providerThread.id} already has an active turn`, |
| 3836 | reason: "previous_turn_active", |
| 3837 | }); |
| 3838 | } |
| 3839 | const wake = state.wake; |
| 3840 | if (!continuation) turn.priorWakeSettled = wake?.settled ?? null; |
| 3841 | state.wake = null; |
| 3842 | state.appThread = turnInput.appThread; |
| 3843 | state.activeTurn = turn; |
| 3844 | state.providerTurns.set(String(providerTurnId), providerTurn); |
| 3845 | yield* emitProviderTurn(state, turn, "running", null); |
| 3846 | yield* updateProviderThread(state, { |
| 3847 | status: "active", |
| 3848 | firstRunOrdinal: |
| 3849 | state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal, |
| 3850 | lastRunOrdinal: turnInput.runOrdinal, |
| 3851 | }); |
| 3852 | yield* updateProviderSession("running", null); |
| 3853 | if (!continuation) { |
| 3854 | for (const event of wake?.events ?? []) { |
| 3855 | if ( |
| 3856 | event.type === "message.updated" && |
| 3857 | event.properties.sessionID === sessionId && |
| 3858 | event.properties.info.role === "user" |
| 3859 | ) { |
| 3860 | turn.priorWakePromptIds.add(event.properties.info.id); |
| 3861 | } |
| 3862 | } |
| 3863 | } |
| 3864 | // Work held after this turn settles is a later result; it starts its own wake. |
| 3865 | yield* Effect.forEach(wake?.events ?? [], (event) => |
| 3866 | (state.activeTurn === turn |
| 3867 | ? routeEvent(event, continuation ? undefined : sessionId) |
| 3868 | : acceptEvent(event) |
| 3869 | ).pipe(Effect.timeout("10 seconds")), |
| 3870 | ).pipe( |
| 3871 | Effect.onError(() => |
| 3872 | Effect.gen(function* () { |
| 3873 | if (state.activeTurn !== turn) return; |
| 3874 | nativeStreamFailure = makeProviderFailure({ |
| 3875 | message: |
| 3876 | "OpenCode buffered replay failed; reconnect the provider session.", |
| 3877 | class: "transport_error", |
| 3878 | }); |
| 3879 | turn.admissionAbortController?.abort(); |
| 3880 | yield* Deferred.succeed(admissionSettled, undefined); |
| 3881 | yield* updateProviderSession("error", nativeStreamFailure.message); |
| 3882 | yield* cleanupSessionWork(state, abortRootSession(state)).pipe( |
| 3883 | Effect.ignore({ log: true }), |
| 3884 | ); |
| 3885 | yield* finalizeTurn(state, turn, "failed", { |
| 3886 | failure: nativeStreamFailure, |
| 3887 | threadDisposition: "broken", |
| 3888 | }); |
| 3889 | }), |
| 3890 | ), |
| 3891 | ); |
| 3892 | // Stop or a newer turn took the wake first; nothing is left to run. |
| 3893 | if (continuation && wake === null) |
| 3894 | yield* finalizeTurn(state, turn, "completed"); |
| 3895 | }), |
| 3896 | ); |
| 3897 | }), |
| 3898 | ); |
| 3899 | if (continuation) return; |
| 3900 | if (turn.priorWakeSettled !== null) { |
| 3901 | yield* Deferred.await(turn.priorWakeSettled); |
| 3902 | turn.priorWakeSettled = null; |
| 3903 | if (!turnIsLive(state, turn)) { |
| 3904 | yield* Deferred.succeed(admissionSettled, undefined); |
| 3905 | return; |
| 3906 | } |
| 3907 | } |
| 3908 | if (isCompaction) { |
| 3909 | yield* sdkCall( |
| 3910 | "session.summarize", |
| 3911 | { sessionID: sessionId, ...parsedModel, auto: false }, |
| 3912 | (signal) => |
| 3913 | client.session.summarize( |
| 3914 | { sessionID: sessionId, ...parsedModel, auto: false }, |
| 3915 | { signal: AbortSignal.any([signal, admissionAbortController!.signal]) }, |
| 3916 | ), |
| 3917 | ).pipe( |
| 3918 | Effect.tap(() => |
| 3919 | turn.interrupted || |
| 3920 | turn.finalized || |
| 3921 | turn.contextOverflow !== null || |
| 3922 | nativeStreamFailure !== null |
| 3923 | ? Effect.void |
| 3924 | : emitCompactionItem(state, turn), |
| 3925 | ), |
| 3926 | Effect.tap(() => |
| 3927 | finalizeTurn(state, turn, turn.interrupted ? "interrupted" : "completed"), |
| 3928 | ), |
| 3929 | Effect.tapError((cause) => |
| 3930 | finalizeTurn(state, turn, turn.interrupted ? "interrupted" : "failed", { |
| 3931 | failure: makeProviderFailure({ cause, class: "provider_error" }), |
| 3932 | }), |
| 3933 | ), |
| 3934 | Effect.ensuring(Deferred.succeed(admissionSettled, undefined)), |
| 3935 | ); |
| 3936 | return; |
| 3937 | } |
| 3938 | yield* submitPrompt( |
| 3939 | state, |
| 3940 | turn, |
| 3941 | { |
| 3942 | sessionID: sessionId, |
| 3943 | messageID: turn.admissionMessageId!, |
| 3944 | model: parsedModel, |
| 3945 | ...turnPromptOptions(turn), |
| 3946 | parts, |
| 3947 | }, |
| 3948 | admissionAbortController!, |
| 3949 | turnInput.message.text, |
| 3950 | ).pipe( |
| 3951 | Effect.tapError((cause) => |
| 3952 | admissionAbortController!.signal.aborted |
| 3953 | ? Effect.void |
| 3954 | : finalizeTurn(state, turn, "failed", { |
| 3955 | failure: makeProviderFailure({ cause, class: "provider_error" }), |
| 3956 | }), |
| 3957 | ), |
| 3958 | Effect.catch((cause) => |
| 3959 | admissionAbortController!.signal.aborted ? Effect.void : Effect.fail(cause), |
| 3960 | ), |
| 3961 | Effect.ensuring( |
| 3962 | Effect.all([ |
| 3963 | Deferred.succeed(admissionSettled, undefined).pipe(Effect.ignore), |
| 3964 | Effect.sync(() => { |
| 3965 | if (turn.admissionAbortController === admissionAbortController) { |
| 3966 | turn.admissionAbortController = null; |
| 3967 | } |
| 3968 | }), |
| 3969 | ]).pipe(Effect.asVoid), |
| 3970 | ), |
| 3971 | ); |
| 3972 | if (turnIsLive(state, turn)) { |
| 3973 | const admissionAction = advanceOpenCodePromptAdmission(turn, "accepted"); |
| 3974 | if (admissionAction === "reconcile-idle") { |
| 3975 | yield* reconcilePromptAdmission(state, turn); |
| 3976 | } |
| 3977 | } |
| 3978 | }, |
| 3979 | (effect, turnInput) => |
| 3980 | Effect.suspend(() => { |
| 3981 | const state = threads.get(nativeThreadId(turnInput.providerThread)); |
| 3982 | const wake = |
| 3983 | turnInput.message.createdBy === "agent" && |
| 3984 | turnInput.message.creationSource === "provider" |
| 3985 | ? state?.wake |
| 3986 | : null; |
| 3987 | return effect.pipe( |
| 3988 | Effect.onError(() => |
| 3989 | state !== undefined && wake != null ? stopWake(state, wake) : Effect.void, |
| 3990 | ), |
| 3991 | Effect.mapError( |
| 3992 | (cause) => |
| 3993 | new ProviderAdapter.ProviderAdapterTurnStartError({ |
| 3994 | driver: OPENCODE_PROVIDER, |
| 3995 | threadId: turnInput.threadId, |
| 3996 | providerThreadId: turnInput.providerThread.id, |
| 3997 | runId: turnInput.runId, |
| 3998 | cause, |
| 3999 | }), |
| 4000 | ), |
| 4001 | ); |
| 4002 | }), |
| 4003 | ), |
| 4004 | steerTurn: Effect.fn("OpencodeAdapter.steerTurn")( |
| 4005 | function* (steerInput) { |
| 4006 | const sessionId = nativeThreadId(steerInput.providerThread); |
| 4007 | const state = threads.get(sessionId); |
| 4008 | const turn = state?.activeTurn; |
| 4009 | if ( |
| 4010 | state === undefined || |
| 4011 | turn === undefined || |
| 4012 | turn === null || |
| 4013 | turn.providerTurnId !== steerInput.providerTurnId || |
| 4014 | turn.interrupted |
| 4015 | ) { |
| 4016 | return yield* protocolError( |
| 4017 | `OpenCode turn ${steerInput.providerTurnId} is not active`, |
| 4018 | ); |
| 4019 | } |
| 4020 | const parsedModel = OpenCodeRuntime.parseOpenCodeModelSlug(turn.modelSelection.model); |
| 4021 | if (parsedModel === null) { |
| 4022 | return yield* protocolError( |
| 4023 | `OpenCode model '${turn.modelSelection.model}' must use provider/model format`, |
| 4024 | ); |
| 4025 | } |
| 4026 | const text = (yield* providerMessageTextWithAttachmentPaths({ |
| 4027 | text: steerInput.message.text, |
| 4028 | attachments: steerInput.message.attachments, |
| 4029 | resolveAttachmentPath: host.resolveAttachmentPath, |
| 4030 | resolveExtractedTextPath: host.resolveExtractedTextPath, |
| 4031 | })).trim(); |
| 4032 | if (state.activeTurn !== turn || turn.interrupted || turn.finalized) { |
| 4033 | return yield* protocolError( |
| 4034 | `OpenCode turn ${steerInput.providerTurnId} is not active`, |
| 4035 | ); |
| 4036 | } |
| 4037 | const files = OpenCodeRuntime.toOpenCodeFileParts({ |
| 4038 | attachments: steerInput.message.attachments, |
| 4039 | resolveAttachmentPath: host.resolveAttachmentPath, |
| 4040 | }); |
| 4041 | if (text.length === 0 && files.length === 0) { |
| 4042 | return yield* protocolError("OpenCode steering requires text or an attachment"); |
| 4043 | } |
| 4044 | const parts = [ |
| 4045 | ...(text.length === 0 ? [] : [{ type: "text" as const, text }]), |
| 4046 | ...files, |
| 4047 | ]; |
| 4048 | const admissionMessageId = yield* makeOpenCodeMessageId(messageIdClock); |
| 4049 | while (turn.admissionAbortController !== null) { |
| 4050 | const pendingAdmission = turn.admissionSettled; |
| 4051 | yield* Deferred.await(pendingAdmission); |
| 4052 | // Another waiting steer may have claimed admission first. |
| 4053 | if (turn.admissionSettled === pendingAdmission) break; |
| 4054 | } |
| 4055 | if (state.activeTurn !== turn || turn.finalized || turn.interrupted) { |
| 4056 | return yield* protocolError( |
| 4057 | `OpenCode turn ${steerInput.providerTurnId} is not active`, |
| 4058 | ); |
| 4059 | } |
| 4060 | // A retry of a steer whose earlier attempt may have reached OpenCode stays uncertain. |
| 4061 | if (!turn.admissionPending) turn.admissionUncertain = false; |
| 4062 | turn.admissionGeneration = state.nextAdmissionGeneration++; |
| 4063 | turn.admissionMessageId = admissionMessageId; |
| 4064 | turn.admissionPending = true; |
| 4065 | turn.admissionAccepted = false; |
| 4066 | turn.admissionMessageObserved = false; |
| 4067 | turn.idleDuringAdmission = false; |
| 4068 | turn.admissionSettled = Deferred.makeUnsafe<void>(); |
| 4069 | // @effect-diagnostics-next-line abortControllerInEffect:off - Steering replaces the admission request independently of this command fiber. |
| 4070 | turn.admissionAbortController = new AbortController(); |
| 4071 | if (turn.admissionMessageId !== null) |
| 4072 | turn.usage.promptMessageIds.add(turn.admissionMessageId); |
| 4073 | const admissionSettled = turn.admissionSettled; |
| 4074 | const admissionAbortController = turn.admissionAbortController; |
| 4075 | const generation = turn.admissionGeneration; |
| 4076 | const acceptAdmission = Effect.suspend(() => |
| 4077 | state.activeTurn === turn && |
| 4078 | !turn.finalized && |
| 4079 | !turn.interrupted && |
| 4080 | advanceOpenCodePromptAdmission(turn, "accepted") === "reconcile-idle" |
| 4081 | ? reconcilePromptAdmission(state, turn) |
| 4082 | : Effect.void, |
| 4083 | ); |
| 4084 | yield* submitPrompt( |
| 4085 | state, |
| 4086 | turn, |
| 4087 | { |
| 4088 | sessionID: sessionId, |
| 4089 | messageID: turn.admissionMessageId, |
| 4090 | model: parsedModel, |
| 4091 | ...turnPromptOptions(turn), |
| 4092 | parts, |
| 4093 | }, |
| 4094 | admissionAbortController!, |
| 4095 | steerInput.message.text, |
| 4096 | ).pipe( |
| 4097 | Effect.tapError((error) => { |
| 4098 | if (!promptAdmissionIsCurrent(state, turn, generation)) return Effect.void; |
| 4099 | if (isOpenCodePromptRejected(error) && !turn.admissionUncertain) { |
| 4100 | return reconcilePromptAdmission(state, turn); |
| 4101 | } |
| 4102 | // OpenCode may have taken this or an earlier attempt: wait for its output or Stop. |
| 4103 | turn.admissionUncertain = true; |
| 4104 | return acceptAdmission; |
| 4105 | }), |
| 4106 | Effect.ensuring( |
| 4107 | Effect.all([ |
| 4108 | Deferred.succeed(admissionSettled, undefined).pipe(Effect.ignore), |
| 4109 | Effect.sync(() => { |
| 4110 | if (turn.admissionAbortController === admissionAbortController) { |
| 4111 | turn.admissionAbortController = null; |
| 4112 | } |
| 4113 | }), |
| 4114 | ]).pipe(Effect.asVoid), |
| 4115 | ), |
| 4116 | ); |
| 4117 | yield* acceptAdmission; |
| 4118 | }, |
| 4119 | (effect, steerInput) => |
| 4120 | effect.pipe( |
| 4121 | Effect.mapError( |
| 4122 | (cause) => |
| 4123 | new ProviderAdapter.ProviderAdapterSteerRunError({ |
| 4124 | driver: OPENCODE_PROVIDER, |
| 4125 | providerThreadId: steerInput.providerThread.id, |
| 4126 | providerTurnId: steerInput.providerTurnId, |
| 4127 | cause, |
| 4128 | }), |
| 4129 | ), |
| 4130 | ), |
| 4131 | ), |
| 4132 | interruptTurn: Effect.fn("OpencodeAdapter.interruptTurn")( |
| 4133 | function* (interruptInput) { |
| 4134 | const sessionId = nativeThreadId(interruptInput.providerThread); |
| 4135 | const state = threads.get(sessionId); |
| 4136 | if (state === undefined) { |
| 4137 | if (interruptInput.requestRuntimeRestart !== true) |
| 4138 | return yield* protocolError(`OpenCode session ${sessionId} is not registered`); |
| 4139 | for (const controller of commandControllers.get(sessionId) ?? []) |
| 4140 | controller.abort(); |
| 4141 | const descendants = yield* abortDescendants(sessionId).pipe(Effect.result); |
| 4142 | yield* interruptLaunchedSubagents(sessionId); |
| 4143 | if (descendants._tag === "Failure") return yield* descendants.failure; |
| 4144 | return; |
| 4145 | } |
| 4146 | return yield* state.lifecyclePermit.withPermit( |
| 4147 | Effect.gen(function* () { |
| 4148 | const turn = state.activeTurn; |
| 4149 | if ( |
| 4150 | (turn === undefined || turn === null) && |
| 4151 | interruptInput.requestRuntimeRestart === true |
| 4152 | ) { |
| 4153 | for (const controller of commandControllers.get(sessionId) ?? []) |
| 4154 | controller.abort(); |
| 4155 | const wake = state.wake; |
| 4156 | if (wake !== null) yield* cancelWake(state, wake); |
| 4157 | else yield* cleanupSessionWork(state, Effect.void); |
| 4158 | return; |
| 4159 | } |
| 4160 | if ( |
| 4161 | turn === undefined || |
| 4162 | turn === null || |
| 4163 | turn.providerTurnId !== interruptInput.providerTurnId |
| 4164 | ) { |
| 4165 | return yield* protocolError( |
| 4166 | `OpenCode turn ${interruptInput.providerTurnId} is not active`, |
| 4167 | ); |
| 4168 | } |
| 4169 | turn.interrupted = true; |
| 4170 | for (const controller of commandControllers.get(sessionId) ?? []) |
| 4171 | controller.abort(); |
| 4172 | const admissionWasPending = turn.admissionPending; |
| 4173 | cancelOpenCodePromptAdmission(turn, state!.nextAdmissionGeneration++); |
| 4174 | turn.admissionAbortController?.abort(); |
| 4175 | if (turn.priorWakeSettled !== null) |
| 4176 | yield* Deferred.succeed(turn.priorWakeSettled, undefined); |
| 4177 | if (admissionWasPending) { |
| 4178 | // Local admission timeout must not block the server-side abort. |
| 4179 | yield* Deferred.await(turn.admissionSettled).pipe( |
| 4180 | Effect.timeout("10 seconds"), |
| 4181 | Effect.ignore, |
| 4182 | ); |
| 4183 | } |
| 4184 | yield* cleanupSessionWork( |
| 4185 | state, |
| 4186 | sdkCall("session.abort", { sessionID: sessionId }, (signal) => |
| 4187 | client.session.abort({ sessionID: sessionId }, { signal }), |
| 4188 | ).pipe( |
| 4189 | Effect.timeoutOrElse({ |
| 4190 | duration: OPENCODE_STOP_CONFIRM_TIMEOUT_MS, |
| 4191 | orElse: () => |
| 4192 | Effect.fail( |
| 4193 | new ProviderAdapter.ProviderAdapterInterruptTimeoutError({ |
| 4194 | driver: OPENCODE_PROVIDER, |
| 4195 | providerThreadId: interruptInput.providerThread.id, |
| 4196 | providerTurnId: interruptInput.providerTurnId, |
| 4197 | timeoutMs: OPENCODE_STOP_CONFIRM_TIMEOUT_MS, |
| 4198 | }), |
| 4199 | ), |
| 4200 | }), |
| 4201 | Effect.catch((cause) => |
| 4202 | turn.finalized |
| 4203 | ? Effect.void |
| 4204 | : Effect.suspend(() => { |
| 4205 | turn.interrupted = false; |
| 4206 | return Effect.fail(cause); |
| 4207 | }), |
| 4208 | ), |
| 4209 | ), |
| 4210 | ); |
| 4211 | }), |
| 4212 | ); |
| 4213 | }, |
| 4214 | (effect, interruptInput) => |
| 4215 | effect.pipe( |
| 4216 | Effect.mapError((cause) => |
| 4217 | cause._tag === "ProviderAdapterInterruptTimeoutError" |
| 4218 | ? cause |
| 4219 | : new ProviderAdapter.ProviderAdapterInterruptError({ |
| 4220 | driver: OPENCODE_PROVIDER, |
| 4221 | providerThreadId: interruptInput.providerThread.id, |
| 4222 | providerTurnId: interruptInput.providerTurnId, |
| 4223 | cause, |
| 4224 | }), |
| 4225 | ), |
| 4226 | ), |
| 4227 | ), |
| 4228 | respondToRuntimeRequest: Effect.fn("OpencodeAdapter.respondToRuntimeRequest")( |
| 4229 | function* (requestInput) { |
| 4230 | const pending = pendingRequests.get(String(requestInput.requestId)); |
| 4231 | if (pending === undefined) { |
| 4232 | return yield* protocolError( |
| 4233 | `No pending OpenCode request ${requestInput.requestId}`, |
| 4234 | ); |
| 4235 | } |
| 4236 | if (pending.question !== undefined) { |
| 4237 | if (requestInput.answers === undefined) { |
| 4238 | return yield* protocolError( |
| 4239 | `OpenCode question request ${requestInput.requestId} requires answers`, |
| 4240 | ); |
| 4241 | } |
| 4242 | const answers = OpenCodeRuntime.toOpenCodeQuestionAnswers( |
| 4243 | pending.question, |
| 4244 | requestInput.answers, |
| 4245 | ); |
| 4246 | yield* sdkCall( |
| 4247 | "question.reply", |
| 4248 | { requestID: pending.nativeRequestId, answers }, |
| 4249 | (signal) => |
| 4250 | client.question.reply( |
| 4251 | { |
| 4252 | requestID: pending.nativeRequestId, |
| 4253 | answers, |
| 4254 | }, |
| 4255 | { signal }, |
| 4256 | ), |
| 4257 | ).pipe(Effect.timeout("10 seconds")); |
| 4258 | return; |
| 4259 | } |
| 4260 | if (requestInput.decision === undefined) { |
| 4261 | return yield* protocolError( |
| 4262 | `OpenCode approval request ${requestInput.requestId} requires a decision`, |
| 4263 | ); |
| 4264 | } |
| 4265 | const reply = OpenCodeRuntime.toOpenCodePermissionReply(requestInput.decision); |
| 4266 | yield* sdkCall( |
| 4267 | "permission.reply", |
| 4268 | { requestID: pending.nativeRequestId, reply }, |
| 4269 | (signal) => |
| 4270 | client.permission.reply( |
| 4271 | { |
| 4272 | requestID: pending.nativeRequestId, |
| 4273 | reply, |
| 4274 | }, |
| 4275 | { signal }, |
| 4276 | ), |
| 4277 | ).pipe(Effect.timeout("10 seconds")); |
| 4278 | }, |
| 4279 | (effect, requestInput) => |
| 4280 | effect.pipe( |
| 4281 | Effect.mapError( |
| 4282 | (cause) => |
| 4283 | new ProviderAdapter.ProviderAdapterRuntimeRequestResponseError({ |
| 4284 | driver: OPENCODE_PROVIDER, |
| 4285 | requestId: requestInput.requestId, |
| 4286 | cause, |
| 4287 | }), |
| 4288 | ), |
| 4289 | ), |
| 4290 | ), |
| 4291 | readThreadSnapshot: (snapshotInput) => |
| 4292 | readSnapshot(snapshotInput.providerThread).pipe( |
| 4293 | Effect.mapError( |
| 4294 | (cause) => |
| 4295 | new ProviderAdapter.ProviderAdapterReadThreadSnapshotError({ |
| 4296 | driver: OPENCODE_PROVIDER, |
| 4297 | providerThreadId: snapshotInput.providerThread.id, |
| 4298 | cause, |
| 4299 | }), |
| 4300 | ), |
| 4301 | ), |
| 4302 | rollbackThread: Effect.fn("OpencodeAdapter.rollbackThread")( |
| 4303 | function* (rollbackInput) { |
| 4304 | const sessionId = nativeThreadId(rollbackInput.providerThread); |
| 4305 | const state = threads.get(sessionId); |
| 4306 | if (state?.activeTurn !== null && state?.activeTurn !== undefined) { |
| 4307 | return yield* protocolError( |
| 4308 | `Cannot roll back OpenCode thread ${rollbackInput.providerThread.id} while a turn is active`, |
| 4309 | ); |
| 4310 | } |
| 4311 | const response = yield* sdkCall("session.messages", { sessionID: sessionId }, () => |
| 4312 | client.session.messages({ sessionID: sessionId }), |
| 4313 | ); |
| 4314 | const messages = unwrapData("session.messages", response); |
| 4315 | let boundaryMessageId: string | undefined; |
| 4316 | if (rollbackInput.target.type === "thread_start") { |
| 4317 | boundaryMessageId = messages.find(({ info }) => info.role === "user")?.info.id; |
| 4318 | } else { |
| 4319 | boundaryMessageId = openCodeBoundaryAfterProviderTurn( |
| 4320 | rollbackInput.providerThreadTurns, |
| 4321 | rollbackInput.target.providerTurn.id, |
| 4322 | ); |
| 4323 | } |
| 4324 | let retainedThread = rollbackInput.providerThread; |
| 4325 | if (boundaryMessageId !== undefined) { |
| 4326 | const boundaryIndex = messages.findIndex( |
| 4327 | ({ info }) => info.id === boundaryMessageId, |
| 4328 | ); |
| 4329 | if (boundaryIndex < 0) |
| 4330 | return yield* protocolError( |
| 4331 | "The OpenCode rewind boundary is no longer available.", |
| 4332 | ); |
| 4333 | const fork = unwrapData( |
| 4334 | "session.fork", |
| 4335 | yield* sdkCall( |
| 4336 | "session.fork", |
| 4337 | { sessionID: sessionId, messageID: boundaryMessageId }, |
| 4338 | () => |
| 4339 | client.session.fork({ sessionID: sessionId, messageID: boundaryMessageId }), |
| 4340 | ), |
| 4341 | ); |
| 4342 | const retained = unwrapData( |
| 4343 | "session.messages", |
| 4344 | yield* sdkCall("session.messages", { sessionID: fork.id }, () => |
| 4345 | client.session.messages({ sessionID: fork.id }), |
| 4346 | ), |
| 4347 | ); |
| 4348 | if (retained.length !== boundaryIndex) |
| 4349 | return yield* protocolError( |
| 4350 | "OpenCode did not preserve the requested rewind boundary.", |
| 4351 | ); |
| 4352 | yield* sdkCall("session.update", { sessionID: fork.id }, () => |
| 4353 | client.session.update({ |
| 4354 | sessionID: fork.id, |
| 4355 | permission: openCodePermissionRules(input.runtimePolicy), |
| 4356 | }), |
| 4357 | ); |
| 4358 | retainedThread = { |
| 4359 | ...rollbackInput.providerThread, |
| 4360 | nativeThreadRef: providerRef(fork.id), |
| 4361 | }; |
| 4362 | registerThread(fork, retainedThread, state?.appThread ?? null); |
| 4363 | } |
| 4364 | const snapshot = yield* readSnapshot(retainedThread); |
| 4365 | return { |
| 4366 | ...snapshot, |
| 4367 | providerThread: { |
| 4368 | ...snapshot.providerThread, |
| 4369 | nativeConversationHeadRef: |
| 4370 | rollbackInput.target.type === "provider_turn" |
| 4371 | ? rollbackInput.target.providerTurn.nativeTurnRef |
| 4372 | : null, |
| 4373 | }, |
| 4374 | }; |
| 4375 | }, |
| 4376 | (effect, rollbackInput) => |
| 4377 | effect.pipe( |
| 4378 | Effect.mapError( |
| 4379 | (cause) => |
| 4380 | new ProviderAdapter.ProviderAdapterRollbackThreadError({ |
| 4381 | driver: OPENCODE_PROVIDER, |
| 4382 | providerThreadId: rollbackInput.providerThread.id, |
| 4383 | checkpointId: rollbackInput.target.checkpointId, |
| 4384 | cause, |
| 4385 | }), |
| 4386 | ), |
| 4387 | ), |
| 4388 | ), |
| 4389 | forkThread: Effect.fn("OpencodeAdapter.forkThread")( |
| 4390 | function* (forkInput) { |
| 4391 | const sourceSessionId = nativeThreadId(forkInput.sourceProviderThread); |
| 4392 | const sourceState = threads.get(sourceSessionId); |
| 4393 | if (sourceState?.activeTurn !== null && sourceState?.activeTurn !== undefined) { |
| 4394 | return yield* protocolError( |
| 4395 | `Cannot fork OpenCode thread ${forkInput.sourceProviderThread.id} while a turn is active`, |
| 4396 | ); |
| 4397 | } |
| 4398 | let boundaryMessageId: string | undefined; |
| 4399 | if (forkInput.providerTurnId !== undefined) { |
| 4400 | const sourceTurns = forkInput.sourceProviderTurns ?? []; |
| 4401 | const selected = sourceTurns.find((turn) => turn.id === forkInput.providerTurnId); |
| 4402 | if (selected === undefined) { |
| 4403 | return yield* protocolError( |
| 4404 | `OpenCode fork boundary turn ${forkInput.providerTurnId} was not found`, |
| 4405 | ); |
| 4406 | } |
| 4407 | boundaryMessageId = openCodeBoundaryAfterProviderTurn(sourceTurns, selected.id); |
| 4408 | } |
| 4409 | const response = yield* sdkCall( |
| 4410 | "session.fork", |
| 4411 | { |
| 4412 | sessionID: sourceSessionId, |
| 4413 | ...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }), |
| 4414 | }, |
| 4415 | () => |
| 4416 | client.session.fork({ |
| 4417 | sessionID: sourceSessionId, |
| 4418 | ...(boundaryMessageId === undefined ? {} : { messageID: boundaryMessageId }), |
| 4419 | }), |
| 4420 | ); |
| 4421 | const nativeSession = unwrapData("session.fork", response); |
| 4422 | const forkedAt = yield* DateTime.now; |
| 4423 | const providerThread = makeProviderThread({ |
| 4424 | idAllocator, |
| 4425 | providerInstanceId: options.instanceId, |
| 4426 | providerSessionId: input.providerSessionId, |
| 4427 | appThreadId: forkInput.targetThreadId, |
| 4428 | ...(forkInput.ownerNodeId === undefined |
| 4429 | ? {} |
| 4430 | : { ownerNodeId: forkInput.ownerNodeId }), |
| 4431 | nativeSession, |
| 4432 | forkedFrom: { |
| 4433 | providerThreadId: forkInput.sourceProviderThread.id, |
| 4434 | ...(forkInput.providerTurnId === undefined |
| 4435 | ? {} |
| 4436 | : { providerTurnId: forkInput.providerTurnId }), |
| 4437 | }, |
| 4438 | now: forkedAt, |
| 4439 | }); |
| 4440 | registerThread(nativeSession, providerThread, null); |
| 4441 | return providerThread; |
| 4442 | }, |
| 4443 | (effect, forkInput) => |
| 4444 | effect.pipe( |
| 4445 | Effect.mapError( |
| 4446 | (cause) => |
| 4447 | new ProviderAdapter.ProviderAdapterForkThreadError({ |
| 4448 | driver: OPENCODE_PROVIDER, |
| 4449 | providerThreadId: forkInput.sourceProviderThread.id, |
| 4450 | cause, |
| 4451 | }), |
| 4452 | ), |
| 4453 | ), |
| 4454 | ), |
| 4455 | }; |
| 4456 | |
| 4457 | return runtimeSession; |
| 4458 | }, |
| 4459 | (effect, input) => |
| 4460 | effect.pipe( |
| 4461 | Effect.mapError( |
| 4462 | (cause) => |
| 4463 | new ProviderAdapter.ProviderAdapterOpenSessionError({ |
| 4464 | driver: OPENCODE_PROVIDER, |
| 4465 | providerSessionId: input.providerSessionId, |
| 4466 | cause, |
| 4467 | }), |
| 4468 | ), |
| 4469 | ), |
| 4470 | ), |
| 4471 | }); |
| 4472 | }); |
| 4473 | |
| 4474 | export type OpenCodeAdapterV2DriverEnv = |
| 4475 | | OpenCodeRuntime.OpenCodeRuntime |
| 4476 | | IdAllocator.IdAllocatorV2 |
| 4477 | | McpProviderSessions.McpProviderSessions |
| 4478 | | ProviderEventLoggers.ProviderEventLoggers |
| 4479 | | ProviderHost.ProviderHost; |
| 4480 | |
| 4481 | export const OpenCodeAdapterV2Driver: ProviderAdapterDriver< |
| 4482 | OpenCodeSettings, |
| 4483 | OpenCodeAdapterV2DriverEnv |
| 4484 | > = { |
| 4485 | driverKind: OPENCODE_PROVIDER, |
| 4486 | configSchema: OpenCodeSettings, |
| 4487 | defaultConfig: (): OpenCodeSettings => DEFAULT_OPENCODE_SETTINGS, |
| 4488 | create: Effect.fn("OpenCodeAdapterV2Driver.create")( |
| 4489 | function* (input: ProviderAdapterDriverCreateInput<OpenCodeSettings>) { |
| 4490 | const hostEnvironment = yield* HostProcess.Environment; |
| 4491 | const providerEventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers; |
| 4492 | return yield* makeOpenCodeAdapterV2({ |
| 4493 | instanceId: input.instanceId, |
| 4494 | settings: { ...input.config, enabled: input.enabled }, |
| 4495 | environment: yield* mergeProviderInstanceEnvironment(input.environment, hostEnvironment), |
| 4496 | ...(providerEventLoggers.native === undefined |
| 4497 | ? {} |
| 4498 | : { nativeEventLogger: providerEventLoggers.native }), |
| 4499 | }); |
| 4500 | }, |
| 4501 | (effect, input) => |
| 4502 | effect.pipe( |
| 4503 | Effect.mapError( |
| 4504 | (cause) => |
| 4505 | new ProviderAdapterDriverCreateError({ |
| 4506 | driver: OPENCODE_PROVIDER, |
| 4507 | instanceId: input.instanceId, |
| 4508 | detail: "Failed to create OpenCode v2 adapter.", |
| 4509 | cause, |
| 4510 | }), |
| 4511 | ), |
| 4512 | ), |
| 4513 | ), |
| 4514 | }; |