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 * as Path from "effect/Path"; |
| 2 | import * as Option from "effect/Option"; |
| 3 | import * as NodeURL from "node:url"; |
| 4 | |
| 5 | import { |
| 6 | AbsolutePath, |
| 7 | Agent, |
| 8 | Form, |
| 9 | Location, |
| 10 | Model, |
| 11 | Permission, |
| 12 | Provider, |
| 13 | Session, |
| 14 | SessionMessage, |
| 15 | Skill, |
| 16 | type OpenCodeEvent, |
| 17 | } from "@opencode/client/effect"; |
| 18 | import * as Shell from "@opencode/schema/shell"; |
| 19 | import { Mcp } from "@opencode/schema/mcp"; |
| 20 | import { |
| 21 | PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, |
| 22 | isOrchestrationV2WorkActive, |
| 23 | parseGoalCommand, |
| 24 | type ChatAttachment, |
| 25 | type OrchestrationV2AppThread, |
| 26 | type OrchestrationV2ConversationMessage, |
| 27 | type OrchestrationV2ExecutionNode, |
| 28 | type OrchestrationV2ProviderCapabilities, |
| 29 | type OrchestrationV2ProviderFailure, |
| 30 | type OrchestrationV2ProviderRetry, |
| 31 | type OrchestrationV2ProviderSession, |
| 32 | type OrchestrationV2ProviderThread, |
| 33 | type OrchestrationV2ProviderTurn, |
| 34 | type OrchestrationV2PlanStep, |
| 35 | type OrchestrationV2RuntimeRequest, |
| 36 | type OrchestrationV2Subagent, |
| 37 | type OrchestrationV2TurnItem, |
| 38 | type OrchestrationV2UserInputQuestion, |
| 39 | type MessageId, |
| 40 | type ModelSelection, |
| 41 | type PlanId, |
| 42 | type ProviderApprovalDecision, |
| 43 | type ProviderInstanceId, |
| 44 | type RunId, |
| 45 | type RuntimeRequestId, |
| 46 | } from "@t3tools/contracts"; |
| 47 | import type * as Cause from "effect/Cause"; |
| 48 | import * as DateTime from "effect/DateTime"; |
| 49 | import * as Deferred from "effect/Deferred"; |
| 50 | import * as Digest from "effect/crypto/Digest"; |
| 51 | import * as Duration from "effect/Duration"; |
| 52 | import * as Effect from "effect/Effect"; |
| 53 | import * as Hex from "effect/encoding/Hex"; |
| 54 | import * as Exit from "effect/Exit"; |
| 55 | import * as P from "effect/Predicate"; |
| 56 | import * as FileSystem from "effect/FileSystem"; |
| 57 | import * as Queue from "effect/Queue"; |
| 58 | import * as Schedule from "effect/Schedule"; |
| 59 | import * as Scope from "effect/Scope"; |
| 60 | import * as Schema from "effect/Schema"; |
| 61 | import * as Semaphore from "effect/Semaphore"; |
| 62 | import * as Stream from "effect/Stream"; |
| 63 | |
| 64 | import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost"; |
| 65 | import * as OpenCode2Client from "./OpenCode2Client.ts"; |
| 66 | import * as OpenCode2Server from "./OpenCode2Server.ts"; |
| 67 | import * as OpenCodeRuntime from "../OpenCodeRuntime.ts"; |
| 68 | import { readableProviderErrorMessage } from "../providerErrorMessage.ts"; |
| 69 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 70 | import { buildRuntimeInstructions } from "@t3tools/provider-core/server/runtimeInstructions"; |
| 71 | import { t3OrchestrationSystemPrompt } from "@t3tools/provider-core/server/orchestrationInstructions"; |
| 72 | import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; |
| 73 | import { HTML_RENDER_TOOL_NAME } from "@t3tools/shared/htmlRender"; |
| 74 | import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; |
| 75 | import { compareSemverVersions } from "@t3tools/shared/semver"; |
| 76 | import * as KeyedLock from "@t3tools/shared/KeyedLock"; |
| 77 | import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model"; |
| 78 | import { causeErrorTag } from "@t3tools/shared/observability"; |
| 79 | |
| 80 | import { |
| 81 | isProviderNativeImageAttachment, |
| 82 | providerMessageTextWithAttachmentPaths, |
| 83 | } from "@t3tools/provider-core/server/attachmentPrompt"; |
| 84 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 85 | import { |
| 86 | backgroundWorkNotification, |
| 87 | type BackgroundWorkReport, |
| 88 | } from "@t3tools/provider-core/server/notification"; |
| 89 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 90 | import { |
| 91 | makeProviderFailure, |
| 92 | makeProviderRetryTurnItem, |
| 93 | } from "@t3tools/provider-core/server/failure"; |
| 94 | import { |
| 95 | makeSubagentChildThread, |
| 96 | makeSubagentConversationArtifacts, |
| 97 | subagentThreadTitle, |
| 98 | } from "@t3tools/provider-core/server/subagentProjection"; |
| 99 | import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 100 | import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition"; |
| 101 | import { OPENCODE_PROVIDER, openCodePermissionRequestKind } from "../adapter.ts"; |
| 102 | import { |
| 103 | openCodeCodeModeHtmlRenders, |
| 104 | openCodeCommandFailed, |
| 105 | openCodeToolTurnItem, |
| 106 | } from "../toolItems.ts"; |
| 107 | |
| 108 | const NativeGoal = Schema.NullOr( |
| 109 | Schema.Struct({ |
| 110 | objective: Schema.NonEmptyString, |
| 111 | status: Schema.Literals(["active", "paused", "complete"]), |
| 112 | rounds: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)), |
| 113 | reason: Schema.optional(Schema.String), |
| 114 | }), |
| 115 | ); |
| 116 | const decodeGoal = Schema.decodeUnknownEffect(NativeGoal); |
| 117 | |
| 118 | const NativeTodoList = Schema.Struct({ |
| 119 | todos: Schema.Array( |
| 120 | Schema.Struct({ |
| 121 | content: Schema.String, |
| 122 | status: Schema.Literals(["pending", "in_progress", "completed", "cancelled"]), |
| 123 | }), |
| 124 | ), |
| 125 | }); |
| 126 | const isNativeTodoList = Schema.is(NativeTodoList); |
| 127 | |
| 128 | const OpenCode2ProviderCapabilities = { |
| 129 | sessions: { |
| 130 | supportsMultipleProviderThreadsPerSession: true, |
| 131 | supportsModelSwitchInSession: true, |
| 132 | supportsProviderSwitchingViaHandoff: true, |
| 133 | supportsRuntimeModeSwitchInSession: true, |
| 134 | pendingRequestsSurviveRestart: false, |
| 135 | }, |
| 136 | threads: { |
| 137 | canCreateEmptyThread: true, |
| 138 | canReadThreadSnapshot: true, |
| 139 | canRollbackThread: true, |
| 140 | canForkThread: true, |
| 141 | canForkFromTurn: true, |
| 142 | canForkFromSubagentThread: false, |
| 143 | exposesNativeThreadId: true, |
| 144 | }, |
| 145 | turns: { |
| 146 | exposesNativeTurnId: false, |
| 147 | emitsTurnStarted: true, |
| 148 | emitsTurnCompleted: true, |
| 149 | supportsInterrupt: true, |
| 150 | supportsNativeResume: true, |
| 151 | supportsActiveSteering: true, |
| 152 | supportsSteeringByInterruptRestart: true, |
| 153 | supportsQueuedMessages: true, |
| 154 | terminalStatusQuality: "strong", |
| 155 | }, |
| 156 | streaming: { |
| 157 | streamsAssistantText: true, |
| 158 | streamsReasoning: true, |
| 159 | streamsToolOutput: false, |
| 160 | streamsPlanText: false, |
| 161 | emitsMessageCompleted: true, |
| 162 | }, |
| 163 | tools: { |
| 164 | exposesToolItemIds: true, |
| 165 | emitsToolStarted: true, |
| 166 | emitsToolCompleted: true, |
| 167 | emitsToolOutput: true, |
| 168 | supportsMcpTools: false, |
| 169 | supportsDynamicToolCallbacks: false, |
| 170 | supportsBackgroundWait: true, |
| 171 | }, |
| 172 | approvals: { |
| 173 | supportsCommandApproval: true, |
| 174 | supportsFileReadApproval: true, |
| 175 | supportsFileChangeApproval: true, |
| 176 | supportsApplyPatchApproval: true, |
| 177 | approvalsHaveNativeRequestIds: true, |
| 178 | approvalCallbacksAreLiveOnly: true, |
| 179 | approvalsCanOriginateFromSubagents: true, |
| 180 | }, |
| 181 | planning: { |
| 182 | emitsPlanUpdated: true, |
| 183 | emitsTodoList: true, |
| 184 | emitsProposedPlan: false, |
| 185 | supportsStructuredQuestions: true, |
| 186 | planDeltasHaveItemIds: false, |
| 187 | }, |
| 188 | subagents: { |
| 189 | supportsSubagents: true, |
| 190 | exposesSubagentThreadIds: true, |
| 191 | emitsSubagentLifecycle: true, |
| 192 | canWaitForSubagents: true, |
| 193 | canCloseSubagents: false, |
| 194 | canForkSubagentThread: false, |
| 195 | }, |
| 196 | context: { |
| 197 | acceptsSystemContext: false, |
| 198 | acceptsDeveloperContext: false, |
| 199 | acceptsSyntheticUserContext: true, |
| 200 | canGenerateSummaries: false, |
| 201 | canConsumeHandoffSummaries: true, |
| 202 | supportsDeltaHandoff: true, |
| 203 | supportsFullThreadHandoff: true, |
| 204 | maxRecommendedHandoffChars: null, |
| 205 | }, |
| 206 | checkpointing: { |
| 207 | appCanCheckpointFilesystem: true, |
| 208 | supportsNestedCheckpointScopes: true, |
| 209 | providerCanRollbackConversation: true, |
| 210 | providerRollbackReturnsSnapshot: true, |
| 211 | providerCanReadConversationSnapshot: true, |
| 212 | }, |
| 213 | identity: { |
| 214 | nativeThreadIds: "strong", |
| 215 | nativeTurnIds: "weak", |
| 216 | nativeItemIds: "strong", |
| 217 | nativeRequestIds: "strong", |
| 218 | }, |
| 219 | runtimePolicy: { enforcement: "native" }, |
| 220 | } satisfies OrchestrationV2ProviderCapabilities; |
| 221 | |
| 222 | type EventOf<T extends OpenCodeEvent["type"]> = Extract<OpenCodeEvent, { readonly type: T }>; |
| 223 | type Tokens = EventOf<"session.step.ended">["data"]["tokens"]; |
| 224 | |
| 225 | interface TurnOwner { |
| 226 | readonly appThread: OrchestrationV2AppThread; |
| 227 | readonly threadId: OrchestrationV2AppThread["id"]; |
| 228 | readonly runId: RunId | null; |
| 229 | readonly runOrdinal: number; |
| 230 | readonly rootNodeId: ProviderAdapter.ProviderAdapterV2TurnInput["rootNodeId"]; |
| 231 | readonly modelSelection: ModelSelection; |
| 232 | readonly runtimePolicy: Pick<ProviderAdapter.ProviderAdapterV2RuntimePolicy, "cwd">; |
| 233 | } |
| 234 | |
| 235 | interface ActiveTurn { |
| 236 | readonly input: TurnOwner; |
| 237 | providerTurn: OrchestrationV2ProviderTurn; |
| 238 | readonly texts: Map<string, OpenBlock>; |
| 239 | /** The last assistant text this turn completed. */ |
| 240 | answer: string | undefined; |
| 241 | /** The completed text no tool has followed yet, which ends the turn unless a steer lands. */ |
| 242 | closingText: OpenBlock | undefined; |
| 243 | readonly tools: Map<string, { readonly name: string; input: Record<string, unknown> }>; |
| 244 | readonly startedAt: Map<string, DateTime.Utc>; |
| 245 | readonly ordinals: Map<string, number>; |
| 246 | nextOrdinal: number; |
| 247 | readonly usage: { |
| 248 | input: number; |
| 249 | cached: number; |
| 250 | cacheWrite: number; |
| 251 | output: number; |
| 252 | reasoning: number; |
| 253 | }; |
| 254 | // Steps OpenCode started; a step that ends without tokens leaves the total partial. |
| 255 | startedSteps: number; |
| 256 | // A reconnect dropped events, so steps may have ended unseen. |
| 257 | missedEvents: boolean; |
| 258 | steps: number; |
| 259 | readonly models: Set<string>; |
| 260 | lastStep: Tokens | undefined; |
| 261 | before: string | null | undefined; |
| 262 | compaction: { readonly nativeId: string; readonly startedAt: DateTime.Utc } | undefined; |
| 263 | compactions: number; |
| 264 | todoPlanId: PlanId | undefined; |
| 265 | retry: |
| 266 | | { |
| 267 | readonly retry: OrchestrationV2ProviderRetry; |
| 268 | readonly failure: OrchestrationV2ProviderFailure; |
| 269 | readonly startedAt: DateTime.Utc; |
| 270 | } |
| 271 | | undefined; |
| 272 | interrupted: boolean; |
| 273 | unsent: boolean; |
| 274 | readonly steers: Set<string>; |
| 275 | readonly settledInbox: Set<string>; |
| 276 | // Reconnects replay finished tools, so each nested html_render takes a page only once. |
| 277 | readonly takenPages: Set<string>; |
| 278 | heldEnd: TurnTerminal | undefined; |
| 279 | awaitingStart: boolean; |
| 280 | /** Scope child tool IDs because model-generated IDs can repeat parent IDs. */ |
| 281 | readonly scope: string; |
| 282 | usedSubagents: boolean; |
| 283 | } |
| 284 | |
| 285 | interface SubagentCall { |
| 286 | readonly toolId: string; |
| 287 | readonly nativeId: string; |
| 288 | readonly state: ThreadState; |
| 289 | readonly turn: ActiveTurn; |
| 290 | readonly ordinal: number; |
| 291 | readonly startedAt: DateTime.Utc; |
| 292 | prompt: string; |
| 293 | title: string | null; |
| 294 | agent: string | undefined; |
| 295 | model: string | null; |
| 296 | background: boolean; |
| 297 | /** The child's turn this call prompted or steered; unset until that turn starts. */ |
| 298 | run: number | undefined; |
| 299 | /** That turn's last text once it ended, which OpenCode sends as the run's report. */ |
| 300 | answer: string | undefined; |
| 301 | child: ThreadState | undefined; |
| 302 | status: OrchestrationV2Subagent["status"]; |
| 303 | result: string | null; |
| 304 | completedAt: DateTime.Utc | null; |
| 305 | } |
| 306 | |
| 307 | interface Wake { |
| 308 | readonly messageId: MessageId | undefined; |
| 309 | readonly events: Array<OpenCode2Client.OpenCode2StreamEvent>; |
| 310 | running: boolean; |
| 311 | readonly reports: Array<BackgroundWorkReport>; |
| 312 | readonly detail: string | null; |
| 313 | dropped: boolean; |
| 314 | readonly after: string | undefined; |
| 315 | readonly first: string | undefined; |
| 316 | readonly children: Set<string>; |
| 317 | readonly awaited: Set<string>; |
| 318 | /** Held shell launches whose end report arrived first; the report already cleared their status. */ |
| 319 | readonly ended: Map< |
| 320 | string, |
| 321 | { readonly status: "completed" | "failed" | "interrupted"; readonly exit?: number } |
| 322 | >; |
| 323 | } |
| 324 | |
| 325 | interface OpenBlock { |
| 326 | readonly block: { readonly assistantMessageID: string; readonly ordinal: number }; |
| 327 | readonly kind: "text" | "reasoning"; |
| 328 | readonly startedAt: DateTime.Utc; |
| 329 | text: string; |
| 330 | } |
| 331 | |
| 332 | interface ThreadState { |
| 333 | readonly sessionId: string; |
| 334 | providerThread: OrchestrationV2ProviderThread; |
| 335 | publishedBackgroundWork?: boolean; |
| 336 | sessionScopedBackground?: boolean; |
| 337 | readonly imageJobs: Map< |
| 338 | string, |
| 339 | { |
| 340 | readonly turn: ActiveTurn; |
| 341 | readonly toolId: string; |
| 342 | readonly tool: { readonly name: string; input: Record<string, unknown> }; |
| 343 | previewed: boolean; |
| 344 | readonly path: string; |
| 345 | readonly model: string; |
| 346 | status: "running" | "completed" | "error" | "cancelled"; |
| 347 | } |
| 348 | >; |
| 349 | goalRevision: number; |
| 350 | goalFresh: boolean; |
| 351 | goalRefreshing: boolean; |
| 352 | readonly providerTurns: Map<string, OrchestrationV2ProviderTurn>; |
| 353 | active: ActiveTurn | undefined; |
| 354 | model: ModelRef | undefined; |
| 355 | /** Locally ended but possibly live; consume its next execution end without settling a new turn. */ |
| 356 | unsettled: boolean; |
| 357 | /** A late first start belongs to the failed prompt; only a subsequent start proves a lost end. */ |
| 358 | unsettledStarted: boolean; |
| 359 | /** Execution starts seen; lets a check that awaited OpenCode notice a run that began meanwhile. */ |
| 360 | starts: number; |
| 361 | directory: string; |
| 362 | agent: string; |
| 363 | title: string | undefined; |
| 364 | rules: ReadonlyArray<Rule> | undefined; |
| 365 | policy: RulesPolicy; |
| 366 | readonly grants: Array<Rule>; |
| 367 | readonly calls: Map<string, SubagentCall>; |
| 368 | subagent: |
| 369 | | { |
| 370 | call: SubagentCall; |
| 371 | readonly appThread: OrchestrationV2AppThread; |
| 372 | turns: number; |
| 373 | prompt: string | undefined; |
| 374 | queued: string | undefined; |
| 375 | } |
| 376 | | undefined; |
| 377 | readonly wakes: Array<Wake>; |
| 378 | readonly reports: Map< |
| 379 | string, |
| 380 | { |
| 381 | readonly inboxId: string; |
| 382 | readonly childId: string; |
| 383 | readonly report: BackgroundWorkReport; |
| 384 | readonly text: string; |
| 385 | } |
| 386 | >; |
| 387 | readonly stoppedChildren: Set<string>; |
| 388 | readonly strandedSteers: Set<string>; |
| 389 | /** Prompts other clients queued while no T3 turn ran, shown once delivered; `leads` the next wake if no report preceded it. */ |
| 390 | readonly externalPrompts: Map<string, { readonly text: string; leads: boolean }>; |
| 391 | mcp: |
| 392 | | { readonly name: string; readonly directory: string; readonly credential: string } |
| 393 | | undefined; |
| 394 | instructions: string | undefined; |
| 395 | } |
| 396 | |
| 397 | type TurnTerminal = |
| 398 | | { readonly status: "completed" | "interrupted" } |
| 399 | | { readonly status: "failed"; readonly failure: ReturnType<typeof makeProviderFailure> }; |
| 400 | |
| 401 | type Rule = Permission.Rule; |
| 402 | type RulesPolicy = Pick< |
| 403 | ProviderAdapter.ProviderAdapterV2RuntimePolicy, |
| 404 | "runtimeMode" | "interactionMode" |
| 405 | >; |
| 406 | type NativeForm = EventOf<"form.created">["data"]["form"]; |
| 407 | |
| 408 | interface PendingRequest { |
| 409 | readonly request: OrchestrationV2RuntimeRequest; |
| 410 | readonly item: OrchestrationV2TurnItem; |
| 411 | readonly node: OrchestrationV2ExecutionNode; |
| 412 | readonly state: ThreadState; |
| 413 | readonly turn: ActiveTurn; |
| 414 | readonly sessionId: string; |
| 415 | answering: boolean; |
| 416 | readonly native: |
| 417 | | { |
| 418 | readonly type: "permission"; |
| 419 | readonly id: string; |
| 420 | readonly action: string; |
| 421 | readonly resources: ReadonlyArray<string>; |
| 422 | readonly save: ReadonlyArray<string>; |
| 423 | } |
| 424 | | { readonly type: "form"; readonly id: string; readonly form: NativeForm }; |
| 425 | } |
| 426 | |
| 427 | const rule = (action: string, effect: Rule["effect"]): Rule => ({ action, resource: "*", effect }); |
| 428 | |
| 429 | /** OpenCode hides tools for names over 64 chars and rejects names over 100; hash long thread IDs. */ |
| 430 | export const t3McpServerName = Effect.fn("t3McpServerName")(function* (threadId: string) { |
| 431 | const name = `t3-code-${threadId.replaceAll(/[^a-zA-Z0-9_-]/g, "_")}`; |
| 432 | if (name.length <= 64) return name; |
| 433 | const crypto = yield* Digest.Digest; |
| 434 | const digest = yield* crypto |
| 435 | .digest(Digest.sha256, new TextEncoder().encode(threadId)) |
| 436 | .pipe(Effect.orDie); |
| 437 | return `t3-code-${Hex.encode(digest).slice(0, 16)}`; |
| 438 | }); |
| 439 | |
| 440 | // Last match wins: deny all threads' T3 servers, then allow only this thread's. |
| 441 | const mcpRules = (mcpServerName: string | null): ReadonlyArray<Rule> => |
| 442 | mcpServerName === null |
| 443 | ? [] |
| 444 | : [ |
| 445 | { action: "t3-code-*", resource: "*", effect: "deny" }, |
| 446 | { action: `${mcpServerName}_*`, resource: "*", effect: "allow" }, |
| 447 | ]; |
| 448 | |
| 449 | const sessionRules = ( |
| 450 | policy: RulesPolicy, |
| 451 | paths: ReadonlyArray<Rule>, |
| 452 | grants: ReadonlyArray<Rule>, |
| 453 | mcpServerName: string | null, |
| 454 | ): ReadonlyArray<Rule> => [ |
| 455 | ...(policy.runtimeMode === "full-access" |
| 456 | ? [rule("*", "allow")] |
| 457 | : [ |
| 458 | rule("shell", "ask"), |
| 459 | rule("edit", policy.runtimeMode === "auto-accept-edits" ? "allow" : "ask"), |
| 460 | rule("external_directory", "ask"), |
| 461 | ]), |
| 462 | ...grants, |
| 463 | // Plan edits are re-allowed only for plan paths; free-tier sessions refuse denied shell/read. |
| 464 | ...(policy.interactionMode === "plan" ? [rule("edit", "deny")] : []), |
| 465 | ...paths, |
| 466 | ...mcpRules(mcpServerName), |
| 467 | ]; |
| 468 | |
| 469 | const sameRules = (left: ReadonlyArray<Rule> | undefined, right: ReadonlyArray<Rule>) => |
| 470 | left?.length === right.length && |
| 471 | left.every( |
| 472 | (entry, index) => |
| 473 | entry.action === right[index]?.action && |
| 474 | entry.resource === right[index]?.resource && |
| 475 | entry.effect === right[index]?.effect, |
| 476 | ); |
| 477 | |
| 478 | // Rejection without a message stops the whole execution, meaning Cancel. |
| 479 | const DECLINED = "The user declined this request."; |
| 480 | const DISMISSED = "The user dismissed this question. Continue without an answer."; |
| 481 | |
| 482 | // Steer before decline; otherwise the model sees only Unable to execute command and retries. |
| 483 | const declinedNote = (action: string, resources: ReadonlyArray<string>) => |
| 484 | `The user declined the ${action} request${resources.length === 0 ? "" : ` (${resources.join(", ")})`}. Do not retry it; continue without it or ask the user how to proceed.`; |
| 485 | |
| 486 | const sessionGrantLabel = (action: string, save: ReadonlyArray<string>) => |
| 487 | save.every((pattern) => pattern === "*") |
| 488 | ? `Allow every ${action} request this session` |
| 489 | : `Allow ${save.join(", ")} this session`; |
| 490 | |
| 491 | const text = (value: string | undefined, fallback: string) => value?.trim() || fallback; |
| 492 | |
| 493 | const formQuestions = ( |
| 494 | form: NativeForm, |
| 495 | ): |
| 496 | | { readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion> } |
| 497 | | { readonly unsupported: string } => { |
| 498 | const questions: Array<OrchestrationV2UserInputQuestion> = []; |
| 499 | for (const [index, field] of form.fields.entries()) { |
| 500 | if (field.type === "external") return { unsupported: "a link to open" }; |
| 501 | if (field.type !== "string" && field.type !== "multiselect") { |
| 502 | return { unsupported: `a ${field.type} value` }; |
| 503 | } |
| 504 | if (field.hidden === true) return { unsupported: "a hidden field" }; |
| 505 | if ((field.when?.length ?? 0) > 0) return { unsupported: "a field that depends on another" }; |
| 506 | const header = text(field.title, `Question ${index + 1}`); |
| 507 | const options = (field.options ?? []).map((option) => { |
| 508 | const label = text(option.label, text(option.value, "Option")); |
| 509 | return { label, description: text(option.description, label), value: option.value }; |
| 510 | }); |
| 511 | questions.push({ |
| 512 | id: field.key, |
| 513 | header, |
| 514 | question: text(field.description, header), |
| 515 | options, |
| 516 | multiSelect: field.type === "multiselect", |
| 517 | allowCustomAnswer: field.custom === true || options.length === 0, |
| 518 | }); |
| 519 | } |
| 520 | return { questions }; |
| 521 | }; |
| 522 | |
| 523 | const formAnswer = (form: NativeForm, answers: Readonly<Record<string, unknown>>) => { |
| 524 | const answer: Record<string, string | ReadonlyArray<string>> = {}; |
| 525 | for (const field of form.fields) { |
| 526 | const raw = answers[field.key]; |
| 527 | const values = (Array.isArray(raw) ? raw : [raw]).filter( |
| 528 | (value): value is string => typeof value === "string" && value.trim().length > 0, |
| 529 | ); |
| 530 | if (values.length > 0) { |
| 531 | answer[field.key] = field.type === "multiselect" ? values : values.join(", "); |
| 532 | } |
| 533 | } |
| 534 | return answer; |
| 535 | }; |
| 536 | |
| 537 | const approves = (decision: ProviderApprovalDecision) => |
| 538 | decision === "accept" || decision === "acceptForSession" || decision === "acceptAlways"; |
| 539 | |
| 540 | const permissionGone = { |
| 541 | PermissionNotFoundError: () => Effect.void, |
| 542 | SessionNotFoundError: () => Effect.void, |
| 543 | }; |
| 544 | const formGone = { |
| 545 | FormNotFoundError: () => Effect.void, |
| 546 | FormAlreadySettledError: () => Effect.void, |
| 547 | SessionNotFoundError: () => Effect.void, |
| 548 | }; |
| 549 | |
| 550 | const agentPaths = (rules: ReadonlyArray<Rule>) => |
| 551 | rules.filter( |
| 552 | (entry) => |
| 553 | entry.effect === "allow" && |
| 554 | entry.resource !== "*" && |
| 555 | (entry.action === "edit" || entry.action === "external_directory"), |
| 556 | ); |
| 557 | |
| 558 | const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({ |
| 559 | driver: OPENCODE_PROVIDER, |
| 560 | nativeId, |
| 561 | strength, |
| 562 | }); |
| 563 | |
| 564 | const sessionIdOf = (providerThread: OrchestrationV2ProviderThread) => { |
| 565 | const nativeId = providerThread.nativeThreadRef?.nativeId; |
| 566 | return nativeId === undefined || nativeId === null |
| 567 | ? Effect.fail( |
| 568 | new ProviderAdapter.ProviderAdapterProtocolError({ |
| 569 | driver: OPENCODE_PROVIDER, |
| 570 | detail: `Provider thread ${providerThread.id} has no OpenCode session`, |
| 571 | }), |
| 572 | ) |
| 573 | : Effect.succeed(nativeId); |
| 574 | }; |
| 575 | |
| 576 | const textOf = (content: ReadonlyArray<{ readonly type: string; readonly text?: string }>) => |
| 577 | content.flatMap((part) => (part.type === "text" && part.text ? [part.text] : [])).join("\n"); |
| 578 | |
| 579 | const stringField = (record: unknown, key: string) => { |
| 580 | const value = |
| 581 | typeof record === "object" && record !== null && key in record |
| 582 | ? Reflect.get(record, key) |
| 583 | : undefined; |
| 584 | return typeof value === "string" && value.trim().length > 0 ? value : undefined; |
| 585 | }; |
| 586 | |
| 587 | const reportOutcome = (state: string | undefined) => |
| 588 | state === "completed" |
| 589 | ? ("completed" as const) |
| 590 | : state === "error" |
| 591 | ? ("failed" as const) |
| 592 | : state === "cancelled" |
| 593 | ? ("cancelled" as const) |
| 594 | : ("unknown" as const); |
| 595 | |
| 596 | const subagentOutput = (text: string) => |
| 597 | /^<subagent\b[^>]*>\n?([\s\S]*?)\n?<\/subagent>$/.exec(text.trim())?.[1] ?? text; |
| 598 | |
| 599 | const isContinuation = (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) => |
| 600 | turnInput.message.createdBy === "agent" && turnInput.message.creationSource === "provider"; |
| 601 | |
| 602 | const wakeTurnId = (sessionId: string, attemptId: string) => `${sessionId}:wake:${attemptId}`; |
| 603 | const isWakeTurn = (turn: OrchestrationV2ProviderTurn) => |
| 604 | turn.nativeTurnRef?.nativeId?.includes(":wake:") === true; |
| 605 | |
| 606 | // OpenCode's claude-agent reports a spent Claude plan as provider.unknown with Claude's own text. |
| 607 | const claudeUsageLimit = (message: string | undefined) => |
| 608 | message !== undefined && /^You've hit your [^\n·]*\blimit\b/.test(message) |
| 609 | ? { resetAt: /\bResets at (\d{4}-\d\d-\d\dT[\d:.]+Z)\.?\s*$/.exec(message)?.[1] ?? null } |
| 610 | : undefined; |
| 611 | |
| 612 | // OpenCode types an empty balance as provider.quota too, but it answers |
| 613 | // that with HTTP 402 and it never resets. Usage windows and budgets are 429. |
| 614 | const isUsageLimit = (error: { |
| 615 | readonly type: string; |
| 616 | readonly status?: number | undefined; |
| 617 | readonly message: string; |
| 618 | }) => |
| 619 | (error.type === "provider.quota" && error.status !== 402) || |
| 620 | error.type === "provider.rate-limit" || |
| 621 | claudeUsageLimit(error.message) !== undefined; |
| 622 | |
| 623 | const INTERRUPT_TIMEOUT = 10_000; |
| 624 | const INSTRUCTIONS_KEY = "t3-code"; |
| 625 | const RECONNECT_ATTEMPTS = 5; |
| 626 | const RECONNECT_DELAY = "2 seconds"; |
| 627 | const RECONCILE_TIMEOUT = "15 seconds"; |
| 628 | const RECONNECT_WAIT = "30 seconds"; |
| 629 | const OWNED_RECONNECT_SCHEDULE = Schedule.exponential(RECONNECT_DELAY).pipe( |
| 630 | Schedule.modifyDelay(({ duration }) => |
| 631 | Effect.succeed(Duration.min(duration, Duration.seconds(30))), |
| 632 | ), |
| 633 | ); |
| 634 | const TRANSIENT_HTTP_STATUSES: ReadonlySet<number> = new Set([408, 425, 429]); |
| 635 | // A live owned server is retried until it answers; these failures repeat however long it waits. |
| 636 | const isPermanentRecoveryError = (error: unknown) => { |
| 637 | if (Schema.isSchemaError(error)) return true; |
| 638 | if ( |
| 639 | P.isTagged(error, "UnauthorizedError") || |
| 640 | P.isTagged(error, "InvalidRequestError") || |
| 641 | P.isTagged(error, "InvalidCursorError") |
| 642 | ) { |
| 643 | return true; |
| 644 | } |
| 645 | const http = OpenCode2Server.httpFailureOf(error); |
| 646 | if (http !== undefined) { |
| 647 | const status = http.response?.status; |
| 648 | return ( |
| 649 | status !== undefined && status >= 400 && status < 500 && !TRANSIENT_HTTP_STATUSES.has(status) |
| 650 | ); |
| 651 | } |
| 652 | // ClientError also wraps an SSE retry request, which clears. |
| 653 | return ( |
| 654 | P.isTagged(error, "ClientError") && |
| 655 | P.hasProperty(error, "cause") && |
| 656 | Schema.isSchemaError(error.cause) |
| 657 | ); |
| 658 | }; |
| 659 | const OWNED_RECOVERY_RETRY = { |
| 660 | schedule: OWNED_RECONNECT_SCHEDULE, |
| 661 | while: (error: unknown) => !isPermanentRecoveryError(error), |
| 662 | }; |
| 663 | // Retries an owned server's request until it answers or the process exits. |
| 664 | const whileAlive = <A, E, R>( |
| 665 | processExit: Effect.Effect<unknown> | undefined, |
| 666 | effect: Effect.Effect<A, E, R>, |
| 667 | ) => |
| 668 | processExit === undefined |
| 669 | ? effect |
| 670 | : effect.pipe( |
| 671 | Effect.retry(OWNED_RECOVERY_RETRY), |
| 672 | Effect.raceFirst( |
| 673 | processExit.pipe(Effect.andThen(Effect.fail(new OpenCode2ServerExitedError()))), |
| 674 | ), |
| 675 | ); |
| 676 | class OpenCode2ServerExitedError extends Schema.TaggedError<OpenCode2ServerExitedError>()( |
| 677 | "OpenCode2ServerExitedError", |
| 678 | {}, |
| 679 | ) {} |
| 680 | const LOST_BACKGROUND = |
| 681 | "T3 Code lost its connection to OpenCode while this subagent ran, so its result is not shown."; |
| 682 | const INVENTORY_TIMEOUT = "5 seconds"; |
| 683 | const MCP_TOOL_RELOAD_SETTLE = "250 millis"; |
| 684 | const ACTIVE_CHECK_TIMEOUT = "5 seconds"; |
| 685 | // Other failures may still have admitted the prompt. |
| 686 | const CLEAR_PROMPT_REJECTIONS: ReadonlySet<string> = new Set([ |
| 687 | "InvalidRequestError", |
| 688 | "ConflictError", |
| 689 | "UnauthorizedError", |
| 690 | "CommandNotFoundError", |
| 691 | "SkillNotFoundError", |
| 692 | ]); |
| 693 | |
| 694 | export const OPENCODE_2_STILL_STOPPING = |
| 695 | "OpenCode is still stopping the previous turn. Send the message again in a moment."; |
| 696 | const REQUEST_REPLY_TIMEOUT = "10 seconds"; |
| 697 | |
| 698 | const deliver = <E>(answer: Effect.Effect<void, E>) => |
| 699 | answer.pipe( |
| 700 | Effect.retry({ times: 1 }), |
| 701 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 702 | Effect.exit, |
| 703 | Effect.map(Exit.isSuccess), |
| 704 | ); |
| 705 | |
| 706 | type ModelRef = ReturnType<typeof Model.Ref.make>; |
| 707 | |
| 708 | // msg_ IDs cannot cross sessions; include session identity because T3 IDs repeat across environments. |
| 709 | // Pre-acknowledgement IDs also establish fork/rollback boundaries. |
| 710 | const turnPromptId = (sessionId: string, attemptId: string) => |
| 711 | SessionMessage.ID.make(`msg_t3_turn_${sessionId}:${attemptId}`); |
| 712 | const steerPromptId = (sessionId: string, messageId: string) => |
| 713 | SessionMessage.ID.make(`msg_t3_steer_${sessionId}:${messageId}`); |
| 714 | const isOwnPrompt = (inboxId: string) => inboxId.startsWith("msg_t3_"); |
| 715 | |
| 716 | const promptOf = (turn: OrchestrationV2ProviderTurn) => { |
| 717 | const nativeId = turn.nativeTurnRef?.nativeId; |
| 718 | return nativeId?.startsWith("msg_") === true ? nativeId : undefined; |
| 719 | }; |
| 720 | |
| 721 | const boundaryAfter = ( |
| 722 | turns: ReadonlyArray<OrchestrationV2ProviderTurn>, |
| 723 | providerThreadId: OrchestrationV2ProviderThread["id"], |
| 724 | kept: OrchestrationV2ProviderTurn | undefined, |
| 725 | prompts: ReadonlySet<string>, |
| 726 | ) => { |
| 727 | const later = turns |
| 728 | .filter( |
| 729 | (turn) => |
| 730 | turn.providerThreadId === providerThreadId && |
| 731 | (kept === undefined || turn.ordinal > kept.ordinal), |
| 732 | ) |
| 733 | .toSorted((left, right) => left.ordinal - right.ordinal); |
| 734 | if (later.some((turn) => promptOf(turn) === undefined && !isWakeTurn(turn))) { |
| 735 | return Effect.fail( |
| 736 | new ProviderAdapter.ProviderAdapterProtocolError({ |
| 737 | driver: OPENCODE_PROVIDER, |
| 738 | detail: |
| 739 | "This OpenCode conversation has turns from an earlier T3 Code version, so it can't be cut there.", |
| 740 | }), |
| 741 | ); |
| 742 | } |
| 743 | return Effect.succeed( |
| 744 | later.map(promptOf).find((messageId) => messageId !== undefined && prompts.has(messageId)) ?? |
| 745 | null, |
| 746 | ); |
| 747 | }; |
| 748 | |
| 749 | const isProviderAdapterError = Schema.is(ProviderAdapter.ProviderAdapterV2Error); |
| 750 | |
| 751 | // A saved or inherited variant the catalog model does not list makes OpenCode reject the turn. |
| 752 | const modelRef = ( |
| 753 | selection: ProviderAdapter.ProviderAdapterV2TurnInput["modelSelection"], |
| 754 | listedVariants: ReadonlySet<string> | undefined, |
| 755 | ) => { |
| 756 | const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(selection.model); |
| 757 | if (parsed === null) return undefined; |
| 758 | const selected = getModelSelectionStringOptionValue(selection, "variant"); |
| 759 | const variant = |
| 760 | selected === undefined || listedVariants === undefined || listedVariants.has(selected) |
| 761 | ? selected |
| 762 | : undefined; |
| 763 | return Model.Ref.make({ |
| 764 | providerID: Provider.ID.make(parsed.providerID), |
| 765 | id: Model.ID.make(parsed.modelID), |
| 766 | ...(variant === undefined ? {} : { variant: Model.VariantID.make(variant) }), |
| 767 | }); |
| 768 | }; |
| 769 | const malformedModel = (model: string) => |
| 770 | `OpenCode model '${model}' must use provider/model format`; |
| 771 | const sameModel = (left: ModelRef, right: ModelRef | undefined) => |
| 772 | left.providerID === right?.providerID && |
| 773 | left.id === right?.id && |
| 774 | (left.variant ?? "default") === (right?.variant ?? "default"); |
| 775 | |
| 776 | const agentFor = (input: ProviderAdapter.ProviderAdapterV2TurnInput) => |
| 777 | input.runtimePolicy.interactionMode === "plan" ? "plan" : "build"; |
| 778 | |
| 779 | const commandOf = (text: string) => { |
| 780 | const match = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(text.trim()); |
| 781 | return match === null ? undefined : { name: match[1]!, text: match[2] ?? "" }; |
| 782 | }; |
| 783 | |
| 784 | const skillMentions = (text: string) => [ |
| 785 | ...new Set([...text.matchAll(SKILL_MENTION_PATTERN)].flatMap((match) => match[2] ?? [])), |
| 786 | ]; |
| 787 | |
| 788 | const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) => { |
| 789 | // A step whose start was missed, in a reconnect gap or as an unreadable event, ran on an unreported model. |
| 790 | const models = |
| 791 | turn.models.size === 0 || turn.missedEvents || turn.steps > turn.startedSteps |
| 792 | ? {} |
| 793 | : { models: [...turn.models] }; |
| 794 | return turn.steps === 0 |
| 795 | ? { |
| 796 | usageScope: "main_agent" as const, |
| 797 | usageStatus: "unavailable" as const, |
| 798 | hasSubagents: turn.usedSubagents, |
| 799 | ...models, |
| 800 | } |
| 801 | : { |
| 802 | ...models, |
| 803 | usageScope: "main_agent" as const, |
| 804 | usageStatus: |
| 805 | status === "completed" && !turn.missedEvents && turn.steps >= turn.startedSteps |
| 806 | ? ("complete" as const) |
| 807 | : ("partial" as const), |
| 808 | inputTokens: turn.usage.input, |
| 809 | cachedInputTokens: turn.usage.cached, |
| 810 | cacheCreationTokens: turn.usage.cacheWrite, |
| 811 | outputTokens: turn.usage.output, |
| 812 | reasoningTokens: turn.usage.reasoning, |
| 813 | hasSubagents: turn.usedSubagents, |
| 814 | }; |
| 815 | }; |
| 816 | |
| 817 | export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: ProviderInstanceId) { |
| 818 | const server = yield* OpenCode2Server.OpenCode2Server; |
| 819 | const idAllocator = yield* IdAllocator.IdAllocatorV2; |
| 820 | const host = yield* ProviderHost.ProviderHost; |
| 821 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 822 | const fileSystem = yield* FileSystem.FileSystem; |
| 823 | const paths = yield* Path.Path; |
| 824 | const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; |
| 825 | const crypto = yield* Digest.Digest; |
| 826 | const driver = OPENCODE_PROVIDER; |
| 827 | let nativeGoalSupport: boolean | undefined; |
| 828 | const mcpServerNameFor = (threadId: string) => |
| 829 | t3McpServerName(threadId).pipe(Effect.provideService(Digest.Digest, crypto)); |
| 830 | |
| 831 | const borrow = Effect.gen(function* () { |
| 832 | const lent = yield* Deferred.make< |
| 833 | OpenCode2Server.OpenCode2Connection, |
| 834 | OpenCodeRuntime.OpenCodeRuntimeError |
| 835 | >(); |
| 836 | yield* server |
| 837 | .withConnection((connection) => |
| 838 | Deferred.succeed(lent, connection).pipe(Effect.andThen(Effect.never)), |
| 839 | ) |
| 840 | .pipe( |
| 841 | Effect.catch((error) => Deferred.fail(lent, error)), |
| 842 | Effect.forkScoped, |
| 843 | ); |
| 844 | return yield* Deferred.await(lent); |
| 845 | }); |
| 846 | |
| 847 | const openSession = Effect.fn("OpenCode2Adapter.openSession")(function* ( |
| 848 | input: Parameters<ProviderAdapter.ProviderAdapterV2["Service"]["openSession"]>[0], |
| 849 | initial: { |
| 850 | readonly connection: OpenCode2Server.OpenCode2Connection; |
| 851 | readonly scope: Scope.Closeable; |
| 852 | }, |
| 853 | ) { |
| 854 | let connection = initial.connection; |
| 855 | const supportsNativeGoals = () => compareSemverVersions(connection.version, "2.2.5") >= 0; |
| 856 | nativeGoalSupport = supportsNativeGoals(); |
| 857 | const goalHoldsTurn = (state: ThreadState) => |
| 858 | supportsNativeGoals() && |
| 859 | (state.goalRefreshing || (state.goalFresh && state.providerThread.goal?.status === "active")); |
| 860 | let client = connection.client; |
| 861 | const sessionScope = yield* Effect.scope; |
| 862 | // Project config changes model limits; key by directory because this runtime serves all instance threads. |
| 863 | const contextWindows = new Map<string, Map<string, number>>(); |
| 864 | const modelVariants = new Map<string, Map<string, ReadonlySet<string>>>(); |
| 865 | const directoryOf = (cwd: string | null | undefined) => cwd ?? host.paths.cwd; |
| 866 | const windowOf = (cwd: string | null | undefined, model: string) => |
| 867 | contextWindows.get(directoryOf(cwd))?.get(model); |
| 868 | const listedModelRef = (selection: ModelSelection, cwd: string | null | undefined) => |
| 869 | modelRef(selection, modelVariants.get(directoryOf(cwd))?.get(selection.model)); |
| 870 | const now = yield* DateTime.now; |
| 871 | let session: OrchestrationV2ProviderSession = { |
| 872 | id: input.providerSessionId, |
| 873 | driver, |
| 874 | providerInstanceId: instanceId, |
| 875 | status: "ready", |
| 876 | cwd: input.runtimePolicy.cwd ?? host.paths.cwd, |
| 877 | model: input.modelSelection.model, |
| 878 | capabilities: { |
| 879 | ...OpenCode2ProviderCapabilities, |
| 880 | turns: { |
| 881 | ...OpenCode2ProviderCapabilities.turns, |
| 882 | supportsNativeGoals: supportsNativeGoals(), |
| 883 | }, |
| 884 | }, |
| 885 | createdAt: now, |
| 886 | updatedAt: now, |
| 887 | lastError: null, |
| 888 | }; |
| 889 | const events = yield* Queue.unbounded<ProviderAdapter.ProviderAdapterV2Event, Cause.Done>(); |
| 890 | const threads = new Map<string, ThreadState>(); |
| 891 | const childOwners = new Map<string, ThreadState>(); |
| 892 | const announced = new Map<string, EventOf<"session.created">["data"]>(); |
| 893 | const strays = new Map<string, ThreadState>(); |
| 894 | const busy = new Set<string>(); |
| 895 | const pending = new Map<RuntimeRequestId, PendingRequest>(); |
| 896 | const lock = yield* Semaphore.make(1); |
| 897 | const clearing = new Map<string, Deferred.Deferred<void>>(); |
| 898 | const stagedReverts = new Set<string>(); |
| 899 | const sessionGates = yield* KeyedLock.make<string>(); |
| 900 | const exclusive = |
| 901 | (providerThread: OrchestrationV2ProviderThread) => |
| 902 | <A, E, R>(effect: Effect.Effect<A, E, R>) => { |
| 903 | const sessionId = providerThread.nativeThreadRef?.nativeId; |
| 904 | if (sessionId == null) return effect; |
| 905 | return sessionGates.withLock(sessionId, effect); |
| 906 | }; |
| 907 | const emit = (event: ProviderAdapter.ProviderAdapterV2Event) => |
| 908 | Queue.offer(events, event).pipe(Effect.asVoid); |
| 909 | const ownerOf = (sessionId: string) => childOwners.get(sessionId) ?? threads.get(sessionId); |
| 910 | const markUnsettled = (state: ThreadState) => { |
| 911 | state.unsettled = true; |
| 912 | state.unsettledStarted = busy.has(state.sessionId); |
| 913 | }; |
| 914 | |
| 915 | const newThreadState = ( |
| 916 | sessionId: string, |
| 917 | providerThread: OrchestrationV2ProviderThread, |
| 918 | directory: string, |
| 919 | subagent: ThreadState["subagent"], |
| 920 | ): ThreadState => ({ |
| 921 | sessionId, |
| 922 | providerThread, |
| 923 | imageJobs: new Map(), |
| 924 | goalRevision: 0, |
| 925 | goalFresh: false, |
| 926 | goalRefreshing: false, |
| 927 | providerTurns: new Map(), |
| 928 | active: undefined, |
| 929 | model: undefined, |
| 930 | unsettled: false, |
| 931 | unsettledStarted: false, |
| 932 | starts: 0, |
| 933 | directory, |
| 934 | agent: "build", |
| 935 | title: undefined, |
| 936 | rules: undefined, |
| 937 | policy: input.runtimePolicy, |
| 938 | grants: [], |
| 939 | calls: new Map(), |
| 940 | subagent, |
| 941 | wakes: [], |
| 942 | reports: new Map(), |
| 943 | stoppedChildren: new Set(), |
| 944 | strandedSteers: new Set(), |
| 945 | externalPrompts: new Map(), |
| 946 | mcp: undefined, |
| 947 | instructions: undefined, |
| 948 | }); |
| 949 | |
| 950 | const rootOf = (state: ThreadState): ThreadState => { |
| 951 | let current = state; |
| 952 | while (current.subagent !== undefined) current = current.subagent.call.state; |
| 953 | return current; |
| 954 | }; |
| 955 | |
| 956 | const sessionsOf = (thread: ThreadState): ReadonlyArray<ThreadState> => [ |
| 957 | thread, |
| 958 | ...[...threads.values()].filter((state) => { |
| 959 | for (let above = state.subagent?.call.state; above; above = above.subagent?.call.state) { |
| 960 | if (above === thread) return true; |
| 961 | } |
| 962 | return false; |
| 963 | }), |
| 964 | ]; |
| 965 | |
| 966 | const runningCalls = (thread: ThreadState): ReadonlyArray<SubagentCall> => |
| 967 | sessionsOf(thread).flatMap((state) => [...state.calls.values()]); |
| 968 | |
| 969 | /** |
| 970 | * The calls a subagent session answers for: the one that launched it and |
| 971 | * the ones that joined it while it ran. |
| 972 | */ |
| 973 | const callsAttachedTo = (child: ThreadState): ReadonlyArray<SubagentCall> => { |
| 974 | const parent = child.subagent?.call.state; |
| 975 | if (parent === undefined) return []; |
| 976 | return [...parent.calls.values()].filter((candidate) => candidate.child === child); |
| 977 | }; |
| 978 | |
| 979 | const callsAbove = (sessionId: string) => { |
| 980 | const calls: Array<SubagentCall> = []; |
| 981 | let current = threads.get(sessionId); |
| 982 | while (current?.subagent !== undefined) { |
| 983 | calls.push(current.subagent.call); |
| 984 | current = current.subagent.call.state; |
| 985 | } |
| 986 | return calls; |
| 987 | }; |
| 988 | |
| 989 | const requestTurn = (sessionId: string) => { |
| 990 | const state = ownerOf(sessionId); |
| 991 | if (state === undefined) return undefined; |
| 992 | const background = callsAbove(sessionId).findLast((call) => call.background); |
| 993 | if (background !== undefined) { |
| 994 | return isOrchestrationV2WorkActive(background.status) |
| 995 | ? { state, turn: background.turn } |
| 996 | : undefined; |
| 997 | } |
| 998 | return state.active === undefined ? undefined : { state, turn: state.active }; |
| 999 | }; |
| 1000 | |
| 1001 | const shellInfo = new Map<string, Shell.Info>(); |
| 1002 | const shells = new Map< |
| 1003 | string, |
| 1004 | { |
| 1005 | state: ThreadState; |
| 1006 | turn?: ActiveTurn; |
| 1007 | toolId?: string; |
| 1008 | tool?: { name: string; input: Record<string, unknown> }; |
| 1009 | command: string; |
| 1010 | running: boolean; |
| 1011 | awaited?: boolean; |
| 1012 | stopping?: boolean; |
| 1013 | output: string; |
| 1014 | cursor: number; |
| 1015 | startedAt?: DateTime.Utc; |
| 1016 | recoveredRunId?: RunId | null; |
| 1017 | published?: boolean; |
| 1018 | } |
| 1019 | >(); |
| 1020 | |
| 1021 | // A held wake routes its shell launches only when T3 starts its run, so marks wait on the wake. |
| 1022 | const heldLaunch = (state: ThreadState, taskId: string) => |
| 1023 | sessionsOf(state) |
| 1024 | .flatMap((session) => session.wakes) |
| 1025 | .find((wake) => |
| 1026 | wake.events.some( |
| 1027 | (event) => |
| 1028 | event.type === "session.tool.success" && |
| 1029 | stringField(event.data.metadata, "shellID") === taskId && |
| 1030 | event.data.metadata?.["exit"] === undefined && |
| 1031 | event.data.metadata?.["signal"] === undefined && |
| 1032 | event.data.metadata?.["timeout"] !== true, |
| 1033 | ), |
| 1034 | ); |
| 1035 | const wakeLaunchingShell = (state: ThreadState, taskId: string) => { |
| 1036 | const wake = heldLaunch(state, taskId); |
| 1037 | return wake === undefined || |
| 1038 | wake.ended.has(taskId) || |
| 1039 | (shellInfo.get(taskId)?.status ?? "running") !== "running" || |
| 1040 | // An end report held with the launch replays after it. |
| 1041 | wake.events.some( |
| 1042 | (event) => |
| 1043 | event.type === "session.inbox.enqueued" && |
| 1044 | event.data.item.type === "synthetic" && |
| 1045 | stringField(event.data.item.payload.metadata, "source") === "shell" && |
| 1046 | stringField(event.data.item.payload.metadata, "shellID") === taskId, |
| 1047 | ) |
| 1048 | ? undefined |
| 1049 | : wake; |
| 1050 | }; |
| 1051 | let replaying: Wake | undefined; |
| 1052 | |
| 1053 | const owesWork = (state: ThreadState) => |
| 1054 | [...shells.values()].some((shell) => shell.state === state && shell.running) || |
| 1055 | [...state.imageJobs.values()].some((job) => job.status === "running") || |
| 1056 | state.wakes.length > 0 || |
| 1057 | state.reports.size > 0 || |
| 1058 | (state.subagent !== undefined && busy.has(state.sessionId)) || |
| 1059 | [...state.calls.values()].some((call) => call.background); |
| 1060 | |
| 1061 | const hasBackground = (thread: ThreadState) => sessionsOf(thread).some(owesWork); |
| 1062 | |
| 1063 | const emitProviderThread = Effect.fnUntraced(function* (state: ThreadState) { |
| 1064 | const pendingBackgroundWork = hasBackground(state); |
| 1065 | state.publishedBackgroundWork = pendingBackgroundWork; |
| 1066 | yield* emit({ |
| 1067 | type: "provider_thread.updated", |
| 1068 | driver, |
| 1069 | providerThread: state.providerThread, |
| 1070 | pendingBackgroundWork, |
| 1071 | ...(state.sessionScopedBackground === true ? { sessionScoped: true } : {}), |
| 1072 | }); |
| 1073 | }); |
| 1074 | |
| 1075 | // Goal changes share the event stream, so do not create a span per notification. |
| 1076 | const updateGoal = Effect.fnUntraced(function* ( |
| 1077 | state: ThreadState, |
| 1078 | goal: typeof NativeGoal.Type, |
| 1079 | ) { |
| 1080 | state.goalRevision += 1; |
| 1081 | state.goalFresh = true; |
| 1082 | state.goalRefreshing = false; |
| 1083 | state.providerThread = { |
| 1084 | ...state.providerThread, |
| 1085 | goal: |
| 1086 | goal === null |
| 1087 | ? null |
| 1088 | : { |
| 1089 | objective: goal.objective, |
| 1090 | status: goal.status, |
| 1091 | checks: goal.rounds, |
| 1092 | ...(goal.reason === undefined ? {} : { lastCheck: goal.reason }), |
| 1093 | }, |
| 1094 | updatedAt: yield* DateTime.now, |
| 1095 | }; |
| 1096 | yield* emitProviderThread(state); |
| 1097 | }); |
| 1098 | |
| 1099 | const readGoal = Effect.fn("OpenCode2Adapter.readGoal")(function* (state: ThreadState) { |
| 1100 | const revision = state.goalRevision; |
| 1101 | const result = yield* client.rpc.call({ |
| 1102 | rpcID: "opencode.goal", |
| 1103 | method: "get", |
| 1104 | location: { directory: state.directory }, |
| 1105 | input: { sessionID: state.sessionId }, |
| 1106 | }); |
| 1107 | const goal = yield* decodeGoal(result.output); |
| 1108 | return yield* lock.withPermit( |
| 1109 | Effect.gen(function* () { |
| 1110 | if (state.goalRevision !== revision) return false; |
| 1111 | yield* updateGoal(state, goal); |
| 1112 | return true; |
| 1113 | }), |
| 1114 | ); |
| 1115 | }); |
| 1116 | |
| 1117 | const setSessionStatus = |
| 1118 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 1119 | Effect.fnUntraced(function* ( |
| 1120 | status: OrchestrationV2ProviderSession["status"], |
| 1121 | lastError: string | null, |
| 1122 | ) { |
| 1123 | // The session is shared by every thread on this instance and is persisted |
| 1124 | // once per attached thread, so a repeat of the same state is not worth a write. |
| 1125 | if (session.status === status && session.lastError === lastError) return; |
| 1126 | session = { ...session, status, lastError, updatedAt: yield* DateTime.now }; |
| 1127 | yield* emit({ type: "provider_session.updated", driver, providerSession: session }); |
| 1128 | }); |
| 1129 | |
| 1130 | const ordinalOf = (turn: ActiveTurn, nativeId: string) => { |
| 1131 | const known = turn.ordinals.get(nativeId); |
| 1132 | if (known !== undefined) return known; |
| 1133 | const next = turn.nextOrdinal++; |
| 1134 | turn.ordinals.set(nativeId, next); |
| 1135 | return next; |
| 1136 | }; |
| 1137 | |
| 1138 | const itemBase = ( |
| 1139 | state: ThreadState, |
| 1140 | turn: ActiveTurn, |
| 1141 | nativeId: string, |
| 1142 | status: OrchestrationV2TurnItem["status"], |
| 1143 | startedAt: DateTime.Utc, |
| 1144 | completedAt: DateTime.Utc | null, |
| 1145 | updatedAt: DateTime.Utc, |
| 1146 | ) => ({ |
| 1147 | id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: nativeId }), |
| 1148 | threadId: turn.input.threadId, |
| 1149 | runId: turn.input.runId, |
| 1150 | nodeId: idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId: nativeId }), |
| 1151 | providerThreadId: state.providerThread.id, |
| 1152 | providerTurnId: turn.providerTurn.id, |
| 1153 | nativeItemRef: ref(nativeId), |
| 1154 | parentItemId: null, |
| 1155 | ordinal: ordinalOf(turn, nativeId), |
| 1156 | status, |
| 1157 | title: null, |
| 1158 | startedAt, |
| 1159 | completedAt, |
| 1160 | updatedAt, |
| 1161 | }); |
| 1162 | |
| 1163 | const emitNode = ( |
| 1164 | state: ThreadState, |
| 1165 | turn: ActiveTurn, |
| 1166 | nativeId: string, |
| 1167 | kind: OrchestrationV2ExecutionNode["kind"], |
| 1168 | status: OrchestrationV2ExecutionNode["status"], |
| 1169 | startedAt: DateTime.Utc, |
| 1170 | completedAt: DateTime.Utc | null, |
| 1171 | ) => |
| 1172 | emit({ |
| 1173 | type: "node.updated", |
| 1174 | driver, |
| 1175 | node: { |
| 1176 | id: idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId: nativeId }), |
| 1177 | threadId: turn.input.threadId, |
| 1178 | runId: turn.input.runId, |
| 1179 | parentNodeId: turn.input.rootNodeId, |
| 1180 | rootNodeId: turn.input.rootNodeId, |
| 1181 | kind, |
| 1182 | status, |
| 1183 | countsForRun: false, |
| 1184 | providerThreadId: state.providerThread.id, |
| 1185 | providerTurnId: turn.providerTurn.id, |
| 1186 | nativeItemRef: ref(nativeId), |
| 1187 | runtimeRequestId: null, |
| 1188 | checkpointScopeId: null, |
| 1189 | startedAt, |
| 1190 | completedAt, |
| 1191 | }, |
| 1192 | }); |
| 1193 | |
| 1194 | const emitText = Effect.fnUntraced(function* ( |
| 1195 | state: ThreadState, |
| 1196 | turn: ActiveTurn, |
| 1197 | data: { |
| 1198 | readonly assistantMessageID: string; |
| 1199 | readonly ordinal: number; |
| 1200 | readonly text?: string; |
| 1201 | }, |
| 1202 | kind: "text" | "reasoning", |
| 1203 | update: (current: string) => string, |
| 1204 | completed = "text" in data, |
| 1205 | phase?: "final_answer", |
| 1206 | ) { |
| 1207 | const nativeId = `${data.assistantMessageID}:${kind}:${data.ordinal}`; |
| 1208 | const updatedAt = yield* DateTime.now; |
| 1209 | const entry = turn.texts.get(nativeId) ?? { |
| 1210 | block: data, |
| 1211 | kind, |
| 1212 | startedAt: updatedAt, |
| 1213 | text: "", |
| 1214 | }; |
| 1215 | entry.text = update(entry.text); |
| 1216 | if (completed) turn.texts.delete(nativeId); |
| 1217 | else turn.texts.set(nativeId, entry); |
| 1218 | if (entry.text.length === 0) return; |
| 1219 | if (completed && kind === "text") { |
| 1220 | turn.answer = entry.text; |
| 1221 | turn.closingText = entry; |
| 1222 | } |
| 1223 | const status = completed ? "completed" : "running"; |
| 1224 | const completedAt = completed ? updatedAt : null; |
| 1225 | const nodeKind = kind === "text" ? "assistant_message" : "reasoning"; |
| 1226 | yield* emitNode(state, turn, nativeId, nodeKind, status, entry.startedAt, completedAt); |
| 1227 | const base = itemBase(state, turn, nativeId, status, entry.startedAt, completedAt, updatedAt); |
| 1228 | if (kind === "reasoning") { |
| 1229 | yield* emit({ |
| 1230 | type: "turn_item.updated", |
| 1231 | driver, |
| 1232 | turnItem: { ...base, type: "reasoning", text: entry.text, streaming: !completed }, |
| 1233 | }); |
| 1234 | return; |
| 1235 | } |
| 1236 | const messageId = idAllocator.derive.messageFromProviderItem({ |
| 1237 | driver, |
| 1238 | nativeItemId: nativeId, |
| 1239 | }); |
| 1240 | const message: OrchestrationV2ConversationMessage = { |
| 1241 | createdBy: "agent", |
| 1242 | creationSource: "provider", |
| 1243 | id: messageId, |
| 1244 | threadId: turn.input.threadId, |
| 1245 | runId: turn.input.runId, |
| 1246 | nodeId: base.nodeId, |
| 1247 | role: "assistant", |
| 1248 | text: entry.text, |
| 1249 | attachments: [], |
| 1250 | streaming: !completed, |
| 1251 | createdAt: entry.startedAt, |
| 1252 | updatedAt, |
| 1253 | }; |
| 1254 | yield* emit({ type: "message.updated", driver, message }); |
| 1255 | yield* emit({ |
| 1256 | type: "turn_item.updated", |
| 1257 | driver, |
| 1258 | turnItem: { |
| 1259 | ...base, |
| 1260 | type: "assistant_message", |
| 1261 | messageId, |
| 1262 | text: entry.text, |
| 1263 | streaming: !completed, |
| 1264 | ...(phase === undefined ? {} : { phase }), |
| 1265 | }, |
| 1266 | }); |
| 1267 | }); |
| 1268 | |
| 1269 | // Background reports delivered into a running turn never reach a wake, so show them here. |
| 1270 | const emitDeliveredReport = Effect.fnUntraced(function* ( |
| 1271 | state: ThreadState, |
| 1272 | turn: ActiveTurn, |
| 1273 | inboxId: string, |
| 1274 | report: BackgroundWorkReport, |
| 1275 | ) { |
| 1276 | // A report can land right after the answer; the reply to it must not fold the answer away. |
| 1277 | const answer = turn.closingText; |
| 1278 | if (answer !== undefined) { |
| 1279 | const nativeId = `${answer.block.assistantMessageID}:text:${answer.block.ordinal}`; |
| 1280 | turn.texts.set(nativeId, answer); |
| 1281 | yield* emitText(state, turn, answer.block, "text", (text) => text, true, "final_answer"); |
| 1282 | turn.closingText = undefined; |
| 1283 | } |
| 1284 | const now = yield* DateTime.now; |
| 1285 | yield* emit({ |
| 1286 | type: "turn_item.updated", |
| 1287 | driver, |
| 1288 | turnItem: { |
| 1289 | ...itemBase(state, turn, inboxId, "completed", now, now, now), |
| 1290 | nodeId: turn.input.rootNodeId, |
| 1291 | type: "notification", |
| 1292 | ...backgroundWorkNotification([report]), |
| 1293 | }, |
| 1294 | }); |
| 1295 | }); |
| 1296 | |
| 1297 | // T3's own prompts are sent while their turn is active, so only other clients reach here. |
| 1298 | const emitExternalPrompt = Effect.fnUntraced(function* ( |
| 1299 | state: ThreadState, |
| 1300 | turn: ActiveTurn, |
| 1301 | inboxId: string, |
| 1302 | text: string, |
| 1303 | ) { |
| 1304 | const now = yield* DateTime.now; |
| 1305 | const base = { |
| 1306 | ...itemBase(state, turn, inboxId, "completed", now, now, now), |
| 1307 | nodeId: turn.input.rootNodeId, |
| 1308 | }; |
| 1309 | // History derives the same ID from the message ID, so a later snapshot does not duplicate it. |
| 1310 | const messageId = idAllocator.derive.messageFromProviderItem({ |
| 1311 | driver, |
| 1312 | nativeItemId: inboxId, |
| 1313 | }); |
| 1314 | yield* emit({ |
| 1315 | type: "message.updated", |
| 1316 | driver, |
| 1317 | message: { |
| 1318 | createdBy: "user", |
| 1319 | creationSource: "provider", |
| 1320 | id: messageId, |
| 1321 | threadId: turn.input.threadId, |
| 1322 | runId: turn.input.runId, |
| 1323 | nodeId: base.nodeId, |
| 1324 | role: "user", |
| 1325 | text, |
| 1326 | attachments: [], |
| 1327 | streaming: false, |
| 1328 | createdAt: now, |
| 1329 | updatedAt: now, |
| 1330 | }, |
| 1331 | }); |
| 1332 | yield* emit({ |
| 1333 | type: "turn_item.updated", |
| 1334 | driver, |
| 1335 | turnItem: { |
| 1336 | ...base, |
| 1337 | createdBy: "user", |
| 1338 | creationSource: "provider", |
| 1339 | type: "user_message", |
| 1340 | messageId, |
| 1341 | inputIntent: "turn_start", |
| 1342 | text, |
| 1343 | attachments: [], |
| 1344 | }, |
| 1345 | }); |
| 1346 | }); |
| 1347 | |
| 1348 | // Todo updates share the provider event span. |
| 1349 | const emitTodo = Effect.fnUntraced(function* ( |
| 1350 | state: ThreadState, |
| 1351 | turn: ActiveTurn, |
| 1352 | todos: typeof NativeTodoList.Type.todos, |
| 1353 | ) { |
| 1354 | turn.todoPlanId ??= yield* idAllocator.allocate.plan({ |
| 1355 | threadId: turn.input.threadId, |
| 1356 | ...(turn.input.runId === null ? {} : { runId: turn.input.runId }), |
| 1357 | driver, |
| 1358 | }); |
| 1359 | const nativeId = `${state.sessionId}:todo:${turn.providerTurn.id}`; |
| 1360 | const now = yield* DateTime.now; |
| 1361 | const startedAt = turn.startedAt.get(nativeId) ?? now; |
| 1362 | turn.startedAt.set(nativeId, startedAt); |
| 1363 | const steps: Array<OrchestrationV2PlanStep> = todos.flatMap((todo, index) => |
| 1364 | todo.status === "cancelled" |
| 1365 | ? [] |
| 1366 | : [ |
| 1367 | { |
| 1368 | id: `${nativeId}:${index + 1}`, |
| 1369 | text: todo.content.trim() || `Todo ${index + 1}`, |
| 1370 | status: |
| 1371 | todo.status === "completed" |
| 1372 | ? "completed" |
| 1373 | : todo.status === "in_progress" |
| 1374 | ? "running" |
| 1375 | : "pending", |
| 1376 | }, |
| 1377 | ], |
| 1378 | ); |
| 1379 | const base = itemBase(state, turn, nativeId, "completed", startedAt, now, now); |
| 1380 | yield* emitNode(state, turn, nativeId, "todo_list", "completed", startedAt, now); |
| 1381 | yield* emit({ |
| 1382 | type: "plan.updated", |
| 1383 | driver, |
| 1384 | plan: { |
| 1385 | id: turn.todoPlanId, |
| 1386 | threadId: turn.input.threadId, |
| 1387 | runId: turn.input.runId, |
| 1388 | nodeId: base.nodeId, |
| 1389 | kind: "todo_list", |
| 1390 | status: steps.every((step) => step.status === "completed") ? "completed" : "active", |
| 1391 | steps, |
| 1392 | }, |
| 1393 | }); |
| 1394 | yield* emit({ |
| 1395 | type: "turn_item.updated", |
| 1396 | driver, |
| 1397 | turnItem: { |
| 1398 | ...base, |
| 1399 | type: "todo_list", |
| 1400 | title: "Todo list", |
| 1401 | planId: turn.todoPlanId, |
| 1402 | steps, |
| 1403 | }, |
| 1404 | }); |
| 1405 | }); |
| 1406 | |
| 1407 | const emitTool = Effect.fnUntraced(function* ( |
| 1408 | state: ThreadState, |
| 1409 | turn: ActiveTurn, |
| 1410 | id: string, |
| 1411 | status: "running" | "completed" | "failed" | "interrupted", |
| 1412 | result?: { |
| 1413 | readonly output: string | undefined; |
| 1414 | readonly nativeTaskId?: string; |
| 1415 | readonly metadata: unknown; |
| 1416 | readonly files?: ReadonlyArray<{ readonly uri: string; readonly mime: string }>; |
| 1417 | }, |
| 1418 | ) { |
| 1419 | const tool = turn.tools.get(id); |
| 1420 | if (tool === undefined) return; |
| 1421 | if (tool.name === "todowrite") { |
| 1422 | if (status === "running") return; |
| 1423 | if (status === "completed" && isNativeTodoList(result?.metadata)) { |
| 1424 | const projected = yield* emitTodo(state, turn, result.metadata.todos).pipe( |
| 1425 | Effect.as(true), |
| 1426 | Effect.catchTags({ |
| 1427 | IdAllocatorV2AllocationError: (error) => |
| 1428 | Effect.logWarning("Could not allocate an OpenCode todo list.", error).pipe( |
| 1429 | Effect.as(false), |
| 1430 | ), |
| 1431 | }), |
| 1432 | ); |
| 1433 | if (projected) return; |
| 1434 | } |
| 1435 | } |
| 1436 | if (tool.name === "experimental_image_generate" && status === "completed") { |
| 1437 | const jobID = stringField(result?.metadata, "jobID"); |
| 1438 | const path = stringField(result?.metadata, "path"); |
| 1439 | const model = stringField(result?.metadata, "model"); |
| 1440 | if (jobID !== undefined && path !== undefined && model !== undefined) { |
| 1441 | // Tool success acknowledges launch, not the background image's outcome. |
| 1442 | if ( |
| 1443 | state.imageJobs.get(jobID)?.status !== undefined && |
| 1444 | state.imageJobs.get(jobID)?.status !== "running" |
| 1445 | ) |
| 1446 | return; |
| 1447 | if (!state.imageJobs.has(jobID)) |
| 1448 | state.imageJobs.set(jobID, { |
| 1449 | turn, |
| 1450 | toolId: id, |
| 1451 | tool, |
| 1452 | previewed: false, |
| 1453 | path, |
| 1454 | model, |
| 1455 | status: "running", |
| 1456 | }); |
| 1457 | status = "running"; |
| 1458 | yield* syncRosterAncestors(state); |
| 1459 | } |
| 1460 | } |
| 1461 | const updatedAt = yield* DateTime.now; |
| 1462 | const startedAt = turn.startedAt.get(id) ?? updatedAt; |
| 1463 | const completedAt = status === "running" ? null : updatedAt; |
| 1464 | const nativeId = `${turn.scope}${id}`; |
| 1465 | const settled = |
| 1466 | status === "completed" && openCodeCommandFailed(tool.name, result?.metadata) |
| 1467 | ? "failed" |
| 1468 | : status; |
| 1469 | yield* emitNode(state, turn, nativeId, "tool_call", settled, startedAt, completedAt); |
| 1470 | const turnItem = openCodeToolTurnItem( |
| 1471 | { |
| 1472 | ...itemBase(state, turn, nativeId, settled, startedAt, completedAt, updatedAt), |
| 1473 | ...(result?.nativeTaskId === undefined |
| 1474 | ? {} |
| 1475 | : { nativeItemRef: ref(result.nativeTaskId) }), |
| 1476 | }, |
| 1477 | { |
| 1478 | name: tool.name, |
| 1479 | input: tool.input, |
| 1480 | output: result?.output, |
| 1481 | files: result?.files, |
| 1482 | completedMetadata: |
| 1483 | status === "completed" || result?.nativeTaskId !== undefined |
| 1484 | ? result?.metadata |
| 1485 | : undefined, |
| 1486 | }, |
| 1487 | ); |
| 1488 | yield* emit({ type: "turn_item.updated", driver, turnItem }); |
| 1489 | if (status === "running") return; |
| 1490 | // A script that returns the reference already renders through its own item. |
| 1491 | const returnedPage = |
| 1492 | turnItem.type === "dynamic_tool" ? htmlRenderFromToolItem(turnItem) : undefined; |
| 1493 | const pages = openCodeCodeModeHtmlRenders( |
| 1494 | result?.metadata, |
| 1495 | yield* mcpServerNameFor(turn.input.threadId), |
| 1496 | ); |
| 1497 | for (const { index, input } of pages) { |
| 1498 | const pageId = `${nativeId}:${HTML_RENDER_TOOL_NAME}:${index}`; |
| 1499 | if (turn.takenPages.has(pageId)) continue; |
| 1500 | turn.takenPages.add(pageId); |
| 1501 | const page = yield* mcpSessions.takeHtmlRender(turn.input.threadId, input); |
| 1502 | if (page === undefined || page.attachmentId === returnedPage?.attachmentId) continue; |
| 1503 | yield* emitNode(state, turn, pageId, "tool_call", "completed", startedAt, updatedAt); |
| 1504 | yield* emit({ |
| 1505 | type: "turn_item.updated", |
| 1506 | driver, |
| 1507 | turnItem: { |
| 1508 | ...itemBase(state, turn, pageId, "completed", startedAt, updatedAt, updatedAt), |
| 1509 | type: "dynamic_tool", |
| 1510 | toolName: `t3-code.${HTML_RENDER_TOOL_NAME}`, |
| 1511 | input: { title: page.title, height: page.height }, |
| 1512 | output: { htmlRender: page }, |
| 1513 | }, |
| 1514 | }); |
| 1515 | } |
| 1516 | }); |
| 1517 | |
| 1518 | const emitCompaction = Effect.fnUntraced(function* ( |
| 1519 | state: ThreadState, |
| 1520 | turn: ActiveTurn, |
| 1521 | status: "running" | "completed" | "failed" | "interrupted", |
| 1522 | summary?: string, |
| 1523 | ) { |
| 1524 | const compaction = turn.compaction; |
| 1525 | if (compaction === undefined) return; |
| 1526 | const updatedAt = yield* DateTime.now; |
| 1527 | const completedAt = status === "running" ? null : updatedAt; |
| 1528 | yield* emit({ |
| 1529 | type: "turn_item.updated", |
| 1530 | driver, |
| 1531 | turnItem: { |
| 1532 | ...itemBase( |
| 1533 | state, |
| 1534 | turn, |
| 1535 | compaction.nativeId, |
| 1536 | status, |
| 1537 | compaction.startedAt, |
| 1538 | completedAt, |
| 1539 | updatedAt, |
| 1540 | ), |
| 1541 | nodeId: turn.input.rootNodeId, |
| 1542 | type: "compaction", |
| 1543 | driver, |
| 1544 | title: |
| 1545 | status === "running" |
| 1546 | ? "Compacting context" |
| 1547 | : status === "completed" |
| 1548 | ? "Context compacted" |
| 1549 | : status === "failed" |
| 1550 | ? "Compaction failed" |
| 1551 | : "Compaction interrupted", |
| 1552 | ...(summary === undefined || summary.length === 0 ? {} : { summary }), |
| 1553 | }, |
| 1554 | }); |
| 1555 | // The pre-compaction step would otherwise settle the turn as its newest usage. |
| 1556 | if (status === "completed") turn.lastStep = undefined; |
| 1557 | if (status === "completed" && state.providerThread.contextUsage !== null) { |
| 1558 | state.providerThread = { |
| 1559 | ...state.providerThread, |
| 1560 | contextUsage: null, |
| 1561 | updatedAt, |
| 1562 | }; |
| 1563 | yield* emitProviderThread(state); |
| 1564 | } |
| 1565 | if (status !== "running") turn.compaction = undefined; |
| 1566 | }); |
| 1567 | |
| 1568 | const emitRetry = Effect.fnUntraced(function* ( |
| 1569 | state: ThreadState, |
| 1570 | turn: ActiveTurn, |
| 1571 | status: "running" | TurnTerminal["status"], |
| 1572 | failure?: OrchestrationV2ProviderFailure, |
| 1573 | ) { |
| 1574 | const retry = turn.retry; |
| 1575 | if (retry === undefined) return; |
| 1576 | yield* emit({ |
| 1577 | type: "turn_item.updated", |
| 1578 | driver, |
| 1579 | turnItem: makeProviderRetryTurnItem({ |
| 1580 | driver, |
| 1581 | threadId: turn.input.threadId, |
| 1582 | runId: turn.input.runId, |
| 1583 | nodeId: turn.input.rootNodeId, |
| 1584 | providerThreadId: state.providerThread.id, |
| 1585 | providerTurnId: turn.providerTurn.id, |
| 1586 | itemOrdinal: ordinalOf(turn, `terminal-failure:${turn.providerTurn.id}`), |
| 1587 | failure: failure ?? retry.failure, |
| 1588 | retry: retry.retry, |
| 1589 | status, |
| 1590 | startedAt: retry.startedAt, |
| 1591 | updatedAt: yield* DateTime.now, |
| 1592 | }), |
| 1593 | }); |
| 1594 | }); |
| 1595 | |
| 1596 | const updateRetry = Effect.fnUntraced(function* ( |
| 1597 | state: ThreadState, |
| 1598 | turn: ActiveTurn, |
| 1599 | { attempt, error }: Pick<EventOf<"session.retry.scheduled">["data"], "attempt" | "error">, |
| 1600 | delayMs: number, |
| 1601 | ) { |
| 1602 | turn.retry = { |
| 1603 | retry: { |
| 1604 | // OpenCode counts the first request as attempt 1, so its first retry is attempt 2. |
| 1605 | attempt: Math.max(1, attempt - 1), |
| 1606 | maxAttempts: null, |
| 1607 | retryDelayMs: Math.max(0, Math.trunc(delayMs)), |
| 1608 | }, |
| 1609 | failure: makeProviderFailure({ |
| 1610 | message: readableProviderErrorMessage(error.message, error.status, error.response?.body), |
| 1611 | code: error.type, |
| 1612 | class: isUsageLimit(error) ? "usage_limit" : "provider_error", |
| 1613 | retryable: true, |
| 1614 | }), |
| 1615 | startedAt: turn.retry?.startedAt ?? (yield* DateTime.now), |
| 1616 | }; |
| 1617 | yield* emitRetry(state, turn, "running"); |
| 1618 | }); |
| 1619 | |
| 1620 | // A background child's question outlives its parent's turn; keep the ingestor from dismissing it. |
| 1621 | const retainedRequestsOf = (turn: ActiveTurn) => { |
| 1622 | const ids = [...pending.values()].flatMap((entry) => |
| 1623 | entry.turn === turn ? [entry.request.id] : [], |
| 1624 | ); |
| 1625 | return ids.length === 0 ? {} : { retainedRuntimeRequestIds: ids }; |
| 1626 | }; |
| 1627 | |
| 1628 | const emitProviderTurn = ( |
| 1629 | state: ThreadState, |
| 1630 | turn: ActiveTurn, |
| 1631 | providerTurn: OrchestrationV2ProviderTurn, |
| 1632 | ) => { |
| 1633 | state.providerTurns.set(String(providerTurn.id), providerTurn); |
| 1634 | return emit({ |
| 1635 | type: "provider_turn.updated", |
| 1636 | driver, |
| 1637 | threadId: turn.input.threadId, |
| 1638 | providerTurn, |
| 1639 | ...(providerTurn.completedAt === null ? {} : retainedRequestsOf(turn)), |
| 1640 | }); |
| 1641 | }; |
| 1642 | |
| 1643 | const makeTurn = ( |
| 1644 | owner: TurnOwner, |
| 1645 | providerTurn: OrchestrationV2ProviderTurn, |
| 1646 | options: { readonly scope: string; readonly awaitingStart: boolean }, |
| 1647 | ): ActiveTurn => ({ |
| 1648 | input: owner, |
| 1649 | providerTurn, |
| 1650 | texts: new Map(), |
| 1651 | answer: undefined, |
| 1652 | closingText: undefined, |
| 1653 | tools: new Map(), |
| 1654 | startedAt: new Map(), |
| 1655 | ordinals: new Map(), |
| 1656 | nextOrdinal: providerTurn.ordinal * 100 + 1, |
| 1657 | usage: { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 }, |
| 1658 | startedSteps: 0, |
| 1659 | missedEvents: false, |
| 1660 | steps: 0, |
| 1661 | models: new Set(), |
| 1662 | lastStep: undefined, |
| 1663 | before: undefined, |
| 1664 | compaction: undefined, |
| 1665 | compactions: 0, |
| 1666 | todoPlanId: undefined, |
| 1667 | retry: undefined, |
| 1668 | interrupted: false, |
| 1669 | unsent: false, |
| 1670 | steers: new Set(), |
| 1671 | settledInbox: new Set(), |
| 1672 | takenPages: new Set(), |
| 1673 | heldEnd: undefined, |
| 1674 | awaitingStart: options.awaitingStart, |
| 1675 | scope: options.scope, |
| 1676 | usedSubagents: false, |
| 1677 | }); |
| 1678 | |
| 1679 | const emitSubagent = Effect.fnUntraced(function* (call: SubagentCall) { |
| 1680 | const updatedAt = yield* DateTime.now; |
| 1681 | const { turn, state } = call; |
| 1682 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 1683 | driver, |
| 1684 | nativeItemId: call.nativeId, |
| 1685 | }); |
| 1686 | const completedAt = isOrchestrationV2WorkActive(call.status) |
| 1687 | ? null |
| 1688 | : (call.completedAt ?? updatedAt); |
| 1689 | const childProviderThreadId = call.child?.providerThread.id ?? null; |
| 1690 | const childThreadId = call.child?.subagent?.appThread.id ?? null; |
| 1691 | yield* emit({ |
| 1692 | type: "node.updated", |
| 1693 | driver, |
| 1694 | node: { |
| 1695 | id: nodeId, |
| 1696 | threadId: turn.input.threadId, |
| 1697 | runId: turn.input.runId, |
| 1698 | parentNodeId: turn.input.rootNodeId, |
| 1699 | rootNodeId: turn.input.rootNodeId, |
| 1700 | kind: "subagent", |
| 1701 | status: call.status, |
| 1702 | countsForRun: false, |
| 1703 | providerThreadId: childProviderThreadId ?? state.providerThread.id, |
| 1704 | providerTurnId: turn.providerTurn.id, |
| 1705 | nativeItemRef: ref(call.nativeId), |
| 1706 | runtimeRequestId: null, |
| 1707 | checkpointScopeId: null, |
| 1708 | startedAt: call.startedAt, |
| 1709 | completedAt, |
| 1710 | }, |
| 1711 | }); |
| 1712 | yield* emit({ |
| 1713 | type: "subagent.updated", |
| 1714 | driver, |
| 1715 | subagent: { |
| 1716 | id: nodeId, |
| 1717 | threadId: turn.input.threadId, |
| 1718 | runId: turn.input.runId, |
| 1719 | parentNodeId: turn.input.rootNodeId, |
| 1720 | origin: "provider_native", |
| 1721 | createdBy: "agent", |
| 1722 | driver, |
| 1723 | providerInstanceId: instanceId, |
| 1724 | providerThreadId: childProviderThreadId, |
| 1725 | childThreadId, |
| 1726 | nativeTaskRef: ref(call.nativeId), |
| 1727 | prompt: call.prompt, |
| 1728 | title: call.title, |
| 1729 | model: call.model, |
| 1730 | status: call.status, |
| 1731 | result: call.result, |
| 1732 | startedAt: call.startedAt, |
| 1733 | completedAt, |
| 1734 | updatedAt, |
| 1735 | }, |
| 1736 | }); |
| 1737 | yield* emit({ |
| 1738 | type: "turn_item.updated", |
| 1739 | driver, |
| 1740 | turnItem: { |
| 1741 | id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: call.nativeId }), |
| 1742 | threadId: turn.input.threadId, |
| 1743 | runId: turn.input.runId, |
| 1744 | nodeId, |
| 1745 | providerThreadId: state.providerThread.id, |
| 1746 | providerTurnId: turn.providerTurn.id, |
| 1747 | nativeItemRef: ref(call.nativeId), |
| 1748 | parentItemId: null, |
| 1749 | ordinal: call.ordinal, |
| 1750 | status: call.status, |
| 1751 | title: call.title, |
| 1752 | startedAt: call.startedAt, |
| 1753 | completedAt, |
| 1754 | updatedAt, |
| 1755 | type: "subagent", |
| 1756 | subagentId: nodeId, |
| 1757 | origin: "provider_native", |
| 1758 | driver, |
| 1759 | providerInstanceId: instanceId, |
| 1760 | childThreadId, |
| 1761 | prompt: call.prompt, |
| 1762 | result: call.result, |
| 1763 | }, |
| 1764 | }); |
| 1765 | yield* syncRosterAncestors(call.state); |
| 1766 | }); |
| 1767 | |
| 1768 | const syncRoster = Effect.fnUntraced(function* (state: ThreadState) { |
| 1769 | const roster: Array<import("@t3tools/contracts").OrchestrationV2PendingBackgroundTask> = |
| 1770 | runningCalls(state) |
| 1771 | .filter((call) => call.background) |
| 1772 | .map((call) => ({ |
| 1773 | taskId: call.nativeId, |
| 1774 | kind: "subagent" as const, |
| 1775 | ...(call.title?.trim() ? { description: call.title.trim() } : {}), |
| 1776 | ...(call.child?.subagent === undefined |
| 1777 | ? {} |
| 1778 | : { childThreadId: call.child.subagent.appThread.id }), |
| 1779 | })); |
| 1780 | for (const [taskId, shell] of shells) { |
| 1781 | if (shell.running && sessionsOf(state).includes(shell.state)) { |
| 1782 | roster.push({ |
| 1783 | taskId, |
| 1784 | kind: "command", |
| 1785 | description: shell.command, |
| 1786 | ...(shell.awaited === true ? { awaited: true } : {}), |
| 1787 | ...(shell.state.subagent === undefined |
| 1788 | ? {} |
| 1789 | : { parentTaskId: shell.state.subagent.call.nativeId }), |
| 1790 | }); |
| 1791 | } |
| 1792 | } |
| 1793 | const imageTasks = sessionsOf(state).flatMap((session) => |
| 1794 | [...session.imageJobs.entries()].flatMap(([taskId, job]) => |
| 1795 | job.status === "running" |
| 1796 | ? [ |
| 1797 | { |
| 1798 | taskId, |
| 1799 | kind: "background_task" as const, |
| 1800 | description: `Image generation (${job.model})`, |
| 1801 | }, |
| 1802 | ] |
| 1803 | : [], |
| 1804 | ), |
| 1805 | ); |
| 1806 | const allTasks = roster.concat(imageTasks); |
| 1807 | const current = state.providerThread.pendingBackgroundTasks ?? []; |
| 1808 | if ( |
| 1809 | state.publishedBackgroundWork === hasBackground(state) && |
| 1810 | current.length === allTasks.length && |
| 1811 | current.every( |
| 1812 | (task, index) => |
| 1813 | task.taskId === allTasks[index]?.taskId && |
| 1814 | task.description === allTasks[index]?.description && |
| 1815 | task.awaited === allTasks[index]?.awaited && |
| 1816 | (task.kind === "subagent" ? task.childThreadId : undefined) === |
| 1817 | (allTasks[index]?.kind === "subagent" ? allTasks[index]?.childThreadId : undefined), |
| 1818 | ) |
| 1819 | ) { |
| 1820 | return; |
| 1821 | } |
| 1822 | state.providerThread = { |
| 1823 | ...state.providerThread, |
| 1824 | pendingBackgroundTasks: allTasks, |
| 1825 | updatedAt: yield* DateTime.now, |
| 1826 | }; |
| 1827 | yield* emitProviderThread(state); |
| 1828 | }); |
| 1829 | |
| 1830 | const syncRosterAncestors = Effect.fnUntraced(function* (state: ThreadState) { |
| 1831 | let current: ThreadState | undefined = state; |
| 1832 | while (current !== undefined) { |
| 1833 | yield* syncRoster(current); |
| 1834 | current = current.subagent?.call.state; |
| 1835 | } |
| 1836 | }); |
| 1837 | |
| 1838 | const fetchShellOutput = Effect.fn("OpenCode2Adapter.fetchShellOutput")(function* ( |
| 1839 | id: string, |
| 1840 | snapshot: { directory: string; cursor: number; output: string }, |
| 1841 | settled = false, |
| 1842 | ) { |
| 1843 | let { cursor, output } = snapshot; |
| 1844 | // Bound each read and retained UI text; the native byte cursor must never use JS string lengths. |
| 1845 | for (let page = 0; page < (settled ? 5 : 4); page++) { |
| 1846 | const { data } = yield* client.shell.output({ |
| 1847 | id: Shell.ID.make(id), |
| 1848 | location: { directory: snapshot.directory }, |
| 1849 | cursor, |
| 1850 | limit: 65536, |
| 1851 | }); |
| 1852 | output = (output + data.output).slice(-262144); |
| 1853 | const previous = cursor; |
| 1854 | cursor = data.cursor; |
| 1855 | if (data.cursor >= data.size || data.cursor <= previous) break; |
| 1856 | if (settled && data.size - data.cursor > 262144) { |
| 1857 | cursor = data.size - 262144; |
| 1858 | output = ""; |
| 1859 | } |
| 1860 | } |
| 1861 | return { cursor, output }; |
| 1862 | }, Effect.timeout(INVENTORY_TIMEOUT)); |
| 1863 | |
| 1864 | const readShellOutput = Effect.fn("OpenCode2Adapter.readShellOutput")(function* ( |
| 1865 | id: string, |
| 1866 | settled = false, |
| 1867 | ) { |
| 1868 | const shell = shells.get(id); |
| 1869 | if (shell === undefined) return; |
| 1870 | const output = yield* fetchShellOutput( |
| 1871 | id, |
| 1872 | { |
| 1873 | directory: shell.state.directory, |
| 1874 | cursor: shell.cursor, |
| 1875 | output: shell.output, |
| 1876 | }, |
| 1877 | settled, |
| 1878 | ); |
| 1879 | Object.assign(shell, output); |
| 1880 | }); |
| 1881 | |
| 1882 | const emitShell = Effect.fnUntraced(function* ( |
| 1883 | id: string, |
| 1884 | status: "running" | "completed" | "failed" | "interrupted", |
| 1885 | exit?: number, |
| 1886 | ) { |
| 1887 | const shell = shells.get(id); |
| 1888 | if (shell === undefined) return; |
| 1889 | if (shell.turn === undefined || shell.toolId === undefined || shell.tool === undefined) { |
| 1890 | const updatedAt = yield* DateTime.now; |
| 1891 | yield* emit({ |
| 1892 | type: "turn_item.updated", |
| 1893 | driver, |
| 1894 | sessionScoped: true, |
| 1895 | turnItem: { |
| 1896 | id: idAllocator.derive.turnItemFromProviderItem({ driver, nativeItemId: id }), |
| 1897 | threadId: shell.state.providerThread.appThreadId ?? input.threadId, |
| 1898 | runId: shell.recoveredRunId ?? null, |
| 1899 | nodeId: null, |
| 1900 | providerThreadId: shell.state.providerThread.id, |
| 1901 | providerTurnId: null, |
| 1902 | nativeItemRef: ref(id), |
| 1903 | parentItemId: null, |
| 1904 | ordinal: 0, |
| 1905 | status, |
| 1906 | title: null, |
| 1907 | startedAt: shell.startedAt ?? updatedAt, |
| 1908 | completedAt: status === "running" ? null : updatedAt, |
| 1909 | updatedAt, |
| 1910 | type: "command_execution", |
| 1911 | input: shell.command, |
| 1912 | output: shell.output, |
| 1913 | ...(exit === undefined ? {} : { exitCode: exit }), |
| 1914 | }, |
| 1915 | }); |
| 1916 | shell.published = true; |
| 1917 | return; |
| 1918 | } |
| 1919 | shell.turn.tools.set(shell.toolId, shell.tool); |
| 1920 | yield* emitTool(shell.state, shell.turn, shell.toolId, status, { |
| 1921 | output: shell.output, |
| 1922 | nativeTaskId: id, |
| 1923 | metadata: { shellID: id, exit }, |
| 1924 | }); |
| 1925 | shell.turn.tools.delete(shell.toolId); |
| 1926 | shell.published = true; |
| 1927 | }); |
| 1928 | |
| 1929 | const stopShell = Effect.fn("OpenCode2Adapter.stopShell")(function* (id: string) { |
| 1930 | const shell = shells.get(id); |
| 1931 | if (shell === undefined || !shell.running) return; |
| 1932 | yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true })); |
| 1933 | shell.stopping = true; |
| 1934 | yield* client.shell |
| 1935 | .remove({ |
| 1936 | id: Shell.ID.make(id), |
| 1937 | location: { directory: shell.state.directory }, |
| 1938 | }) |
| 1939 | .pipe( |
| 1940 | Effect.timeout(INVENTORY_TIMEOUT), |
| 1941 | Effect.onError(() => |
| 1942 | Effect.sync(() => { |
| 1943 | shell.stopping = false; |
| 1944 | }), |
| 1945 | ), |
| 1946 | ); |
| 1947 | shell.stopping = false; |
| 1948 | shell.running = false; |
| 1949 | shell.state.stoppedChildren.add(id); |
| 1950 | yield* emitShell(id, "interrupted"); |
| 1951 | shells.delete(id); |
| 1952 | shellInfo.delete(id); |
| 1953 | yield* syncRosterAncestors(shell.state); |
| 1954 | }); |
| 1955 | |
| 1956 | const recoverShells = Effect.fn("OpenCode2Adapter.recoverShells")( |
| 1957 | function* (state: ThreadState) { |
| 1958 | if (compareSemverVersions(connection.version, "2.2.1") < 0) return; |
| 1959 | const jobs = |
| 1960 | compareSemverVersions(connection.version, "2.2.6") >= 0 && |
| 1961 | connection.shellJobs !== undefined |
| 1962 | ? yield* connection.shellJobs(state.sessionId).pipe(Effect.option) |
| 1963 | : undefined; |
| 1964 | const data = |
| 1965 | jobs?._tag === "Some" |
| 1966 | ? jobs.value.data.map((job) => ({ |
| 1967 | id: Shell.ID.make(job.shellID), |
| 1968 | command: job.command, |
| 1969 | metadata: { sessionID: job.sessionID }, |
| 1970 | })) |
| 1971 | : (yield* client.shell.list({ location: { directory: state.directory } })).data; |
| 1972 | for (const info of data) { |
| 1973 | const sessionId = stringField(info.metadata, "sessionID"); |
| 1974 | const owner = |
| 1975 | sessionId === undefined |
| 1976 | ? undefined |
| 1977 | : (threads.get(sessionId) ?? |
| 1978 | ownerOf(sessionId) ?? |
| 1979 | (jobs?._tag === "Some" ? state : undefined)); |
| 1980 | if (owner === undefined || !sessionsOf(state).includes(owner)) continue; |
| 1981 | if (!shells.has(info.id)) { |
| 1982 | if (state.active === undefined && !hasBackground(state)) { |
| 1983 | state.sessionScopedBackground = true; |
| 1984 | delete state.publishedBackgroundWork; |
| 1985 | } |
| 1986 | const target = requestTurn(owner.sessionId); |
| 1987 | shells.set(info.id, { |
| 1988 | state: owner, |
| 1989 | ...(target === undefined |
| 1990 | ? { |
| 1991 | recoveredRunId: |
| 1992 | owner.providerThread.lastRunOrdinal === null |
| 1993 | ? null |
| 1994 | : idAllocator.derive.run({ |
| 1995 | threadId: owner.providerThread.appThreadId ?? input.threadId, |
| 1996 | ordinal: owner.providerThread.lastRunOrdinal, |
| 1997 | }), |
| 1998 | } |
| 1999 | : { |
| 2000 | turn: target.turn, |
| 2001 | toolId: info.id, |
| 2002 | tool: { name: "shell", input: { command: info.command } }, |
| 2003 | }), |
| 2004 | command: info.command, |
| 2005 | awaited: |
| 2006 | state.providerThread.pendingBackgroundTasks?.some( |
| 2007 | (task) => task.taskId === info.id && task.awaited === true, |
| 2008 | ) === true || wakeLaunchingShell(state, info.id)?.awaited.has(info.id) === true, |
| 2009 | running: true, |
| 2010 | output: "", |
| 2011 | cursor: 0, |
| 2012 | }); |
| 2013 | } |
| 2014 | } |
| 2015 | for (const [id, shell] of shells) { |
| 2016 | if (!shell.running || !sessionsOf(state).includes(shell.state)) continue; |
| 2017 | yield* Effect.gen(function* () { |
| 2018 | const found = yield* client.shell |
| 2019 | .get({ id: Shell.ID.make(id), location: { directory: shell.state.directory } }) |
| 2020 | .pipe( |
| 2021 | Effect.timeout(INVENTORY_TIMEOUT), |
| 2022 | Effect.catchTags({ ShellNotFoundError: () => Effect.undefined }), |
| 2023 | ); |
| 2024 | if (found === undefined) { |
| 2025 | shell.running = false; |
| 2026 | yield* emitShell(id, "interrupted"); |
| 2027 | shells.delete(id); |
| 2028 | return; |
| 2029 | } |
| 2030 | const info = found.data; |
| 2031 | shell.startedAt = DateTime.makeUnsafe(info.time.started); |
| 2032 | yield* readShellOutput(id, info.status !== "running").pipe( |
| 2033 | Effect.ignore({ log: true }), |
| 2034 | ); |
| 2035 | shell.running = info.status === "running"; |
| 2036 | yield* emitShell( |
| 2037 | id, |
| 2038 | shell.running |
| 2039 | ? "running" |
| 2040 | : info.status === "killed" |
| 2041 | ? "interrupted" |
| 2042 | : info.exit === 0 |
| 2043 | ? "completed" |
| 2044 | : "failed", |
| 2045 | info.exit, |
| 2046 | ); |
| 2047 | if (!shell.running) shells.delete(id); |
| 2048 | }).pipe( |
| 2049 | Effect.catch((cause) => |
| 2050 | Effect.logWarning("Could not recover an OpenCode shell.", cause).pipe( |
| 2051 | Effect.andThen(emitShell(id, "running")), |
| 2052 | ), |
| 2053 | ), |
| 2054 | ); |
| 2055 | } |
| 2056 | }, |
| 2057 | (effect, state) => |
| 2058 | lock.withPermit( |
| 2059 | effect.pipe( |
| 2060 | Effect.timeout(INVENTORY_TIMEOUT), |
| 2061 | Effect.ensuring( |
| 2062 | Effect.gen(function* () { |
| 2063 | for (const [id, shell] of shells) { |
| 2064 | if ( |
| 2065 | shell.running && |
| 2066 | shell.published !== true && |
| 2067 | sessionsOf(state).includes(shell.state) |
| 2068 | ) |
| 2069 | yield* emitShell(id, "running"); |
| 2070 | } |
| 2071 | yield* syncRosterAncestors(state); |
| 2072 | }), |
| 2073 | ), |
| 2074 | ), |
| 2075 | ), |
| 2076 | ); |
| 2077 | |
| 2078 | const withReportedModel = ( |
| 2079 | providerThread: OrchestrationV2ProviderThread, |
| 2080 | model: ModelRef | undefined, |
| 2081 | ): OrchestrationV2ProviderThread => { |
| 2082 | if (model === undefined) return providerThread; |
| 2083 | const modelSelection: ModelSelection = { |
| 2084 | instanceId, |
| 2085 | model: `${model.providerID}/${model.id}`, |
| 2086 | options: model.variant === undefined ? [] : [{ id: "variant", value: model.variant }], |
| 2087 | }; |
| 2088 | if ( |
| 2089 | providerThread.nativeMetadata?.modelSelection !== undefined && |
| 2090 | modelSelectionsEqual(providerThread.nativeMetadata.modelSelection, modelSelection) |
| 2091 | ) |
| 2092 | return providerThread; |
| 2093 | return { |
| 2094 | ...providerThread, |
| 2095 | nativeMetadata: { ...providerThread.nativeMetadata, modelSelection }, |
| 2096 | }; |
| 2097 | }; |
| 2098 | |
| 2099 | const attachChild = Effect.fnUntraced(function* (call: SubagentCall, childId: string) { |
| 2100 | if (call.child !== undefined) return; |
| 2101 | const info = announced.get(childId); |
| 2102 | announced.delete(childId); |
| 2103 | const now = yield* DateTime.now; |
| 2104 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 2105 | driver, |
| 2106 | nativeItemId: call.nativeId, |
| 2107 | }); |
| 2108 | const childThreadId = idAllocator.derive.subagentThread({ |
| 2109 | driver, |
| 2110 | nativeThreadId: childId, |
| 2111 | providerInstanceId: instanceId, |
| 2112 | }); |
| 2113 | const providerThreadId = idAllocator.derive.providerThread({ |
| 2114 | driver, |
| 2115 | nativeThreadId: childId, |
| 2116 | providerInstanceId: instanceId, |
| 2117 | }); |
| 2118 | if (info?.model !== undefined) call.model = `${info.model.providerID}/${info.model.id}`; |
| 2119 | call.title = call.title ?? info?.title ?? null; |
| 2120 | const parentThread = call.turn.input.appThread; |
| 2121 | const appThread = makeSubagentChildThread({ |
| 2122 | parentThread, |
| 2123 | childThreadId, |
| 2124 | parentNodeId: nodeId, |
| 2125 | activeProviderThreadId: providerThreadId, |
| 2126 | providerInstanceId: instanceId, |
| 2127 | modelSelection: { |
| 2128 | instanceId, |
| 2129 | model: call.model ?? call.turn.input.modelSelection.model, |
| 2130 | }, |
| 2131 | title: subagentThreadTitle({ |
| 2132 | parentTitle: parentThread.title, |
| 2133 | title: call.title, |
| 2134 | prompt: call.prompt, |
| 2135 | ordinal: call.ordinal, |
| 2136 | }), |
| 2137 | now, |
| 2138 | createdBy: "agent", |
| 2139 | creationSource: "provider", |
| 2140 | }); |
| 2141 | const providerThread: OrchestrationV2ProviderThread = { |
| 2142 | id: providerThreadId, |
| 2143 | driver, |
| 2144 | providerInstanceId: instanceId, |
| 2145 | providerSessionId: input.providerSessionId, |
| 2146 | appThreadId: childThreadId, |
| 2147 | ownerNodeId: nodeId, |
| 2148 | nativeThreadRef: ref(childId), |
| 2149 | nativeConversationHeadRef: null, |
| 2150 | status: "active", |
| 2151 | firstRunOrdinal: null, |
| 2152 | lastRunOrdinal: null, |
| 2153 | handoffIds: [], |
| 2154 | forkedFrom: null, |
| 2155 | createdAt: now, |
| 2156 | updatedAt: now, |
| 2157 | }; |
| 2158 | const previous = threads.get(childId); |
| 2159 | // A call to a running child steers that run; OpenCode reports it once for all its calls. |
| 2160 | if (previous?.active !== undefined) call.run = previous.subagent?.turns; |
| 2161 | const subagent = { |
| 2162 | call, |
| 2163 | appThread, |
| 2164 | turns: previous?.subagent?.turns ?? 0, |
| 2165 | prompt: call.prompt, |
| 2166 | queued: undefined, |
| 2167 | }; |
| 2168 | const child = |
| 2169 | previous ?? newThreadState(childId, providerThread, call.state.directory, subagent); |
| 2170 | child.subagent = subagent; |
| 2171 | child.sessionScopedBackground = false; |
| 2172 | child.model = info?.model ?? child.model; |
| 2173 | child.providerThread = withReportedModel(providerThread, child.model); |
| 2174 | child.directory = call.state.directory; |
| 2175 | child.agent = info?.agent ?? call.agent ?? child.agent; |
| 2176 | child.rules = info?.permissions ?? child.rules; |
| 2177 | threads.set(childId, child); |
| 2178 | childOwners.set(childId, rootOf(call.state)); |
| 2179 | call.child = child; |
| 2180 | yield* emit({ type: "app_thread.created", driver, appThread }); |
| 2181 | yield* emitProviderThread(child); |
| 2182 | yield* emitSubagent(call); |
| 2183 | // Reused child sessions may retain old mode rules; refresh policy as soon as the call identifies them. |
| 2184 | if (info === undefined) { |
| 2185 | yield* writeRules(child, rootOf(call.state).policy).pipe( |
| 2186 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 2187 | Effect.ignore({ log: true }), |
| 2188 | ); |
| 2189 | } |
| 2190 | }); |
| 2191 | |
| 2192 | const settleCall: ( |
| 2193 | call: SubagentCall, |
| 2194 | status: OrchestrationV2Subagent["status"], |
| 2195 | result?: string, |
| 2196 | ) => Effect.Effect<void> = Effect.fnUntraced(function* (call, status, result) { |
| 2197 | if (!isOrchestrationV2WorkActive(call.status)) return; |
| 2198 | call.status = status; |
| 2199 | call.completedAt = yield* DateTime.now; |
| 2200 | if (result !== undefined) call.result = result; |
| 2201 | call.state.calls.delete(call.toolId); |
| 2202 | const child = call.child; |
| 2203 | if (child !== undefined) { |
| 2204 | for (const nested of Array.from(child.calls.values())) { |
| 2205 | if (nested.background && status !== "failed") continue; |
| 2206 | yield* settleCall(nested, status === "completed" ? "interrupted" : status); |
| 2207 | } |
| 2208 | if (child.active !== undefined && status !== "completed") { |
| 2209 | yield* finishTurn(child, { status: "interrupted" }); |
| 2210 | } |
| 2211 | child.sessionScopedBackground = false; |
| 2212 | child.providerThread = { |
| 2213 | ...child.providerThread, |
| 2214 | status: "idle", |
| 2215 | updatedAt: call.completedAt, |
| 2216 | }; |
| 2217 | yield* emitProviderThread(child); |
| 2218 | } |
| 2219 | yield* emitSubagent(call); |
| 2220 | }); |
| 2221 | |
| 2222 | const startChildTurn = Effect.fnUntraced(function* (child: ThreadState) { |
| 2223 | const subagent = child.subagent; |
| 2224 | if (subagent === undefined || child.active !== undefined) return; |
| 2225 | subagent.turns += 1; |
| 2226 | for (const call of callsAttachedTo(child)) call.run ??= subagent.turns; |
| 2227 | const startedAt = yield* DateTime.now; |
| 2228 | const nativeTurnId = `${child.sessionId}:turn:${subagent.turns}`; |
| 2229 | const rootNodeId = idAllocator.derive.nodeFromProviderItem({ |
| 2230 | driver, |
| 2231 | nativeItemId: `${nativeTurnId}:root`, |
| 2232 | }); |
| 2233 | const providerTurn: OrchestrationV2ProviderTurn = { |
| 2234 | id: idAllocator.derive.providerTurn({ driver, nativeTurnId }), |
| 2235 | providerThreadId: child.providerThread.id, |
| 2236 | nodeId: rootNodeId, |
| 2237 | runAttemptId: null, |
| 2238 | nativeTurnRef: ref(nativeTurnId, "weak"), |
| 2239 | ordinal: subagent.turns, |
| 2240 | status: "running", |
| 2241 | startedAt, |
| 2242 | completedAt: null, |
| 2243 | }; |
| 2244 | const turn = makeTurn( |
| 2245 | { |
| 2246 | appThread: subagent.appThread, |
| 2247 | threadId: subagent.appThread.id, |
| 2248 | runId: null, |
| 2249 | runOrdinal: subagent.call.turn.input.runOrdinal, |
| 2250 | rootNodeId, |
| 2251 | modelSelection: subagent.appThread.modelSelection, |
| 2252 | runtimePolicy: subagent.call.turn.input.runtimePolicy, |
| 2253 | }, |
| 2254 | providerTurn, |
| 2255 | { scope: `${child.sessionId}:`, awaitingStart: false }, |
| 2256 | ); |
| 2257 | turn.before = subagent.queued; |
| 2258 | subagent.queued = undefined; |
| 2259 | child.active = turn; |
| 2260 | child.sessionScopedBackground = false; |
| 2261 | yield* emit({ |
| 2262 | type: "node.updated", |
| 2263 | driver, |
| 2264 | node: { |
| 2265 | id: rootNodeId, |
| 2266 | threadId: turn.input.threadId, |
| 2267 | runId: null, |
| 2268 | parentNodeId: null, |
| 2269 | rootNodeId, |
| 2270 | kind: "root_turn", |
| 2271 | status: "running", |
| 2272 | countsForRun: false, |
| 2273 | providerThreadId: child.providerThread.id, |
| 2274 | providerTurnId: providerTurn.id, |
| 2275 | nativeItemRef: ref(nativeTurnId, "weak"), |
| 2276 | runtimeRequestId: null, |
| 2277 | checkpointScopeId: null, |
| 2278 | startedAt, |
| 2279 | completedAt: null, |
| 2280 | }, |
| 2281 | }); |
| 2282 | yield* emitProviderTurn(child, turn, providerTurn); |
| 2283 | const prompt = subagent.prompt; |
| 2284 | subagent.prompt = undefined; |
| 2285 | if (prompt !== undefined && prompt.length > 0) { |
| 2286 | const nativeId = `${nativeTurnId}:prompt`; |
| 2287 | const artifacts = makeSubagentConversationArtifacts({ |
| 2288 | messageId: idAllocator.derive.messageFromProviderItem({ driver, nativeItemId: nativeId }), |
| 2289 | senderThreadId: subagent.call.turn.input.threadId, |
| 2290 | turnItemId: idAllocator.derive.turnItemFromProviderItem({ |
| 2291 | driver, |
| 2292 | nativeItemId: nativeId, |
| 2293 | }), |
| 2294 | threadId: turn.input.threadId, |
| 2295 | rootNodeId, |
| 2296 | providerThreadId: child.providerThread.id, |
| 2297 | providerTurnId: providerTurn.id, |
| 2298 | nativeItemRef: ref(nativeId, "weak"), |
| 2299 | role: "user", |
| 2300 | text: prompt, |
| 2301 | ordinal: ordinalOf(turn, nativeId), |
| 2302 | now: startedAt, |
| 2303 | }); |
| 2304 | yield* emit({ type: "message.updated", driver, message: artifacts.message }); |
| 2305 | yield* emit({ type: "turn_item.updated", driver, turnItem: artifacts.turnItem }); |
| 2306 | } |
| 2307 | }); |
| 2308 | |
| 2309 | const offerWake = Effect.fnUntraced(function* (state: ThreadState, wake: Wake) { |
| 2310 | const route = state.providerThread.appThreadId; |
| 2311 | if (route === null || wake.messageId === undefined) return; |
| 2312 | const notification = backgroundWorkNotification(wake.reports); |
| 2313 | yield* continuationRequests.offer({ |
| 2314 | threadId: route, |
| 2315 | providerThreadId: state.providerThread.id, |
| 2316 | driver, |
| 2317 | detail: wake.detail, |
| 2318 | messageId: wake.messageId, |
| 2319 | ...(notification === null ? {} : { notification }), |
| 2320 | dispatchIfCurrent: (dispatch) => |
| 2321 | wake.dropped ? Effect.succeedNone : Effect.asSome(dispatch), |
| 2322 | }); |
| 2323 | }); |
| 2324 | |
| 2325 | const finishTurn = Effect.fnUntraced(function* ( |
| 2326 | state: ThreadState, |
| 2327 | terminal: TurnTerminal, |
| 2328 | threadDisposition: "reusable" | "broken" = "reusable", |
| 2329 | ) { |
| 2330 | const turn = state.active; |
| 2331 | if (turn === undefined) return; |
| 2332 | state.active = undefined; |
| 2333 | for (const inboxID of turn.steers) state.strandedSteers.add(inboxID); |
| 2334 | for (const entry of pending.values()) { |
| 2335 | const background = callsAbove(entry.sessionId).some((call) => call.background); |
| 2336 | if ( |
| 2337 | entry.sessionId === state.sessionId || |
| 2338 | (entry.turn === turn && !(background && terminal.status !== "failed")) |
| 2339 | ) { |
| 2340 | yield* settleRequest(entry, "cancelled"); |
| 2341 | } |
| 2342 | } |
| 2343 | const completedAt = yield* DateTime.now; |
| 2344 | for (const open of turn.texts.values()) { |
| 2345 | yield* emitText(state, turn, open.block, open.kind, (text) => text, true); |
| 2346 | } |
| 2347 | for (const id of turn.tools.keys()) { |
| 2348 | if ([...state.imageJobs.values()].some((job) => job.turn === turn && job.toolId === id)) |
| 2349 | continue; |
| 2350 | yield* emitTool( |
| 2351 | state, |
| 2352 | turn, |
| 2353 | id, |
| 2354 | terminal.status === "completed" ? "completed" : "interrupted", |
| 2355 | ); |
| 2356 | } |
| 2357 | for (const call of Array.from(state.calls.values())) { |
| 2358 | if (call.turn !== turn) continue; |
| 2359 | if (call.background && terminal.status !== "failed") continue; |
| 2360 | yield* settleCall(call, terminal.status === "completed" ? "completed" : terminal.status); |
| 2361 | } |
| 2362 | if (state.subagent !== undefined) { |
| 2363 | yield* emit({ |
| 2364 | type: "node.updated", |
| 2365 | driver, |
| 2366 | node: { |
| 2367 | id: turn.input.rootNodeId, |
| 2368 | threadId: turn.input.threadId, |
| 2369 | runId: null, |
| 2370 | parentNodeId: null, |
| 2371 | rootNodeId: turn.input.rootNodeId, |
| 2372 | kind: "root_turn", |
| 2373 | status: terminal.status, |
| 2374 | countsForRun: false, |
| 2375 | providerThreadId: state.providerThread.id, |
| 2376 | providerTurnId: turn.providerTurn.id, |
| 2377 | nativeItemRef: turn.providerTurn.nativeTurnRef, |
| 2378 | runtimeRequestId: null, |
| 2379 | checkpointScopeId: null, |
| 2380 | startedAt: turn.providerTurn.startedAt, |
| 2381 | completedAt, |
| 2382 | }, |
| 2383 | }); |
| 2384 | } |
| 2385 | yield* emitCompaction(state, turn, terminal.status === "failed" ? "failed" : "interrupted"); |
| 2386 | yield* emitRetry( |
| 2387 | state, |
| 2388 | turn, |
| 2389 | terminal.status, |
| 2390 | terminal.status === "failed" ? terminal.failure : undefined, |
| 2391 | ); |
| 2392 | const window = windowOf(turn.input.runtimePolicy.cwd, turn.input.modelSelection.model); |
| 2393 | const lastStep = turn.lastStep; |
| 2394 | yield* emitProviderTurn(state, turn, { |
| 2395 | ...turn.providerTurn, |
| 2396 | status: terminal.status, |
| 2397 | completedAt, |
| 2398 | turnTokenUsage: turnTokenUsage(turn, terminal.status), |
| 2399 | ...(lastStep === undefined |
| 2400 | ? {} |
| 2401 | : { |
| 2402 | tokenUsage: { |
| 2403 | usedTokens: |
| 2404 | lastStep.input + lastStep.cache.read + lastStep.cache.write + lastStep.output, |
| 2405 | maxTokens: window ?? null, |
| 2406 | inputTokens: lastStep.input + lastStep.cache.read + lastStep.cache.write, |
| 2407 | cachedInputTokens: lastStep.cache.read, |
| 2408 | outputTokens: lastStep.output, |
| 2409 | reasoningOutputTokens: lastStep.reasoning, |
| 2410 | updatedAt: DateTime.formatIso(completedAt), |
| 2411 | }, |
| 2412 | }), |
| 2413 | }); |
| 2414 | // Subagent turns are runless; their calls own settlement. |
| 2415 | if (state.subagent !== undefined) { |
| 2416 | const call = state.subagent.call; |
| 2417 | for (const attached of callsAttachedTo(state)) { |
| 2418 | if (attached.run === state.subagent.turns) attached.answer = turn.answer; |
| 2419 | } |
| 2420 | if (!call.background && terminal.status !== "completed") { |
| 2421 | yield* settleCall(call, terminal.status); |
| 2422 | } |
| 2423 | if (terminal.status === "failed") { |
| 2424 | // Background calls settle when the parent reads a report; failed children have no report. |
| 2425 | // Fail every attached call so earlier background calls cannot leave phantom work, |
| 2426 | // regardless of which call joined last or is still foreground. |
| 2427 | for (const attached of callsAttachedTo(state)) { |
| 2428 | yield* settleCall(attached, terminal.status, terminal.failure.message); |
| 2429 | } |
| 2430 | } |
| 2431 | return; |
| 2432 | } |
| 2433 | state.providerThread = { |
| 2434 | ...state.providerThread, |
| 2435 | status: threadDisposition === "broken" ? "error" : "idle", |
| 2436 | updatedAt: completedAt, |
| 2437 | }; |
| 2438 | yield* emitProviderThread(state); |
| 2439 | const anyActive = [...threads.values()].some( |
| 2440 | (candidate) => candidate.subagent === undefined && candidate.active !== undefined, |
| 2441 | ); |
| 2442 | yield* setSessionStatus(pending.size > 0 ? "waiting" : anyActive ? "running" : "ready", null); |
| 2443 | const base = { |
| 2444 | type: "turn.terminal" as const, |
| 2445 | driver, |
| 2446 | // Native forks change thread IDs; terminal events must retain the recorded start identity. |
| 2447 | providerThreadId: turn.providerTurn.providerThreadId, |
| 2448 | providerTurnId: turn.providerTurn.id, |
| 2449 | runOrdinal: turn.input.runOrdinal, |
| 2450 | threadDisposition, |
| 2451 | ...retainedRequestsOf(turn), |
| 2452 | }; |
| 2453 | yield* emit( |
| 2454 | terminal.status === "failed" |
| 2455 | ? { |
| 2456 | ...base, |
| 2457 | status: "failed", |
| 2458 | failure: terminal.failure, |
| 2459 | failureItemOrdinal: ordinalOf(turn, `terminal-failure:${turn.providerTurn.id}`), |
| 2460 | ...(turn.retry === undefined |
| 2461 | ? {} |
| 2462 | : { retry: turn.retry.retry, retryStartedAt: turn.retry.startedAt }), |
| 2463 | } |
| 2464 | : { ...base, status: terminal.status, failure: null }, |
| 2465 | ); |
| 2466 | // Cold servers list models lazily; refresh unknown windows off-stream for the next turn. |
| 2467 | if (window === undefined) { |
| 2468 | yield* Effect.forkIn(readModels(directoryOf(turn.input.runtimePolicy.cwd)), sessionScope); |
| 2469 | } |
| 2470 | }); |
| 2471 | |
| 2472 | // OpenCode waits forever on unanswered requests; stop that run and keep its end from settling the next. |
| 2473 | const abandonRequest = Effect.fnUntraced(function* (state: ThreadState, reason: string) { |
| 2474 | yield* Effect.logWarning("Could not answer an OpenCode request; ending its turn.", { |
| 2475 | reason, |
| 2476 | }); |
| 2477 | if (state.active === undefined) return; |
| 2478 | markUnsettled(state); |
| 2479 | yield* finishTurn(state, { |
| 2480 | status: "failed", |
| 2481 | failure: makeProviderFailure({ |
| 2482 | message: "OpenCode is waiting on a request T3 Code couldn't answer.", |
| 2483 | class: "provider_error", |
| 2484 | }), |
| 2485 | }); |
| 2486 | yield* client.session |
| 2487 | .interrupt({ sessionID: Session.ID.make(state.sessionId) }) |
| 2488 | .pipe(Effect.timeout("2 seconds"), Effect.ignore({ log: true })); |
| 2489 | }); |
| 2490 | |
| 2491 | const forgetRequest = Effect.fnUntraced(function* (entry: PendingRequest) { |
| 2492 | if (!pending.delete(entry.request.id)) return false; |
| 2493 | if (pending.size === 0 && session.status === "waiting") { |
| 2494 | yield* setSessionStatus("running", null); |
| 2495 | } |
| 2496 | return true; |
| 2497 | }); |
| 2498 | |
| 2499 | // The orchestrator already recorded T3-owned answers; only forget them here. |
| 2500 | const settleRequest = Effect.fnUntraced(function* ( |
| 2501 | entry: PendingRequest, |
| 2502 | status: "resolved" | "cancelled", |
| 2503 | ) { |
| 2504 | if (!(yield* forgetRequest(entry)) || entry.answering) return; |
| 2505 | const now = yield* DateTime.now; |
| 2506 | const itemStatus = status === "resolved" ? "completed" : "cancelled"; |
| 2507 | yield* emit({ |
| 2508 | type: "runtime_request.updated", |
| 2509 | driver, |
| 2510 | threadId: entry.turn.input.threadId, |
| 2511 | runtimeRequest: { ...entry.request, status, resolvedAt: now }, |
| 2512 | }); |
| 2513 | yield* emit({ |
| 2514 | type: "node.updated", |
| 2515 | driver, |
| 2516 | node: { ...entry.node, status: itemStatus, completedAt: now }, |
| 2517 | }); |
| 2518 | yield* emit({ |
| 2519 | type: "turn_item.updated", |
| 2520 | driver, |
| 2521 | turnItem: { ...entry.item, status: itemStatus, completedAt: now, updatedAt: now }, |
| 2522 | }); |
| 2523 | }); |
| 2524 | |
| 2525 | const stopStaleRequest = ( |
| 2526 | sessionId: string, |
| 2527 | native: { readonly type: "permission" | "form"; readonly id: string }, |
| 2528 | ): Effect.Effect<void> => |
| 2529 | native.type === "permission" |
| 2530 | ? client.permission |
| 2531 | .reply({ |
| 2532 | sessionID: Session.ID.make(sessionId), |
| 2533 | requestID: Permission.ID.make(native.id), |
| 2534 | decision: "reject", |
| 2535 | }) |
| 2536 | .pipe( |
| 2537 | Effect.catchTags(permissionGone), |
| 2538 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 2539 | Effect.ignore({ log: true }), |
| 2540 | ) |
| 2541 | : client.session.form |
| 2542 | .cancel({ sessionID: sessionId, formID: Form.ID.make(native.id) }) |
| 2543 | .pipe( |
| 2544 | Effect.catchTags(formGone), |
| 2545 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 2546 | Effect.ignore({ log: true }), |
| 2547 | ); |
| 2548 | |
| 2549 | // T3 expired pre-load requests and no longer shows them; stop them so OpenCode cannot wait forever. |
| 2550 | const stopLeftoverRequests = Effect.fnUntraced(function* (state: ThreadState) { |
| 2551 | const sessionID = Session.ID.make(state.sessionId); |
| 2552 | const listed = yield* Effect.all([ |
| 2553 | client.permission.list({ sessionID }), |
| 2554 | client.session.form.list({ sessionID }), |
| 2555 | ]).pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option); |
| 2556 | if (listed._tag === "None") { |
| 2557 | return yield* Effect.logWarning("Could not list an OpenCode session's open requests."); |
| 2558 | } |
| 2559 | const [permissions, forms] = listed.value; |
| 2560 | if (permissions.length === 0 && forms.length === 0) return; |
| 2561 | markUnsettled(state); |
| 2562 | for (const request of permissions) { |
| 2563 | yield* stopStaleRequest(state.sessionId, { type: "permission", id: request.id }); |
| 2564 | } |
| 2565 | for (const form of forms) { |
| 2566 | yield* stopStaleRequest(state.sessionId, { type: "form", id: form.id }); |
| 2567 | } |
| 2568 | }); |
| 2569 | |
| 2570 | const showRequest = Effect.fnUntraced(function* ( |
| 2571 | sessionId: string, |
| 2572 | native: PendingRequest["native"], |
| 2573 | body: |
| 2574 | | { |
| 2575 | readonly type: "approval_request"; |
| 2576 | readonly requestKind: Extract< |
| 2577 | OrchestrationV2TurnItem, |
| 2578 | { type: "approval_request" } |
| 2579 | >["requestKind"]; |
| 2580 | readonly prompt: string; |
| 2581 | readonly options: Extract< |
| 2582 | OrchestrationV2TurnItem, |
| 2583 | { type: "approval_request" } |
| 2584 | >["options"]; |
| 2585 | } |
| 2586 | | { |
| 2587 | readonly type: "user_input_request"; |
| 2588 | readonly questions: ReadonlyArray<OrchestrationV2UserInputQuestion>; |
| 2589 | }, |
| 2590 | ) { |
| 2591 | const target = requestTurn(sessionId); |
| 2592 | if (target === undefined) return; |
| 2593 | const { state, turn } = target; |
| 2594 | if ([...pending.values()].some((entry) => entry.native.id === native.id)) return; |
| 2595 | const now = yield* DateTime.now; |
| 2596 | const requestId = yield* idAllocator.allocate.runtimeRequest({ |
| 2597 | driver, |
| 2598 | providerTurnId: turn.providerTurn.id, |
| 2599 | nativeRequestId: native.id, |
| 2600 | }); |
| 2601 | const nodeId = idAllocator.derive.approvalNode({ requestId }); |
| 2602 | const request: OrchestrationV2RuntimeRequest = { |
| 2603 | id: requestId, |
| 2604 | nodeId, |
| 2605 | providerTurnId: turn.providerTurn.id, |
| 2606 | nativeRequestRef: ref(native.id), |
| 2607 | kind: body.type === "approval_request" ? body.requestKind : "user_input", |
| 2608 | status: "pending", |
| 2609 | responseCapability: { type: "live", providerSessionId: input.providerSessionId }, |
| 2610 | createdAt: now, |
| 2611 | resolvedAt: null, |
| 2612 | }; |
| 2613 | const node: OrchestrationV2ExecutionNode = { |
| 2614 | id: nodeId, |
| 2615 | threadId: turn.input.threadId, |
| 2616 | runId: turn.input.runId, |
| 2617 | parentNodeId: turn.input.rootNodeId, |
| 2618 | rootNodeId: turn.input.rootNodeId, |
| 2619 | kind: body.type, |
| 2620 | status: "waiting", |
| 2621 | countsForRun: false, |
| 2622 | providerThreadId: state.providerThread.id, |
| 2623 | providerTurnId: turn.providerTurn.id, |
| 2624 | nativeItemRef: ref(native.id), |
| 2625 | runtimeRequestId: requestId, |
| 2626 | checkpointScopeId: null, |
| 2627 | startedAt: now, |
| 2628 | completedAt: null, |
| 2629 | }; |
| 2630 | const base = { |
| 2631 | id: idAllocator.derive.approvalTurnItem({ requestId }), |
| 2632 | threadId: turn.input.threadId, |
| 2633 | runId: turn.input.runId, |
| 2634 | nodeId, |
| 2635 | providerThreadId: state.providerThread.id, |
| 2636 | providerTurnId: turn.providerTurn.id, |
| 2637 | nativeItemRef: ref(native.id), |
| 2638 | parentItemId: null, |
| 2639 | ordinal: ordinalOf(turn, native.id), |
| 2640 | status: "waiting" as const, |
| 2641 | startedAt: now, |
| 2642 | completedAt: null, |
| 2643 | updatedAt: now, |
| 2644 | }; |
| 2645 | const item: OrchestrationV2TurnItem = |
| 2646 | body.type === "approval_request" |
| 2647 | ? { |
| 2648 | ...base, |
| 2649 | title: native.type === "permission" ? native.action : null, |
| 2650 | type: "approval_request", |
| 2651 | requestId, |
| 2652 | requestKind: body.requestKind, |
| 2653 | prompt: body.prompt, |
| 2654 | ...(body.options === undefined ? {} : { options: body.options }), |
| 2655 | } |
| 2656 | : { |
| 2657 | ...base, |
| 2658 | title: "User input", |
| 2659 | type: "user_input_request", |
| 2660 | requestId, |
| 2661 | questions: body.questions, |
| 2662 | }; |
| 2663 | pending.set(requestId, { |
| 2664 | request, |
| 2665 | item, |
| 2666 | node, |
| 2667 | state, |
| 2668 | turn, |
| 2669 | sessionId, |
| 2670 | answering: false, |
| 2671 | native, |
| 2672 | }); |
| 2673 | yield* emit({ type: "node.updated", driver, node }); |
| 2674 | yield* emit({ type: "turn_item.updated", driver, turnItem: item }); |
| 2675 | // A response can commit as soon as the actionable request is published. |
| 2676 | yield* emit({ |
| 2677 | type: "runtime_request.updated", |
| 2678 | driver, |
| 2679 | threadId: turn.input.threadId, |
| 2680 | runtimeRequest: request, |
| 2681 | }); |
| 2682 | yield* setSessionStatus("waiting", null); |
| 2683 | }); |
| 2684 | |
| 2685 | const onPermissionAsked = Effect.fnUntraced(function* (data: Permission.Request) { |
| 2686 | const turn = threads.get(data.sessionID)?.active; |
| 2687 | const toolName = |
| 2688 | data.source === undefined ? undefined : turn?.tools.get(data.source.id)?.name; |
| 2689 | const save = data.save ?? []; |
| 2690 | yield* showRequest( |
| 2691 | data.sessionID, |
| 2692 | { type: "permission", id: data.id, action: data.action, resources: data.resources, save }, |
| 2693 | { |
| 2694 | type: "approval_request", |
| 2695 | requestKind: openCodePermissionRequestKind(data.action, toolName), |
| 2696 | prompt: data.resources.length === 0 ? data.action : data.resources.join("\n"), |
| 2697 | options: [ |
| 2698 | { decision: "cancel", label: "Cancel" }, |
| 2699 | { decision: "decline", label: "Decline" }, |
| 2700 | ...(save.length > 0 |
| 2701 | ? [ |
| 2702 | { |
| 2703 | decision: "acceptForSession" as const, |
| 2704 | label: sessionGrantLabel(data.action, save), |
| 2705 | }, |
| 2706 | ] |
| 2707 | : []), |
| 2708 | { decision: "accept", label: "Approve" }, |
| 2709 | ], |
| 2710 | }, |
| 2711 | ); |
| 2712 | }); |
| 2713 | |
| 2714 | const onFormCreated = Effect.fnUntraced(function* (form: NativeForm) { |
| 2715 | const target = requestTurn(form.sessionID); |
| 2716 | if (target === undefined) return; |
| 2717 | const { state } = target; |
| 2718 | const mapped = formQuestions(form); |
| 2719 | if ("questions" in mapped) { |
| 2720 | return yield* showRequest( |
| 2721 | form.sessionID, |
| 2722 | { type: "form", id: form.id, form }, |
| 2723 | { type: "user_input_request", questions: mapped.questions }, |
| 2724 | ); |
| 2725 | } |
| 2726 | // Cancel reports user Stop; record failure here and skip that execution end. |
| 2727 | yield* Effect.logWarning("Declined an OpenCode form T3 Code cannot show.", { |
| 2728 | reason: mapped.unsupported, |
| 2729 | }); |
| 2730 | const cancelled = yield* deliver( |
| 2731 | client.session.form.cancel({ sessionID: form.sessionID, formID: form.id }), |
| 2732 | ); |
| 2733 | // Cancel stops the asking child's session, not its parent; child sessions have no Stop end to skip. |
| 2734 | const asker = threads.get(form.sessionID) ?? state; |
| 2735 | if (!cancelled) return yield* abandonRequest(asker, "form cancel failed"); |
| 2736 | if (asker.subagent === undefined) markUnsettled(asker); |
| 2737 | yield* finishTurn(asker, { |
| 2738 | status: "failed", |
| 2739 | failure: makeProviderFailure({ |
| 2740 | message: `OpenCode asked for ${mapped.unsupported}, which T3 Code can't show. The question was declined.`, |
| 2741 | class: "provider_error", |
| 2742 | }), |
| 2743 | }); |
| 2744 | }); |
| 2745 | |
| 2746 | const onAsked = Effect.fnUntraced(function* ( |
| 2747 | asked: |
| 2748 | | { readonly type: "permission"; readonly request: Permission.Request } |
| 2749 | | { readonly type: "form"; readonly form: NativeForm }, |
| 2750 | ) { |
| 2751 | const asking = asked.type === "permission" ? asked.request.sessionID : asked.form.sessionID; |
| 2752 | if (strays.has(asking)) { |
| 2753 | return yield* stopStaleRequest( |
| 2754 | asking, |
| 2755 | asked.type === "permission" |
| 2756 | ? { type: "permission", id: asked.request.id } |
| 2757 | : { type: "form", id: asked.form.id }, |
| 2758 | ); |
| 2759 | } |
| 2760 | const state = ownerOf(asking); |
| 2761 | if (state === undefined) return; |
| 2762 | const target = requestTurn(asking); |
| 2763 | if (target !== undefined && !target.turn.awaitingStart) { |
| 2764 | if (asked.type === "permission") return yield* onPermissionAsked(asked.request); |
| 2765 | return yield* onFormCreated(asked.form); |
| 2766 | } |
| 2767 | if (state.unsettled || state.active?.awaitingStart === true) { |
| 2768 | yield* stopStaleRequest( |
| 2769 | asking, |
| 2770 | asked.type === "permission" |
| 2771 | ? { type: "permission", id: asked.request.id } |
| 2772 | : { type: "form", id: asked.form.id }, |
| 2773 | ); |
| 2774 | } |
| 2775 | }); |
| 2776 | |
| 2777 | const sessionOfEvent = (event: OpenCode2Client.OpenCode2StreamEvent) => |
| 2778 | event.type === "unreadable.execution.ended" || event.type === "unreadable.execution.started" |
| 2779 | ? event.sessionID |
| 2780 | : event.type === "form.created" |
| 2781 | ? event.data.form.sessionID |
| 2782 | : "sessionID" in event.data && typeof event.data.sessionID === "string" |
| 2783 | ? event.data.sessionID |
| 2784 | : undefined; |
| 2785 | |
| 2786 | const executionEnd = (type: string) => |
| 2787 | type === "session.execution.succeeded" || |
| 2788 | type === "session.execution.failed" || |
| 2789 | type === "session.execution.interrupted"; |
| 2790 | |
| 2791 | const startCall = Effect.fnUntraced(function* ( |
| 2792 | state: ThreadState, |
| 2793 | turn: ActiveTurn, |
| 2794 | toolId: string, |
| 2795 | ) { |
| 2796 | const nativeId = `${turn.scope}${toolId}`; |
| 2797 | const call: SubagentCall = { |
| 2798 | toolId, |
| 2799 | nativeId, |
| 2800 | state, |
| 2801 | turn, |
| 2802 | ordinal: ordinalOf(turn, nativeId), |
| 2803 | startedAt: yield* DateTime.now, |
| 2804 | prompt: "", |
| 2805 | title: null, |
| 2806 | agent: undefined, |
| 2807 | model: null, |
| 2808 | background: false, |
| 2809 | run: undefined, |
| 2810 | answer: undefined, |
| 2811 | child: undefined, |
| 2812 | status: "running", |
| 2813 | result: null, |
| 2814 | completedAt: null, |
| 2815 | }; |
| 2816 | turn.usedSubagents = true; |
| 2817 | state.calls.set(toolId, call); |
| 2818 | yield* emitSubagent(call); |
| 2819 | }); |
| 2820 | |
| 2821 | const onTurnEvent = Effect.fnUntraced(function* ( |
| 2822 | state: ThreadState, |
| 2823 | turn: ActiveTurn, |
| 2824 | event: OpenCode2Client.OpenCode2StreamEvent, |
| 2825 | ) { |
| 2826 | // OpenCode sends nothing when a retry goes through; the provider's first output marks it. |
| 2827 | if ( |
| 2828 | turn.retry !== undefined && |
| 2829 | (event.type === "session.text.started" || |
| 2830 | event.type === "session.reasoning.started" || |
| 2831 | event.type === "session.tool.input.started") |
| 2832 | ) { |
| 2833 | yield* emitRetry(state, turn, "completed"); |
| 2834 | turn.retry = undefined; |
| 2835 | } |
| 2836 | switch (event.type) { |
| 2837 | case "session.text.started": |
| 2838 | case "session.reasoning.started": |
| 2839 | case "session.text.delta": |
| 2840 | case "session.reasoning.delta": |
| 2841 | case "session.text.ended": |
| 2842 | case "session.reasoning.ended": { |
| 2843 | const data = event.data; |
| 2844 | const kind = event.type.startsWith("session.text.") ? "text" : "reasoning"; |
| 2845 | return yield* emitText(state, turn, data, kind, (text) => |
| 2846 | "delta" in data ? text + data.delta : "text" in data ? data.text : text, |
| 2847 | ); |
| 2848 | } |
| 2849 | case "session.tool.input.started": |
| 2850 | turn.closingText = undefined; |
| 2851 | if (event.data.name === "question") return; |
| 2852 | if (event.data.name === "subagent") return yield* startCall(state, turn, event.data.id); |
| 2853 | turn.tools.set(event.data.id, { name: event.data.name, input: {} }); |
| 2854 | turn.startedAt.set(event.data.id, yield* DateTime.now); |
| 2855 | return yield* emitTool(state, turn, event.data.id, "running"); |
| 2856 | case "session.tool.called": { |
| 2857 | const call = state.calls.get(event.data.id); |
| 2858 | if (call !== undefined) { |
| 2859 | const { input } = event.data; |
| 2860 | call.prompt = stringField(input, "prompt") ?? call.prompt; |
| 2861 | call.title = stringField(input, "description") ?? call.title; |
| 2862 | call.agent = stringField(input, "agent"); |
| 2863 | call.model = stringField(input, "model") ?? call.model; |
| 2864 | call.background = input["background"] === true; |
| 2865 | return yield* emitSubagent(call); |
| 2866 | } |
| 2867 | const tool = turn.tools.get(event.data.id); |
| 2868 | if (tool !== undefined) tool.input = event.data.input; |
| 2869 | return yield* emitTool(state, turn, event.data.id, "running"); |
| 2870 | } |
| 2871 | case "session.tool.progress": { |
| 2872 | const call = state.calls.get(event.data.id); |
| 2873 | const childId = stringField(event.data.metadata, "sessionID"); |
| 2874 | if (call !== undefined && childId !== undefined) yield* attachChild(call, childId); |
| 2875 | return; |
| 2876 | } |
| 2877 | case "session.tool.success": { |
| 2878 | const call = state.calls.get(event.data.id); |
| 2879 | if (call !== undefined) { |
| 2880 | const childId = stringField(event.data.metadata, "sessionID"); |
| 2881 | if (childId !== undefined) yield* attachChild(call, childId); |
| 2882 | // Background and joined-background calls return at launch; reports settle them. |
| 2883 | if (event.data.metadata?.["status"] === "running") { |
| 2884 | if (call.background) return; |
| 2885 | call.background = true; |
| 2886 | return yield* emitSubagent(call); |
| 2887 | } |
| 2888 | return yield* settleCall(call, "completed", subagentOutput(textOf(event.data.content))); |
| 2889 | } |
| 2890 | const shellId = stringField(event.data.metadata, "shellID"); |
| 2891 | const tool = turn.tools.get(event.data.id); |
| 2892 | if ( |
| 2893 | shellId !== undefined && |
| 2894 | tool?.name === "shell" && |
| 2895 | event.data.metadata?.["exit"] === undefined && |
| 2896 | event.data.metadata?.["signal"] === undefined && |
| 2897 | event.data.metadata?.["timeout"] !== true |
| 2898 | ) { |
| 2899 | shells.set(shellId, { |
| 2900 | state, |
| 2901 | turn, |
| 2902 | toolId: event.data.id, |
| 2903 | tool, |
| 2904 | command: stringField(tool.input, "command") ?? "Shell command", |
| 2905 | ...(replaying?.awaited.has(shellId) === true ? { awaited: true } : {}), |
| 2906 | running: true, |
| 2907 | output: "", |
| 2908 | cursor: 0, |
| 2909 | }); |
| 2910 | const known = shellInfo.get(shellId); |
| 2911 | const ended = replaying?.ended.get(shellId); |
| 2912 | const tracked = shells.get(shellId)!; |
| 2913 | tracked.running = |
| 2914 | ended === undefined && (known === undefined || known.status === "running"); |
| 2915 | yield* readShellOutput(shellId, !tracked.running).pipe(Effect.ignore({ log: true })); |
| 2916 | yield* emitShell( |
| 2917 | shellId, |
| 2918 | tracked.running |
| 2919 | ? "running" |
| 2920 | : (ended?.status ?? |
| 2921 | (known?.status === "killed" |
| 2922 | ? "interrupted" |
| 2923 | : known?.exit === 0 |
| 2924 | ? "completed" |
| 2925 | : "failed")), |
| 2926 | ended?.exit ?? known?.exit, |
| 2927 | ); |
| 2928 | if (ended !== undefined) shells.delete(shellId); |
| 2929 | yield* syncRosterAncestors(state); |
| 2930 | return; |
| 2931 | } |
| 2932 | if (shellId !== undefined) shellInfo.delete(shellId); |
| 2933 | const output = textOf(event.data.content); |
| 2934 | yield* emitTool(state, turn, event.data.id, "completed", { |
| 2935 | output, |
| 2936 | files: event.data.content.flatMap((part) => (part.type === "file" ? [part] : [])), |
| 2937 | metadata: event.data.metadata, |
| 2938 | }); |
| 2939 | if ( |
| 2940 | ![...state.imageJobs.values()].some( |
| 2941 | (job) => job.turn === turn && job.toolId === event.data.id, |
| 2942 | ) |
| 2943 | ) |
| 2944 | turn.tools.delete(event.data.id); |
| 2945 | return; |
| 2946 | } |
| 2947 | case "session.tool.failed": { |
| 2948 | const aborted = event.data.error.type === "aborted"; |
| 2949 | const call = state.calls.get(event.data.id); |
| 2950 | if (call !== undefined) { |
| 2951 | return yield* settleCall( |
| 2952 | call, |
| 2953 | aborted ? "interrupted" : "failed", |
| 2954 | event.data.error.message, |
| 2955 | ); |
| 2956 | } |
| 2957 | yield* emitTool(state, turn, event.data.id, aborted ? "interrupted" : "failed", { |
| 2958 | output: event.data.error.message, |
| 2959 | metadata: event.data.metadata, |
| 2960 | }); |
| 2961 | turn.tools.delete(event.data.id); |
| 2962 | return; |
| 2963 | } |
| 2964 | case "session.compaction.started": |
| 2965 | turn.compaction = { |
| 2966 | nativeId: `${turn.providerTurn.id}:compaction:${turn.compactions++}`, |
| 2967 | startedAt: yield* DateTime.now, |
| 2968 | }; |
| 2969 | return yield* emitCompaction(state, turn, "running"); |
| 2970 | case "session.compaction.ended": |
| 2971 | return yield* emitCompaction(state, turn, "completed", event.data.text); |
| 2972 | case "session.compaction.failed": |
| 2973 | return yield* emitCompaction(state, turn, "failed"); |
| 2974 | case "session.step.started": |
| 2975 | turn.startedSteps += 1; |
| 2976 | turn.models.add(`${event.data.model.providerID}/${event.data.model.id}`); |
| 2977 | return; |
| 2978 | case "session.step.ended": |
| 2979 | case "session.step.failed": { |
| 2980 | const tokens = event.data.tokens; |
| 2981 | if (tokens === undefined) return; |
| 2982 | turn.steps += 1; |
| 2983 | turn.lastStep = tokens; |
| 2984 | turn.usage.input += tokens.input + tokens.cache.read + tokens.cache.write; |
| 2985 | turn.usage.cached += tokens.cache.read; |
| 2986 | turn.usage.cacheWrite += tokens.cache.write; |
| 2987 | turn.usage.output += tokens.output + tokens.reasoning; |
| 2988 | turn.usage.reasoning += tokens.reasoning; |
| 2989 | return; |
| 2990 | } |
| 2991 | case "session.retry.scheduled": |
| 2992 | return yield* updateRetry(state, turn, event.data, event.data.at - event.created); |
| 2993 | case "session.execution.started": |
| 2994 | turn.heldEnd = undefined; |
| 2995 | return; |
| 2996 | case "session.execution.succeeded": |
| 2997 | return yield* endExecution(state, turn, { |
| 2998 | status: turn.interrupted ? "interrupted" : "completed", |
| 2999 | }); |
| 3000 | case "session.execution.interrupted": |
| 3001 | return yield* endExecution(state, turn, { status: "interrupted" }); |
| 3002 | case "session.execution.failed": { |
| 3003 | const { type, message, status, response } = event.data.error; |
| 3004 | return yield* endExecution(state, turn, { |
| 3005 | status: "failed", |
| 3006 | failure: makeProviderFailure({ |
| 3007 | message: readableProviderErrorMessage(message, status, response?.body), |
| 3008 | code: type, |
| 3009 | class: isUsageLimit(event.data.error) ? "usage_limit" : "provider_error", |
| 3010 | resetAt: claudeUsageLimit(message)?.resetAt ?? null, |
| 3011 | }), |
| 3012 | }); |
| 3013 | } |
| 3014 | default: |
| 3015 | return; |
| 3016 | } |
| 3017 | }); |
| 3018 | |
| 3019 | const takeReports = Effect.fnUntraced(function* (state: ThreadState) { |
| 3020 | const delivered = [...state.reports.values()]; |
| 3021 | state.reports.clear(); |
| 3022 | const stopped = |
| 3023 | delivered.length > 0 && |
| 3024 | delivered.every((entry) => state.stoppedChildren.has(entry.childId)); |
| 3025 | for (const entry of delivered) state.stoppedChildren.delete(entry.childId); |
| 3026 | if (stopped) { |
| 3027 | markUnsettled(state); |
| 3028 | yield* client.session |
| 3029 | .interrupt({ sessionID: Session.ID.make(state.sessionId) }) |
| 3030 | .pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore({ log: true })); |
| 3031 | } |
| 3032 | return { delivered, stopped }; |
| 3033 | }); |
| 3034 | |
| 3035 | const onWake = Effect.fnUntraced(function* (state: ThreadState) { |
| 3036 | const { delivered, stopped } = yield* takeReports(state); |
| 3037 | if (stopped) return; |
| 3038 | const route = state.providerThread.appThreadId; |
| 3039 | // History begins at whichever OpenCode queued first: a report or another client's prompt. |
| 3040 | // A prompt leads only this wake, so one dropped undelivered cannot move a later boundary. |
| 3041 | const leading = [...state.externalPrompts].find(([, prompt]) => prompt.leads)?.[0]; |
| 3042 | for (const prompt of state.externalPrompts.values()) prompt.leads = false; |
| 3043 | const wake: Wake = { |
| 3044 | messageId: |
| 3045 | route === null |
| 3046 | ? undefined |
| 3047 | : yield* idAllocator.allocate.message({ threadId: route, ordinal: 0 }), |
| 3048 | events: [], |
| 3049 | running: true, |
| 3050 | reports: delivered.map((entry) => entry.report), |
| 3051 | detail: delivered.length === 0 ? null : delivered.map((entry) => entry.text).join("\n\n"), |
| 3052 | dropped: false, |
| 3053 | after: delivered.at(-1)?.inboxId, |
| 3054 | first: leading ?? delivered[0]?.inboxId, |
| 3055 | children: new Set(), |
| 3056 | awaited: new Set(), |
| 3057 | ended: new Map(), |
| 3058 | }; |
| 3059 | state.wakes.push(wake); |
| 3060 | yield* Effect.logInfo("OpenCode started a turn on its own; asking for a continuation.", { |
| 3061 | providerThreadId: state.providerThread.id, |
| 3062 | }); |
| 3063 | yield* offerWake(state, wake); |
| 3064 | }); |
| 3065 | |
| 3066 | const imageReport = Effect.fn("OpenCode2Adapter.imageReport")(function* ( |
| 3067 | state: ThreadState, |
| 3068 | payload: { |
| 3069 | readonly text: string; |
| 3070 | readonly metadata?: Readonly<Record<string, unknown>> | undefined; |
| 3071 | }, |
| 3072 | ) { |
| 3073 | const jobID = stringField(payload.metadata, "jobID"); |
| 3074 | const job = jobID === undefined ? undefined : state.imageJobs.get(jobID); |
| 3075 | const outcome = stringField(payload.metadata, "state"); |
| 3076 | if ( |
| 3077 | job === undefined || |
| 3078 | (outcome !== "completed" && outcome !== "error" && outcome !== "cancelled") |
| 3079 | ) |
| 3080 | return; |
| 3081 | // Native job inventory exposes the stem, while a completion notice names the saved file. |
| 3082 | const saved = /Saved image: (.+) \([^\n]+\)\./.exec(payload.text)?.[1]; |
| 3083 | const previewPath = |
| 3084 | saved !== undefined && saved.startsWith(job.path + ".") ? saved : undefined; |
| 3085 | if ( |
| 3086 | job.status !== "running" && |
| 3087 | !( |
| 3088 | job.status === "completed" && |
| 3089 | outcome === "completed" && |
| 3090 | !job.previewed && |
| 3091 | previewPath !== undefined |
| 3092 | ) |
| 3093 | ) |
| 3094 | return; |
| 3095 | const files: Array<{ uri: string; mime: string }> = []; |
| 3096 | yield* Effect.gen(function* () { |
| 3097 | if (outcome !== "completed" || previewPath === undefined) return; |
| 3098 | const image = yield* ( |
| 3099 | connection.external |
| 3100 | ? connection.readImage(previewPath, state.directory) |
| 3101 | : Effect.gen(function* () { |
| 3102 | const mime = OpenCode2Client.imagePreviewMime(paths.extname(previewPath)); |
| 3103 | const info = yield* fileSystem.stat(previewPath); |
| 3104 | if (mime === undefined || info.size > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) |
| 3105 | return yield* new OpenCode2Client.OpenCode2ImageError({ |
| 3106 | cause: "Unsupported image preview", |
| 3107 | }); |
| 3108 | const bytes = yield* fileSystem.readFile(previewPath); |
| 3109 | if (bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) |
| 3110 | return yield* new OpenCode2Client.OpenCode2ImageError({ |
| 3111 | cause: "Image exceeds preview limit", |
| 3112 | }); |
| 3113 | return { |
| 3114 | uri: `data:${mime};base64,${Buffer.from(bytes).toString("base64")}`, |
| 3115 | mime, |
| 3116 | }; |
| 3117 | }) |
| 3118 | ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.option); |
| 3119 | if (Option.isSome(image)) files.push(image.value); |
| 3120 | }).pipe( |
| 3121 | Effect.ensuring( |
| 3122 | Effect.gen(function* () { |
| 3123 | // A known outcome must still settle its tool if preview I/O is interrupted. |
| 3124 | job.status = outcome; |
| 3125 | job.previewed ||= files.length > 0; |
| 3126 | job.turn.tools.set(job.toolId, job.tool); |
| 3127 | yield* emitTool( |
| 3128 | state, |
| 3129 | job.turn, |
| 3130 | job.toolId, |
| 3131 | outcome === "completed" |
| 3132 | ? "completed" |
| 3133 | : outcome === "error" |
| 3134 | ? "failed" |
| 3135 | : "interrupted", |
| 3136 | { output: payload.text, metadata: undefined, files }, |
| 3137 | ); |
| 3138 | job.turn.tools.delete(job.toolId); |
| 3139 | yield* syncRosterAncestors(state); |
| 3140 | }), |
| 3141 | ), |
| 3142 | ); |
| 3143 | }); |
| 3144 | |
| 3145 | const onReport = Effect.fnUntraced(function* ( |
| 3146 | state: ThreadState, |
| 3147 | inboxId: string, |
| 3148 | payload: { |
| 3149 | readonly text: string; |
| 3150 | readonly description?: string | undefined; |
| 3151 | readonly metadata?: Readonly<Record<string, unknown>> | undefined; |
| 3152 | }, |
| 3153 | ) { |
| 3154 | if (stringField(payload.metadata, "source") === "shell") { |
| 3155 | const id = stringField(payload.metadata, "shellID"); |
| 3156 | const shell = id === undefined ? undefined : shells.get(id); |
| 3157 | if (shell !== undefined && shell.state !== state) return; |
| 3158 | state.reports.set(inboxId, { |
| 3159 | inboxId, |
| 3160 | childId: id ?? inboxId, |
| 3161 | text: payload.text, |
| 3162 | report: { |
| 3163 | kind: "command", |
| 3164 | label: shell?.command ?? payload.description, |
| 3165 | outcome: reportOutcome(stringField(payload.metadata, "state")), |
| 3166 | }, |
| 3167 | }); |
| 3168 | if (id !== undefined && shell === undefined) { |
| 3169 | const outcome = reportOutcome(stringField(payload.metadata, "state")); |
| 3170 | const known = shellInfo.get(id); |
| 3171 | const exit = known?.exit; |
| 3172 | // A known exit outranks the report, which says "completed" for a timeout. |
| 3173 | heldLaunch(state, id)?.ended.set(id, { |
| 3174 | status: |
| 3175 | known !== undefined && known.status !== "running" |
| 3176 | ? known.status === "killed" |
| 3177 | ? "interrupted" |
| 3178 | : exit === 0 |
| 3179 | ? "completed" |
| 3180 | : "failed" |
| 3181 | : outcome === "failed" |
| 3182 | ? "failed" |
| 3183 | : outcome === "cancelled" |
| 3184 | ? "interrupted" |
| 3185 | : "completed", |
| 3186 | ...(exit === undefined ? {} : { exit }), |
| 3187 | }); |
| 3188 | } |
| 3189 | if (id !== undefined && shell?.stopping !== true) { |
| 3190 | if (shell?.running === true && shell.state === state) { |
| 3191 | yield* readShellOutput(id, true).pipe(Effect.ignore({ log: true })); |
| 3192 | shell.running = false; |
| 3193 | const outcome = reportOutcome(stringField(payload.metadata, "state")); |
| 3194 | yield* emitShell( |
| 3195 | id, |
| 3196 | outcome === "failed" |
| 3197 | ? "failed" |
| 3198 | : outcome === "cancelled" |
| 3199 | ? "interrupted" |
| 3200 | : "completed", |
| 3201 | ); |
| 3202 | } |
| 3203 | shells.delete(id); |
| 3204 | shellInfo.delete(id); |
| 3205 | } |
| 3206 | return; |
| 3207 | } |
| 3208 | if (stringField(payload.metadata, "source") === "experimental_image_generate") { |
| 3209 | return yield* imageReport(state, payload); |
| 3210 | } |
| 3211 | const childId = stringField(payload.metadata, "childID"); |
| 3212 | if (stringField(payload.metadata, "source") !== "subagent" || childId === undefined) return; |
| 3213 | strays.delete(childId); |
| 3214 | const open = [...state.calls.values()].filter( |
| 3215 | (candidate) => candidate.child?.sessionId === childId, |
| 3216 | ); |
| 3217 | const output = subagentOutput(payload.text); |
| 3218 | const started = open |
| 3219 | .flatMap((candidate) => |
| 3220 | candidate.run === undefined ? [] : [{ call: candidate, run: candidate.run }], |
| 3221 | ) |
| 3222 | .sort((a, b) => a.run - b.run); |
| 3223 | // The report names only the child, and reports arrive in order. So it belongs to the oldest |
| 3224 | // open run, unless that run ended with a different text: then its own report is lost. |
| 3225 | const next = started.find( |
| 3226 | (candidate) => candidate.call.answer === undefined || candidate.call.answer === output, |
| 3227 | ); |
| 3228 | const written = next?.call.answer === output ? next.run : undefined; |
| 3229 | const call = written === undefined ? open[0] : next?.call; |
| 3230 | const calls = |
| 3231 | call?.run === undefined |
| 3232 | ? open.slice(0, 1) |
| 3233 | : open.filter((candidate) => candidate.run === call.run); |
| 3234 | const lost = started.flatMap((candidate) => |
| 3235 | written !== undefined && candidate.run < written ? [candidate.call] : [], |
| 3236 | ); |
| 3237 | const outcome = reportOutcome(stringField(payload.metadata, "state")); |
| 3238 | state.reports.set(inboxId, { |
| 3239 | inboxId, |
| 3240 | childId, |
| 3241 | text: payload.text, |
| 3242 | report: { |
| 3243 | kind: "subagent", |
| 3244 | label: call?.title ?? stringField(payload.metadata, "description"), |
| 3245 | childThreadId: call?.child?.subagent?.appThread.id, |
| 3246 | outcome, |
| 3247 | }, |
| 3248 | }); |
| 3249 | const status = state.stoppedChildren.has(childId) |
| 3250 | ? "interrupted" |
| 3251 | : outcome === "failed" |
| 3252 | ? "failed" |
| 3253 | : outcome === "cancelled" |
| 3254 | ? "cancelled" |
| 3255 | : "completed"; |
| 3256 | for (const each of lost) yield* settleCall(each, "completed", each.answer); |
| 3257 | for (const each of calls) yield* settleCall(each, status, output); |
| 3258 | }); |
| 3259 | |
| 3260 | const holderOf = (sessionId: string) => { |
| 3261 | const own = threads.get(sessionId); |
| 3262 | if (own !== undefined) return own.wakes.at(-1)?.running === true ? own : undefined; |
| 3263 | const parent = announced.get(sessionId)?.parentID; |
| 3264 | const holder = parent === undefined ? undefined : threads.get(parent); |
| 3265 | return holder !== undefined && holder.active === undefined && holder.wakes.length > 0 |
| 3266 | ? holder |
| 3267 | : undefined; |
| 3268 | }; |
| 3269 | |
| 3270 | // Undelivered steers start another execution owned by this turn; Stop starts nothing. |
| 3271 | const endExecution = Effect.fnUntraced(function* ( |
| 3272 | state: ThreadState, |
| 3273 | turn: ActiveTurn, |
| 3274 | end: TurnTerminal, |
| 3275 | ) { |
| 3276 | if (end.status === "completed" && (turn.steers.size > 0 || goalHoldsTurn(state))) { |
| 3277 | turn.heldEnd = end; |
| 3278 | // OpenCode can pause a goal without telling this server, such as another process's |
| 3279 | // restart sweep, so confirm the goal is still active before waiting on it. |
| 3280 | if (goalHoldsTurn(state) && !state.goalRefreshing) yield* refreshGoal(state); |
| 3281 | return; |
| 3282 | } |
| 3283 | yield* finishTurn(state, end); |
| 3284 | }); |
| 3285 | |
| 3286 | const endIfSettled = (state: ThreadState, turn: ActiveTurn) => |
| 3287 | turn.heldEnd !== undefined && turn.steers.size === 0 && !goalHoldsTurn(state) |
| 3288 | ? finishTurn(state, turn.heldEnd) |
| 3289 | : Effect.void; |
| 3290 | |
| 3291 | // Holds a goal turn until OpenCode's goal is read again; a failed read releases it. |
| 3292 | const refreshGoal = Effect.fnUntraced(function* (state: ThreadState) { |
| 3293 | state.goalFresh = false; |
| 3294 | state.goalRefreshing = true; |
| 3295 | state.goalRevision += 1; |
| 3296 | const revision = state.goalRevision; |
| 3297 | yield* Effect.forkIn( |
| 3298 | readGoal(state).pipe( |
| 3299 | Effect.timeout(INVENTORY_TIMEOUT), |
| 3300 | Effect.catch(() => |
| 3301 | Effect.logWarning("Could not refresh OpenCode goal state.").pipe(Effect.as(false)), |
| 3302 | ), |
| 3303 | Effect.flatMap((applied) => |
| 3304 | lock.withPermit( |
| 3305 | Effect.gen(function* () { |
| 3306 | if (state.goalRevision === revision) state.goalRefreshing = false; |
| 3307 | // A newer goal event or a reconnect's read owns settlement now. |
| 3308 | else if (!applied) return; |
| 3309 | if (state.active !== undefined) yield* endIfSettled(state, state.active); |
| 3310 | }), |
| 3311 | ), |
| 3312 | ), |
| 3313 | ), |
| 3314 | sessionScope, |
| 3315 | ); |
| 3316 | }); |
| 3317 | |
| 3318 | const handleEvent = Effect.fnUntraced(function* (event: OpenCode2Client.OpenCode2StreamEvent) { |
| 3319 | if (event.type === "shell.created") { |
| 3320 | const sessionId = stringField(event.data.info.metadata, "sessionID"); |
| 3321 | if (sessionId !== undefined && ownerOf(sessionId) !== undefined) { |
| 3322 | shellInfo.set(event.data.info.id, event.data.info); |
| 3323 | if (shellInfo.size > 128) shellInfo.delete(shellInfo.keys().next().value!); |
| 3324 | } |
| 3325 | return; |
| 3326 | } |
| 3327 | if (event.type === "shell.exited" || event.type === "shell.deleted") { |
| 3328 | const known = shellInfo.get(event.data.id); |
| 3329 | if (known !== undefined) |
| 3330 | shellInfo.set(event.data.id, { |
| 3331 | ...known, |
| 3332 | status: event.type === "shell.deleted" ? "killed" : event.data.status, |
| 3333 | exit: "exit" in event.data ? event.data.exit : undefined, |
| 3334 | }); |
| 3335 | const shell = shells.get(event.data.id); |
| 3336 | if (shell === undefined || !shell.running || shell.stopping === true) return; |
| 3337 | if (event.type === "shell.exited") |
| 3338 | yield* readShellOutput(event.data.id, true).pipe(Effect.ignore({ log: true })); |
| 3339 | shell.running = false; |
| 3340 | yield* emitShell( |
| 3341 | event.data.id, |
| 3342 | event.type === "shell.deleted" || event.data.status === "killed" |
| 3343 | ? "interrupted" |
| 3344 | : event.data.exit === 0 |
| 3345 | ? "completed" |
| 3346 | : "failed", |
| 3347 | "exit" in event.data ? event.data.exit : undefined, |
| 3348 | ); |
| 3349 | shells.delete(event.data.id); |
| 3350 | shellInfo.delete(event.data.id); |
| 3351 | yield* syncRosterAncestors(shell.state); |
| 3352 | return; |
| 3353 | } |
| 3354 | const sessionId = sessionOfEvent(event); |
| 3355 | const cleared = sessionId === undefined ? undefined : clearing.get(sessionId); |
| 3356 | if (cleared !== undefined) { |
| 3357 | if (event.type === "unreadable.execution.ended" || executionEnd(event.type)) { |
| 3358 | return yield* Deferred.succeed(cleared, undefined); |
| 3359 | } |
| 3360 | if ( |
| 3361 | event.type === "session.execution.started" || |
| 3362 | event.type === "unreadable.execution.started" |
| 3363 | ) { |
| 3364 | return; |
| 3365 | } |
| 3366 | } |
| 3367 | if (sessionId !== undefined) { |
| 3368 | if ( |
| 3369 | event.type === "session.execution.started" || |
| 3370 | event.type === "unreadable.execution.started" |
| 3371 | ) { |
| 3372 | // Executions are serial: a second start proves the unsettled run lost its end. |
| 3373 | const state = threads.get(sessionId); |
| 3374 | if (state !== undefined) state.starts += 1; |
| 3375 | if (state?.unsettled === true) { |
| 3376 | if (state.unsettledStarted) state.unsettled = false; |
| 3377 | else state.unsettledStarted = true; |
| 3378 | } |
| 3379 | busy.add(sessionId); |
| 3380 | } else if (event.type === "unreadable.execution.ended" || executionEnd(event.type)) { |
| 3381 | busy.delete(sessionId); |
| 3382 | } |
| 3383 | } |
| 3384 | if (event.type === "session.created" && event.data.parentID !== undefined) { |
| 3385 | const strayCaller = strays.get(event.data.parentID); |
| 3386 | if (strayCaller !== undefined) { |
| 3387 | strays.set(event.data.sessionID, strayCaller); |
| 3388 | return; |
| 3389 | } |
| 3390 | const owner = ownerOf(event.data.parentID); |
| 3391 | if (owner !== undefined) { |
| 3392 | childOwners.set(event.data.sessionID, owner); |
| 3393 | announced.set(event.data.sessionID, event.data); |
| 3394 | holderOf(event.data.parentID)?.wakes.at(-1)?.children.add(event.data.sessionID); |
| 3395 | } |
| 3396 | return; |
| 3397 | } |
| 3398 | const holder = sessionId === undefined ? undefined : holderOf(sessionId); |
| 3399 | const held = holder?.wakes.at(-1); |
| 3400 | if (holder !== undefined && held !== undefined) { |
| 3401 | held.events.push(event); |
| 3402 | if ( |
| 3403 | sessionId === holder.sessionId && |
| 3404 | (event.type === "unreadable.execution.ended" || executionEnd(event.type)) |
| 3405 | ) { |
| 3406 | held.running = false; |
| 3407 | } |
| 3408 | return; |
| 3409 | } |
| 3410 | return yield* route(event, sessionId); |
| 3411 | }); |
| 3412 | |
| 3413 | const route = Effect.fnUntraced(function* ( |
| 3414 | event: OpenCode2Client.OpenCode2StreamEvent, |
| 3415 | sessionId: string | undefined, |
| 3416 | held = false, |
| 3417 | ) { |
| 3418 | const ended = |
| 3419 | !held && (event.type === "unreadable.execution.ended" || executionEnd(event.type)) |
| 3420 | ? threads.get(sessionId ?? "") |
| 3421 | : undefined; |
| 3422 | if (ended?.unsettled === true) { |
| 3423 | ended.unsettled = false; |
| 3424 | return; |
| 3425 | } |
| 3426 | if (event.type === "unreadable.execution.started") { |
| 3427 | const turn = threads.get(event.sessionID)?.active; |
| 3428 | if (turn !== undefined) { |
| 3429 | turn.awaitingStart = false; |
| 3430 | turn.heldEnd = undefined; |
| 3431 | return; |
| 3432 | } |
| 3433 | } |
| 3434 | if (event.type === "unreadable.execution.ended") { |
| 3435 | const state = threads.get(event.sessionID); |
| 3436 | const turn = state?.active; |
| 3437 | if (state === undefined || turn === undefined || turn.awaitingStart) return; |
| 3438 | return yield* endExecution( |
| 3439 | state, |
| 3440 | turn, |
| 3441 | event.executionType === "session.execution.succeeded" |
| 3442 | ? { status: turn.interrupted ? "interrupted" : "completed" } |
| 3443 | : event.executionType === "session.execution.interrupted" |
| 3444 | ? { status: "interrupted" } |
| 3445 | : { |
| 3446 | status: "failed", |
| 3447 | failure: makeProviderFailure({ |
| 3448 | message: "OpenCode ended the turn with an error this version cannot read.", |
| 3449 | class: "provider_error", |
| 3450 | }), |
| 3451 | }, |
| 3452 | ); |
| 3453 | } |
| 3454 | if (event.type === "permission.asked") { |
| 3455 | return yield* onAsked({ type: "permission", request: event.data }); |
| 3456 | } |
| 3457 | if (event.type === "form.created") |
| 3458 | return yield* onAsked({ type: "form", form: event.data.form }); |
| 3459 | if ( |
| 3460 | event.type === "permission.replied" || |
| 3461 | event.type === "form.replied" || |
| 3462 | event.type === "form.cancelled" |
| 3463 | ) { |
| 3464 | const nativeId = event.type === "permission.replied" ? event.data.requestID : event.data.id; |
| 3465 | const entry = [...pending.values()].find((candidate) => candidate.native.id === nativeId); |
| 3466 | if (entry === undefined || entry.answering) return; |
| 3467 | const answered = |
| 3468 | event.type === "form.replied" || |
| 3469 | (event.type === "permission.replied" && event.data.reply !== "reject"); |
| 3470 | return yield* settleRequest(entry, answered ? "resolved" : "cancelled"); |
| 3471 | } |
| 3472 | if (sessionId === undefined) return; |
| 3473 | const state = threads.get(sessionId); |
| 3474 | if (state === undefined) return; |
| 3475 | if (event.type === "rpc.opencode.goal.changed") { |
| 3476 | if (!supportsNativeGoals()) return; |
| 3477 | const goal = yield* decodeGoal(event.data["goal"]).pipe(Effect.result); |
| 3478 | if (goal._tag === "Failure") { |
| 3479 | yield* Effect.logWarning( |
| 3480 | "Could not decode an OpenCode goal update; refreshing its state.", |
| 3481 | ); |
| 3482 | return yield* refreshGoal(state); |
| 3483 | } |
| 3484 | yield* updateGoal(state, goal.success); |
| 3485 | if (state.active !== undefined) yield* endIfSettled(state, state.active); |
| 3486 | return; |
| 3487 | } |
| 3488 | if (event.type === "session.model.selected" || event.type === "session.step.started") { |
| 3489 | if (event.type === "session.model.selected") state.model = event.data.model; |
| 3490 | const providerThread = withReportedModel(state.providerThread, event.data.model); |
| 3491 | if (providerThread !== state.providerThread) { |
| 3492 | state.providerThread = { ...providerThread, updatedAt: yield* DateTime.now }; |
| 3493 | yield* emitProviderThread(state); |
| 3494 | } |
| 3495 | } |
| 3496 | if ( |
| 3497 | event.type === "session.inbox.enqueued" && |
| 3498 | state.subagent !== undefined && |
| 3499 | state.active === undefined |
| 3500 | ) { |
| 3501 | state.subagent.queued ??= event.data.inboxID; |
| 3502 | } |
| 3503 | if (event.type === "session.inbox.enqueued" && event.data.item.type === "synthetic") { |
| 3504 | return yield* onReport(state, event.data.inboxID, event.data.item.payload); |
| 3505 | } |
| 3506 | if (event.type === "session.inbox.cancelled" || event.type === "session.inbox.delivered") { |
| 3507 | const report = state.reports.get(event.data.inboxID); |
| 3508 | state.reports.delete(event.data.inboxID); |
| 3509 | const external = state.externalPrompts.get(event.data.inboxID); |
| 3510 | state.externalPrompts.delete(event.data.inboxID); |
| 3511 | const turn = state.active; |
| 3512 | if (turn !== undefined && turn.steers.delete(event.data.inboxID)) { |
| 3513 | turn.settledInbox.add(event.data.inboxID); |
| 3514 | if (event.type === "session.inbox.cancelled") yield* endIfSettled(state, turn); |
| 3515 | } else if ( |
| 3516 | event.type === "session.inbox.delivered" && |
| 3517 | external !== undefined && |
| 3518 | turn !== undefined |
| 3519 | ) { |
| 3520 | yield* emitExternalPrompt(state, turn, event.data.inboxID, external.text); |
| 3521 | } else if ( |
| 3522 | event.type === "session.inbox.delivered" && |
| 3523 | report !== undefined && |
| 3524 | turn !== undefined |
| 3525 | ) { |
| 3526 | yield* emitDeliveredReport(state, turn, event.data.inboxID, report.report); |
| 3527 | } |
| 3528 | return; |
| 3529 | } |
| 3530 | // No T3 turn existed while a wake held these, so its user items came from another client. |
| 3531 | if ( |
| 3532 | event.type === "session.inbox.enqueued" && |
| 3533 | event.data.item.type === "user" && |
| 3534 | (state.active === undefined || (held && state.subagent === undefined)) |
| 3535 | ) { |
| 3536 | const text = event.data.item.payload.text; |
| 3537 | if (state.subagent !== undefined) state.subagent.prompt ??= text; |
| 3538 | // T3's own prompts can be admitted after a failed submit ended their turn. |
| 3539 | else if (!isOwnPrompt(event.data.inboxID)) { |
| 3540 | state.externalPrompts.set(event.data.inboxID, { |
| 3541 | text, |
| 3542 | leads: !held && state.reports.size === 0, |
| 3543 | }); |
| 3544 | } |
| 3545 | return; |
| 3546 | } |
| 3547 | const started = |
| 3548 | event.type === "session.execution.started" || event.type === "unreadable.execution.started"; |
| 3549 | if (state.subagent !== undefined && state.active === undefined && started) { |
| 3550 | if ((yield* takeReports(state)).stopped) { |
| 3551 | state.subagent.queued = undefined; |
| 3552 | return; |
| 3553 | } |
| 3554 | return yield* startChildTurn(state); |
| 3555 | } |
| 3556 | const turn = state.active; |
| 3557 | if (turn === undefined) { |
| 3558 | if (started && state.subagent === undefined) return yield* onWake(state); |
| 3559 | return; |
| 3560 | } |
| 3561 | if (turn.awaitingStart) { |
| 3562 | if (event.type === "session.execution.started") turn.awaitingStart = false; |
| 3563 | return; |
| 3564 | } |
| 3565 | return yield* onTurnEvent(state, turn, event); |
| 3566 | }); |
| 3567 | |
| 3568 | // Terminal events are volatile; reconnects lose events and restarted servers cannot end lost executions. |
| 3569 | let streamFailure: string | undefined; |
| 3570 | let reconnected = yield* Deferred.make<void>(); |
| 3571 | const failAll = Effect.fnUntraced(function* (message: string) { |
| 3572 | streamFailure = message; |
| 3573 | yield* Deferred.succeed(reconnected, undefined); |
| 3574 | for (const state of threads.values()) { |
| 3575 | const failure = makeProviderFailure({ message, class: "transport_error" }); |
| 3576 | yield* finishTurn(state, { status: "failed", failure }, "broken"); |
| 3577 | } |
| 3578 | for (const state of threads.values()) { |
| 3579 | for (const call of runningCalls(state)) yield* settleCall(call, "failed"); |
| 3580 | for (const [jobID, job] of state.imageJobs) { |
| 3581 | if (job.status !== "running") continue; |
| 3582 | yield* imageReport(state, { text: message, metadata: { jobID, state: "error" } }); |
| 3583 | } |
| 3584 | for (const wake of state.wakes.splice(0)) wake.dropped = true; |
| 3585 | state.reports.clear(); |
| 3586 | yield* syncRosterAncestors(state); |
| 3587 | } |
| 3588 | yield* setSessionStatus("error", message); |
| 3589 | yield* Queue.end(events); |
| 3590 | }); |
| 3591 | const backfill = Effect.fnUntraced(function* (sessionId: string, state: ThreadState) { |
| 3592 | const turn = state.active; |
| 3593 | if (turn === undefined) return undefined; |
| 3594 | const promptId = promptOf(turn.providerTurn); |
| 3595 | const { before } = turn; |
| 3596 | if (promptId === undefined && before === undefined) return undefined; |
| 3597 | const start = before !== undefined ? before : promptId; |
| 3598 | const read = yield* OpenCode2Client.paginate( |
| 3599 | { sessionID: Session.ID.make(sessionId), order: "desc" as const, limit: 50 }, |
| 3600 | client.message.list, |
| 3601 | ).pipe( |
| 3602 | Stream.takeUntil((message) => message.id === start), |
| 3603 | Stream.runCollect, |
| 3604 | Effect.catchTags({ SessionNotFoundError: () => Effect.succeed(null) }), |
| 3605 | ); |
| 3606 | return yield* lock.withPermit( |
| 3607 | Effect.gen(function* () { |
| 3608 | if (state.active !== turn) return undefined; |
| 3609 | if (read === null) return { outcome: "missing" as const }; |
| 3610 | // Without this turn's start in history, all retrieved turns are older. |
| 3611 | const found = start === null || read.at(-1)?.id === start; |
| 3612 | if (!found) return undefined; |
| 3613 | const recent = before !== undefined && before !== null ? read.slice(0, -1) : read; |
| 3614 | for (const message of recent) { |
| 3615 | if (message.type === "user" && turn.steers.delete(message.id)) { |
| 3616 | turn.settledInbox.add(message.id); |
| 3617 | } |
| 3618 | } |
| 3619 | const idle = recent.find((message) => message.type === "idle"); |
| 3620 | const assistant = recent.find((message) => message.type === "assistant"); |
| 3621 | if (assistant?.retry !== undefined) { |
| 3622 | // Snapshots omit when the retry was scheduled, so only its remaining delay is known. |
| 3623 | yield* updateRetry( |
| 3624 | state, |
| 3625 | turn, |
| 3626 | assistant.retry, |
| 3627 | DateTime.toEpochMillis(assistant.retry.at) - |
| 3628 | DateTime.toEpochMillis(yield* DateTime.now), |
| 3629 | ); |
| 3630 | } else if ( |
| 3631 | turn.retry !== undefined && |
| 3632 | assistant !== undefined && |
| 3633 | assistant.error === undefined && |
| 3634 | assistant.content.length > 0 |
| 3635 | ) { |
| 3636 | yield* emitRetry(state, turn, "completed"); |
| 3637 | turn.retry = undefined; |
| 3638 | } |
| 3639 | for (const message of recent.toReversed()) { |
| 3640 | if (message.type !== "assistant" || state.active !== turn) continue; |
| 3641 | const ordinals = { text: 0, reasoning: 0 }; |
| 3642 | for (const [index, part] of message.content.entries()) { |
| 3643 | if (part.type === "text" || part.type === "reasoning") { |
| 3644 | const block = { assistantMessageID: message.id, ordinal: ordinals[part.type]++ }; |
| 3645 | // OpenCode saves a block's text only when the block ends, so the last block of a |
| 3646 | // response still streaming stays open and keeps the text that already arrived. |
| 3647 | const open = |
| 3648 | message.time.streamed === undefined && index === message.content.length - 1; |
| 3649 | yield* emitText( |
| 3650 | state, |
| 3651 | turn, |
| 3652 | block, |
| 3653 | part.type, |
| 3654 | (text) => (open && !part.text.startsWith(text) ? text : part.text), |
| 3655 | !open, |
| 3656 | ); |
| 3657 | continue; |
| 3658 | } |
| 3659 | if (part.type !== "tool") continue; |
| 3660 | turn.closingText = undefined; |
| 3661 | if (!turn.tools.has(part.id)) { |
| 3662 | turn.tools.set(part.id, { name: part.name, input: {} }); |
| 3663 | turn.startedAt.set(part.id, yield* DateTime.now); |
| 3664 | } |
| 3665 | const tool = turn.tools.get(part.id)!; |
| 3666 | if (typeof part.state.input === "object" && part.state.input !== null) { |
| 3667 | tool.input = part.state.input as Record<string, unknown>; |
| 3668 | } |
| 3669 | if (part.state.status === "completed") { |
| 3670 | yield* emitTool(state, turn, part.id, "completed", { |
| 3671 | output: textOf(part.state.content), |
| 3672 | files: part.state.content.flatMap((content) => |
| 3673 | content.type === "file" ? [content] : [], |
| 3674 | ), |
| 3675 | metadata: part.state.metadata, |
| 3676 | }); |
| 3677 | if ( |
| 3678 | ![...state.imageJobs.values()].some( |
| 3679 | (job) => job.turn === turn && job.toolId === part.id, |
| 3680 | ) |
| 3681 | ) |
| 3682 | turn.tools.delete(part.id); |
| 3683 | } else if (part.state.status === "error") { |
| 3684 | yield* emitTool(state, turn, part.id, "failed", { |
| 3685 | output: part.state.error.message, |
| 3686 | metadata: part.state.metadata, |
| 3687 | }); |
| 3688 | turn.tools.delete(part.id); |
| 3689 | } else { |
| 3690 | yield* emitTool(state, turn, part.id, "running"); |
| 3691 | } |
| 3692 | } |
| 3693 | } |
| 3694 | return idle === undefined ? undefined : { outcome: idle.outcome }; |
| 3695 | }), |
| 3696 | ); |
| 3697 | }); |
| 3698 | |
| 3699 | // Restarts retain the previous session.outcome; without an idle item, the lost execution was interrupted. |
| 3700 | const recoverImages = Effect.fn("OpenCode2Adapter.recoverImages")(function* ( |
| 3701 | state: ThreadState, |
| 3702 | ) { |
| 3703 | if (![...state.imageJobs.values()].some((job) => job.status === "running")) return; |
| 3704 | yield* OpenCode2Client.paginate( |
| 3705 | { sessionID: Session.ID.make(state.sessionId), type: "synthetic" as const, limit: 100 }, |
| 3706 | client.message.list, |
| 3707 | ).pipe( |
| 3708 | Stream.runForEach((message) => |
| 3709 | message.type === "synthetic" && |
| 3710 | stringField(message.metadata, "source") === "experimental_image_generate" |
| 3711 | ? imageReport(state, message) |
| 3712 | : Effect.void, |
| 3713 | ), |
| 3714 | ); |
| 3715 | if ( |
| 3716 | ![...state.imageJobs.values()].some((job) => job.status === "running") || |
| 3717 | compareSemverVersions(connection.version, "2.2.6") < 0 |
| 3718 | ) |
| 3719 | return; |
| 3720 | const jobs = yield* connection.imageJobs(state.sessionId); |
| 3721 | for (const job of jobs) { |
| 3722 | if (job.status === "running") continue; |
| 3723 | yield* imageReport(state, { |
| 3724 | text: `Image generation ${job.status}. Output path: ${job.path} (${job.model}).`, |
| 3725 | metadata: { source: "experimental_image_generate", jobID: job.id, state: job.status }, |
| 3726 | }); |
| 3727 | } |
| 3728 | }); |
| 3729 | |
| 3730 | const reconcile = Effect.fn("OpenCode2Adapter.reconcile")(function* () { |
| 3731 | // Read deepest sessions first; subagent turns end before their waiting parents. |
| 3732 | const running = [...threads] |
| 3733 | .filter(([, state]) => state.active !== undefined) |
| 3734 | .toSorted(([left], [right]) => callsAbove(right).length - callsAbove(left).length); |
| 3735 | const background = [...threads.values()].filter( |
| 3736 | (state) => state.subagent === undefined && hasBackground(state), |
| 3737 | ); |
| 3738 | const marked = [...threads.values()].some((state) => state.unsettled); |
| 3739 | if ( |
| 3740 | running.length === 0 && |
| 3741 | background.length === 0 && |
| 3742 | busy.size === 0 && |
| 3743 | !marked && |
| 3744 | strays.size === 0 |
| 3745 | ) { |
| 3746 | return; |
| 3747 | } |
| 3748 | const active = { ...(yield* client.session.active()) }; |
| 3749 | for (const sessionId of busy) if (!(sessionId in active)) busy.delete(sessionId); |
| 3750 | for (const state of threads.values()) { |
| 3751 | if (state.unsettled && !(state.sessionId in active)) state.unsettledStarted = true; |
| 3752 | } |
| 3753 | for (const childId of strays.keys()) if (!(childId in active)) strays.delete(childId); |
| 3754 | for (const [sessionId, state] of running) { |
| 3755 | const turn = state.active; |
| 3756 | if (turn === undefined) continue; |
| 3757 | turn.missedEvents = true; |
| 3758 | const ended = yield* backfill(sessionId, state); |
| 3759 | if (ended?.outcome === "missing") { |
| 3760 | delete active[Session.ID.make(sessionId)]; |
| 3761 | busy.delete(sessionId); |
| 3762 | } |
| 3763 | yield* lock.withPermit( |
| 3764 | Effect.gen(function* () { |
| 3765 | if (state.active !== turn) return; |
| 3766 | if (sessionId in active) { |
| 3767 | turn.heldEnd = undefined; |
| 3768 | return; |
| 3769 | } |
| 3770 | if (ended?.outcome === "missing") { |
| 3771 | return yield* finishTurn(state, { status: "interrupted" }, "broken"); |
| 3772 | } |
| 3773 | const terminal: TurnTerminal = |
| 3774 | ended?.outcome === "succeeded" |
| 3775 | ? { status: turn.interrupted ? "interrupted" : "completed" } |
| 3776 | : ended?.outcome === "failed" |
| 3777 | ? { |
| 3778 | status: "failed", |
| 3779 | failure: makeProviderFailure({ |
| 3780 | message: |
| 3781 | "OpenCode ended the turn with an error while T3 Code was reconnecting.", |
| 3782 | class: "provider_error", |
| 3783 | }), |
| 3784 | } |
| 3785 | : { status: "interrupted" }; |
| 3786 | yield* endExecution(state, turn, terminal); |
| 3787 | }), |
| 3788 | ); |
| 3789 | } |
| 3790 | for (const state of threads.values()) { |
| 3791 | yield* lock |
| 3792 | .withPermit(recoverImages(state).pipe(Effect.timeout(INVENTORY_TIMEOUT))) |
| 3793 | .pipe(Effect.ignore({ log: true })); |
| 3794 | } |
| 3795 | yield* lock.withPermit( |
| 3796 | Effect.gen(function* () { |
| 3797 | for (const state of background) { |
| 3798 | for (const call of runningCalls(state)) { |
| 3799 | const child = call.child?.sessionId; |
| 3800 | if (child === undefined || !(child in active)) { |
| 3801 | yield* settleCall(call, "interrupted", LOST_BACKGROUND); |
| 3802 | } |
| 3803 | } |
| 3804 | const sessions = sessionsOf(state); |
| 3805 | for (const session of sessions) { |
| 3806 | discardWakes(session, session.wakes.splice(0)); |
| 3807 | session.reports.clear(); |
| 3808 | } |
| 3809 | for (const session of sessions.toReversed()) yield* syncRoster(session); |
| 3810 | } |
| 3811 | // Stopped off the lock this reconcile holds; one still running waits for a Stop. |
| 3812 | for (const thread of new Set([...strays.values()].map(rootOf))) { |
| 3813 | yield* Effect.forkIn(stopStrays(thread), sessionScope); |
| 3814 | } |
| 3815 | }), |
| 3816 | ); |
| 3817 | const listed = new Map<string, Set<string>>(); |
| 3818 | for (const sessionId of Object.keys(active)) { |
| 3819 | const owner = ownerOf(sessionId); |
| 3820 | if (owner === undefined) continue; |
| 3821 | const turn = requestTurn(sessionId)?.turn; |
| 3822 | // Replies may settle during these reads; an older snapshot must not ask again. |
| 3823 | const known = new Set([...pending.values()].map((entry) => entry.native.id)); |
| 3824 | const sessionID = Session.ID.make(sessionId); |
| 3825 | const [permissions, forms] = yield* Effect.all([ |
| 3826 | client.permission.list({ sessionID }), |
| 3827 | client.session.form.list({ sessionID }), |
| 3828 | ]); |
| 3829 | yield* lock.withPermit( |
| 3830 | Effect.gen(function* () { |
| 3831 | if (ownerOf(sessionId) !== owner || requestTurn(sessionId)?.turn !== turn) return; |
| 3832 | listed.set(sessionId, new Set([...permissions, ...forms].map((request) => request.id))); |
| 3833 | const shown = new Set([...pending.values()].map((entry) => entry.native.id)); |
| 3834 | for (const request of permissions) { |
| 3835 | if (!shown.has(request.id) && !known.has(request.id)) |
| 3836 | yield* onAsked({ type: "permission", request }); |
| 3837 | } |
| 3838 | for (const form of forms) { |
| 3839 | if (!shown.has(form.id) && !known.has(form.id)) |
| 3840 | yield* onAsked({ type: "form", form }); |
| 3841 | } |
| 3842 | }), |
| 3843 | ); |
| 3844 | } |
| 3845 | yield* lock.withPermit( |
| 3846 | Effect.gen(function* () { |
| 3847 | for (const entry of Array.from(pending.values())) { |
| 3848 | if (listed.get(entry.sessionId)?.has(entry.native.id) !== true) { |
| 3849 | yield* settleRequest(entry, "cancelled"); |
| 3850 | } |
| 3851 | } |
| 3852 | }), |
| 3853 | ); |
| 3854 | }); |
| 3855 | |
| 3856 | const reconnect = Effect.gen(function* () { |
| 3857 | // Release the borrow on every failure, including reconnect interruption, so spawned servers can idle-stop. |
| 3858 | const scope = yield* Scope.make(); |
| 3859 | const { next, stream } = yield* Effect.gen(function* () { |
| 3860 | const next = yield* borrow.pipe(Effect.provideService(Scope.Scope, scope)); |
| 3861 | const events = next.events.pipe(Effect.provideService(Scope.Scope, scope)); |
| 3862 | return { next, stream: yield* whileAlive(next.processExit, events) }; |
| 3863 | }).pipe(Effect.onError(() => Scope.close(scope, Exit.void))); |
| 3864 | const previous = currentScope; |
| 3865 | connection = next; |
| 3866 | client = next.client; |
| 3867 | nativeGoalSupport = supportsNativeGoals(); |
| 3868 | session = { |
| 3869 | ...session, |
| 3870 | capabilities: { |
| 3871 | ...session.capabilities, |
| 3872 | turns: { ...session.capabilities.turns, supportsNativeGoals: supportsNativeGoals() }, |
| 3873 | }, |
| 3874 | }; |
| 3875 | currentScope = scope; |
| 3876 | yield* Scope.close(previous, Exit.void); |
| 3877 | // A restarted server forgot T3's MCP servers; the next turn adds them again. |
| 3878 | // The gap may have started a pending prompt unseen, so none may set a later wake's boundary. |
| 3879 | for (const state of threads.values()) { |
| 3880 | state.mcp = undefined; |
| 3881 | state.goalFresh = false; |
| 3882 | state.goalRefreshing = false; |
| 3883 | state.goalRevision += 1; |
| 3884 | for (const prompt of state.externalPrompts.values()) prompt.leads = false; |
| 3885 | } |
| 3886 | if (supportsNativeGoals()) { |
| 3887 | yield* Effect.forEach( |
| 3888 | [...threads.values()], |
| 3889 | (state) => readGoal(state).pipe(Effect.ignore({ log: true })), |
| 3890 | { concurrency: 4, discard: true }, |
| 3891 | ).pipe(Effect.timeout(INVENTORY_TIMEOUT), Effect.ignore({ log: true })); |
| 3892 | } |
| 3893 | for (const state of threads.values()) { |
| 3894 | yield* recoverShells(state).pipe(Effect.ignore({ log: true })); |
| 3895 | } |
| 3896 | // An owned process's exit, rather than a read deadline, bounds recovery; the bounded retry |
| 3897 | // below then borrows a restarted server. HTTP waits stay outside the event lock so Stop can still settle. |
| 3898 | yield* next.processExit === undefined |
| 3899 | ? reconcile().pipe(Effect.timeout(RECONCILE_TIMEOUT)) |
| 3900 | : whileAlive(next.processExit, reconcile()); |
| 3901 | return stream; |
| 3902 | }).pipe( |
| 3903 | // Borrows and process exits stay bounded; only a live owned process is waited on above. |
| 3904 | Effect.retry({ |
| 3905 | times: RECONNECT_ATTEMPTS - 1, |
| 3906 | schedule: Schedule.spaced(RECONNECT_DELAY), |
| 3907 | ...(connection.processExit === undefined |
| 3908 | ? {} |
| 3909 | : { while: (error: unknown) => !isPermanentRecoveryError(error) }), |
| 3910 | }), |
| 3911 | ); |
| 3912 | |
| 3913 | let currentScope = initial.scope; |
| 3914 | yield* Effect.addFinalizer(() => Scope.close(currentScope, Exit.void)); |
| 3915 | const follow = ( |
| 3916 | stream: Stream.Stream<OpenCode2Client.OpenCode2StreamEvent, unknown>, |
| 3917 | ): Effect.Effect<void> => |
| 3918 | stream.pipe( |
| 3919 | Stream.runForEach((event) => |
| 3920 | lock.withPermit( |
| 3921 | Effect.gen(function* () { |
| 3922 | yield* handleEvent(event); |
| 3923 | if ( |
| 3924 | event.type === "session.execution.started" || |
| 3925 | event.type === "unreadable.execution.started" || |
| 3926 | executionEnd(event.type) || |
| 3927 | event.type === "unreadable.execution.ended" || |
| 3928 | event.type === "session.inbox.enqueued" || |
| 3929 | event.type === "session.inbox.delivered" || |
| 3930 | event.type === "session.inbox.cancelled" |
| 3931 | ) { |
| 3932 | const sessionId = sessionOfEvent(event); |
| 3933 | const state = sessionId === undefined ? undefined : threads.get(sessionId); |
| 3934 | if (state !== undefined) yield* syncRosterAncestors(state); |
| 3935 | } |
| 3936 | }), |
| 3937 | ), |
| 3938 | ), |
| 3939 | Effect.exit, |
| 3940 | Effect.flatMap(() => |
| 3941 | Effect.gen(function* () { |
| 3942 | streamFailure = "The OpenCode event stream was lost. Reconnecting."; |
| 3943 | yield* Effect.logWarning("Lost the OpenCode event stream; reconnecting."); |
| 3944 | // Failures may contain URLs or response text; annotate only the tag and keep details in cause. |
| 3945 | const next = yield* reconnect.pipe( |
| 3946 | Effect.tapCause((cause) => |
| 3947 | Effect.logWarning( |
| 3948 | "Could not reconnect to the OpenCode event stream; failing the session.", |
| 3949 | cause, |
| 3950 | ).pipe(Effect.annotateLogs({ errorTag: causeErrorTag(cause) })), |
| 3951 | ), |
| 3952 | Effect.option, |
| 3953 | ); |
| 3954 | if (next._tag === "None") { |
| 3955 | return yield* lock.withPermit( |
| 3956 | failAll("The OpenCode event stream was lost and could not reconnect."), |
| 3957 | ); |
| 3958 | } |
| 3959 | streamFailure = undefined; |
| 3960 | const done = reconnected; |
| 3961 | reconnected = yield* Deferred.make<void>(); |
| 3962 | yield* Deferred.succeed(done, undefined); |
| 3963 | return yield* follow(next.value); |
| 3964 | }), |
| 3965 | ), |
| 3966 | ); |
| 3967 | // Subscribed before any session or prompt call, so no event of theirs is missed. |
| 3968 | yield* follow( |
| 3969 | yield* connection.events.pipe(Effect.provideService(Scope.Scope, currentScope)), |
| 3970 | ).pipe(Effect.forkScoped); |
| 3971 | |
| 3972 | yield* Effect.gen(function* () { |
| 3973 | const snapshots = yield* lock.withPermit( |
| 3974 | Effect.sync(() => |
| 3975 | [...shells] |
| 3976 | .filter(([, shell]) => shell.running) |
| 3977 | .map(([id, shell]) => ({ |
| 3978 | id, |
| 3979 | shell, |
| 3980 | cursor: shell.cursor, |
| 3981 | output: shell.output, |
| 3982 | directory: shell.state.directory, |
| 3983 | })), |
| 3984 | ), |
| 3985 | ); |
| 3986 | yield* Effect.forEach( |
| 3987 | snapshots, |
| 3988 | (snapshot) => |
| 3989 | fetchShellOutput(snapshot.id, snapshot).pipe( |
| 3990 | Effect.flatMap((next) => |
| 3991 | lock.withPermit( |
| 3992 | Effect.gen(function* () { |
| 3993 | const shell = shells.get(snapshot.id); |
| 3994 | // An exit, Stop, or recovery may have consumed this cursor while the request was in flight. |
| 3995 | if ( |
| 3996 | shell !== snapshot.shell || |
| 3997 | !shell.running || |
| 3998 | shell.cursor !== snapshot.cursor |
| 3999 | ) |
| 4000 | return; |
| 4001 | if (next.cursor <= shell.cursor) return; |
| 4002 | Object.assign(shell, next); |
| 4003 | yield* emitShell(snapshot.id, "running"); |
| 4004 | }), |
| 4005 | ), |
| 4006 | ), |
| 4007 | Effect.ignore({ log: true }), |
| 4008 | ), |
| 4009 | { concurrency: 4, discard: true }, |
| 4010 | ); |
| 4011 | }).pipe(Effect.repeat(Schedule.spaced("2 seconds")), Effect.forkScoped); |
| 4012 | |
| 4013 | // External servers outlive T3; stop their turns before losing observation. |
| 4014 | if (connection.external) { |
| 4015 | yield* Effect.addFinalizer(() => |
| 4016 | Effect.forEach( |
| 4017 | [...threads].filter(([, state]) => state.active !== undefined), |
| 4018 | ([sessionId]) => |
| 4019 | client.session |
| 4020 | .interrupt({ sessionID: Session.ID.make(sessionId) }) |
| 4021 | .pipe(Effect.timeout("1 second"), Effect.ignore({ log: true })), |
| 4022 | { concurrency: 8, discard: true }, |
| 4023 | ), |
| 4024 | ); |
| 4025 | } |
| 4026 | |
| 4027 | const readModels = (directory: string) => |
| 4028 | Effect.suspend(() => { |
| 4029 | const windows = contextWindows.get(directory) ?? new Map<string, number>(); |
| 4030 | contextWindows.set(directory, windows); |
| 4031 | const variants = modelVariants.get(directory) ?? new Map<string, ReadonlySet<string>>(); |
| 4032 | modelVariants.set(directory, variants); |
| 4033 | return client.model.list({ location: { directory } }).pipe( |
| 4034 | Effect.timeout("5 seconds"), |
| 4035 | Effect.tap((models) => |
| 4036 | Effect.sync(() => { |
| 4037 | for (const model of models.data) { |
| 4038 | const slug = `${model.providerID}/${model.id}`; |
| 4039 | windows.set(slug, model.limit.input ?? model.limit.context); |
| 4040 | variants.set(slug, new Set(model.variants.map((variant) => variant.id))); |
| 4041 | } |
| 4042 | }), |
| 4043 | ), |
| 4044 | Effect.ignore({ log: true }), |
| 4045 | ); |
| 4046 | }); |
| 4047 | const readModelsOnce = (cwd: string | null | undefined) => |
| 4048 | contextWindows.has(directoryOf(cwd)) ? Effect.void : readModels(directoryOf(cwd)); |
| 4049 | yield* readModels(session.cwd); |
| 4050 | |
| 4051 | const agentRules = new Map<string, ReadonlyMap<string, ReadonlyArray<Rule>>>(); |
| 4052 | const pathsFor = Effect.fnUntraced(function* ( |
| 4053 | directory: string, |
| 4054 | agents: ReadonlyArray<string>, |
| 4055 | ) { |
| 4056 | let known = agentRules.get(directory); |
| 4057 | if (known === undefined) { |
| 4058 | // A fresh server lists no agents for its first moments, like its models. |
| 4059 | const listed = yield* client.agent.list({ location: { directory } }).pipe( |
| 4060 | Effect.repeat({ |
| 4061 | until: (list) => list.data.length > 0, |
| 4062 | schedule: Schedule.spaced("250 millis"), |
| 4063 | }), |
| 4064 | Effect.timeout("5 seconds"), |
| 4065 | Effect.tapCause((cause) => |
| 4066 | Effect.logWarning( |
| 4067 | "Could not list OpenCode agents; their path rules are skipped.", |
| 4068 | cause, |
| 4069 | ).pipe(Effect.annotateLogs({ errorTag: causeErrorTag(cause) })), |
| 4070 | ), |
| 4071 | Effect.option, |
| 4072 | ); |
| 4073 | if (listed._tag === "None") return []; |
| 4074 | known = new Map( |
| 4075 | listed.value.data.map((agent) => [agent.id, agentPaths(agent.permissions)]), |
| 4076 | ); |
| 4077 | agentRules.set(directory, known); |
| 4078 | } |
| 4079 | const paths = new Map<string, Rule>(); |
| 4080 | for (const agent of agents) { |
| 4081 | for (const entry of known.get(agent) ?? []) { |
| 4082 | paths.set(`${entry.action}\u0000${entry.resource}`, entry); |
| 4083 | } |
| 4084 | } |
| 4085 | return [...paths.values()]; |
| 4086 | }); |
| 4087 | |
| 4088 | const rulesFor = Effect.fnUntraced(function* ( |
| 4089 | thread: Pick<ThreadState, "directory" | "agent" | "grants">, |
| 4090 | policy: RulesPolicy, |
| 4091 | appThreadId: string | null, |
| 4092 | ) { |
| 4093 | const plan = policy.interactionMode === "plan"; |
| 4094 | const paths = |
| 4095 | policy.runtimeMode === "full-access" && !plan |
| 4096 | ? [] |
| 4097 | : yield* pathsFor(thread.directory, plan ? [thread.agent, "plan"] : [thread.agent]); |
| 4098 | return sessionRules( |
| 4099 | policy, |
| 4100 | paths, |
| 4101 | policy.runtimeMode === "full-access" ? [] : thread.grants, |
| 4102 | appThreadId === null ? null : yield* mcpServerNameFor(appThreadId), |
| 4103 | ); |
| 4104 | }); |
| 4105 | |
| 4106 | const writeRules = Effect.fnUntraced(function* (state: ThreadState, policy: RulesPolicy) { |
| 4107 | const rules = yield* rulesFor(state, policy, rootOf(state).providerThread.appThreadId); |
| 4108 | if (!sameRules(state.rules, rules)) { |
| 4109 | yield* client.session.update({ |
| 4110 | sessionID: Session.ID.make(state.sessionId), |
| 4111 | permissions: rules, |
| 4112 | }); |
| 4113 | state.rules = rules; |
| 4114 | } |
| 4115 | state.policy = policy; |
| 4116 | }); |
| 4117 | |
| 4118 | const writeTitle = Effect.fnUntraced(function* (state: ThreadState, title: string) { |
| 4119 | const next = title.trim(); |
| 4120 | // An empty title asks OpenCode to generate one. |
| 4121 | if (next === "" || next === state.title) return; |
| 4122 | yield* client.session.update({ sessionID: Session.ID.make(state.sessionId), title: next }); |
| 4123 | state.title = next; |
| 4124 | }); |
| 4125 | |
| 4126 | const register = ( |
| 4127 | providerThread: OrchestrationV2ProviderThread, |
| 4128 | native: { |
| 4129 | readonly id: string; |
| 4130 | readonly model?: ModelRef | undefined; |
| 4131 | readonly agent?: string | undefined; |
| 4132 | readonly title?: string | undefined; |
| 4133 | readonly permissions?: ReadonlyArray<Rule> | undefined; |
| 4134 | }, |
| 4135 | directory: string, |
| 4136 | ) => { |
| 4137 | providerThread = withReportedModel(providerThread, native.model); |
| 4138 | const existing = threads.get(native.id); |
| 4139 | if (existing !== undefined) { |
| 4140 | existing.providerThread = providerThread; |
| 4141 | existing.model = native.model; |
| 4142 | existing.directory = directory; |
| 4143 | existing.agent = native.agent ?? existing.agent; |
| 4144 | existing.title = native.title; |
| 4145 | existing.rules = native.permissions; |
| 4146 | return existing; |
| 4147 | } |
| 4148 | const state = newThreadState(native.id, providerThread, directory, undefined); |
| 4149 | state.model = native.model; |
| 4150 | state.agent = native.agent ?? state.agent; |
| 4151 | state.title = native.title; |
| 4152 | state.rules = native.permissions; |
| 4153 | threads.set(native.id, state); |
| 4154 | return state; |
| 4155 | }; |
| 4156 | |
| 4157 | // Background reports can wake sessions into history being cut; rollback must wait for them too. |
| 4158 | const ensureQuiet = Effect.fnUntraced(function* ( |
| 4159 | sessionId: string, |
| 4160 | verb: "roll back" | "fork", |
| 4161 | ) { |
| 4162 | const state = threads.get(sessionId); |
| 4163 | // A stopped turn whose end was lost with the stream stays active here, |
| 4164 | // so OpenCode's own list decides whether it still runs. |
| 4165 | const stopped = state?.active?.interrupted === true ? state.active : undefined; |
| 4166 | const starts = state?.starts; |
| 4167 | const stillWorking = new ProviderAdapter.ProviderAdapterProtocolError({ |
| 4168 | driver: OPENCODE_PROVIDER, |
| 4169 | detail: `Cannot ${verb} OpenCode session ${sessionId} while it is still working`, |
| 4170 | }); |
| 4171 | const busyHere = |
| 4172 | state !== undefined && |
| 4173 | ((stopped === undefined && (state.active !== undefined || busy.has(sessionId))) || |
| 4174 | (verb === "roll back" && hasBackground(state))); |
| 4175 | const busyThere = |
| 4176 | !busyHere && |
| 4177 | (state === undefined || state.unsettled || stopped !== undefined) && |
| 4178 | sessionId in (yield* client.session.active().pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT))); |
| 4179 | if (busyHere || busyThere) return yield* stillWorking; |
| 4180 | if (state === undefined || stopped === undefined) return; |
| 4181 | yield* lock.withPermit( |
| 4182 | Effect.gen(function* () { |
| 4183 | // A run that started during the check may postdate OpenCode's answer. |
| 4184 | if (state.starts !== starts) return yield* stillWorking; |
| 4185 | if (state.active !== stopped) return; |
| 4186 | // Its end may still arrive late; unsettled swallows it and makes the next turn await its start. |
| 4187 | // OpenCode reported it idle, so any later start is a new run. |
| 4188 | state.unsettled = true; |
| 4189 | state.unsettledStarted = true; |
| 4190 | busy.delete(sessionId); |
| 4191 | yield* finishTurn(state, { status: "interrupted" }); |
| 4192 | }), |
| 4193 | ); |
| 4194 | }); |
| 4195 | |
| 4196 | const cancelStrandedSteers = Effect.fnUntraced(function* (state: ThreadState) { |
| 4197 | const sessionID = Session.ID.make(state.sessionId); |
| 4198 | for (const inboxID of Array.from(state.strandedSteers)) { |
| 4199 | const cancelled = yield* client.session.inbox |
| 4200 | .cancel({ sessionID, inboxID: SessionMessage.ID.make(inboxID) }) |
| 4201 | .pipe( |
| 4202 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 4203 | Effect.tapCause((cause) => |
| 4204 | Effect.logWarning("Could not take back an OpenCode steer.", cause), |
| 4205 | ), |
| 4206 | Effect.exit, |
| 4207 | Effect.map(Exit.isSuccess), |
| 4208 | ); |
| 4209 | if (cancelled) state.strandedSteers.delete(inboxID); |
| 4210 | } |
| 4211 | }); |
| 4212 | |
| 4213 | // OpenCode 2.0.18 executes even unstaged revert clears; wait so that end cannot settle a T3 turn. |
| 4214 | const clearRevert = Effect.fnUntraced(function* (sessionId: string) { |
| 4215 | const settled = yield* Deferred.make<void>(); |
| 4216 | clearing.set(sessionId, settled); |
| 4217 | yield* client.session.revert |
| 4218 | .clear({ sessionID: Session.ID.make(sessionId) }) |
| 4219 | .pipe( |
| 4220 | Effect.andThen(Deferred.await(settled)), |
| 4221 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 4222 | Effect.ensuring(Effect.sync(() => clearing.delete(sessionId))), |
| 4223 | ); |
| 4224 | stagedReverts.delete(sessionId); |
| 4225 | }); |
| 4226 | |
| 4227 | // Failed/interrupted rollbacks must clear staged reverts before the next prompt commits them. |
| 4228 | // Leave files to T3 checkpoints; history-only rewinds must preserve them. |
| 4229 | const rollBackTo = Effect.fnUntraced(function* ( |
| 4230 | sessionId: string, |
| 4231 | boundary: SessionMessage.ID, |
| 4232 | ) { |
| 4233 | const sessionID = Session.ID.make(sessionId); |
| 4234 | // Bound each step so unresponsive servers cannot hold the gate and block the next turn. |
| 4235 | yield* client.session.revert.stage({ sessionID, messageID: boundary, files: false }).pipe( |
| 4236 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 4237 | Effect.andThen( |
| 4238 | client.session.revert.commit({ sessionID }).pipe(Effect.timeout(REQUEST_REPLY_TIMEOUT)), |
| 4239 | ), |
| 4240 | Effect.onError(() => |
| 4241 | clearRevert(sessionId).pipe( |
| 4242 | Effect.tapError(() => Effect.sync(() => stagedReverts.add(sessionId))), |
| 4243 | Effect.ignore({ log: true }), |
| 4244 | ), |
| 4245 | ), |
| 4246 | ); |
| 4247 | }); |
| 4248 | |
| 4249 | // Rollback must validate full history before native mutation; forks only need prompts. |
| 4250 | const userMessages = (sessionId: string, types?: ReadonlyArray<"user" | "synthetic">) => |
| 4251 | Stream.fromIterable(types ?? [undefined]).pipe( |
| 4252 | Stream.flatMap((type) => |
| 4253 | OpenCode2Client.paginate( |
| 4254 | { |
| 4255 | sessionID: Session.ID.make(sessionId), |
| 4256 | limit: 100, |
| 4257 | ...(type === undefined ? {} : { type }), |
| 4258 | }, |
| 4259 | client.message.list, |
| 4260 | ), |
| 4261 | ), |
| 4262 | Stream.runCollect, |
| 4263 | Effect.map( |
| 4264 | (messages) => |
| 4265 | new Set( |
| 4266 | messages.flatMap((message) => |
| 4267 | message.type === "user" || message.type === "synthetic" ? [String(message.id)] : [], |
| 4268 | ), |
| 4269 | ), |
| 4270 | ), |
| 4271 | ); |
| 4272 | |
| 4273 | const snapshotOf = Effect.fnUntraced(function* ( |
| 4274 | providerThread: OrchestrationV2ProviderThread, |
| 4275 | sessionId: string, |
| 4276 | ) { |
| 4277 | const history = yield* OpenCode2Client.paginate( |
| 4278 | { sessionID: Session.ID.make(sessionId), order: "asc" as const, limit: 100 }, |
| 4279 | client.message.list, |
| 4280 | ).pipe(Stream.runCollect); |
| 4281 | const snapshotAt = yield* DateTime.now; |
| 4282 | const messages = history.flatMap((message): Array<OrchestrationV2ConversationMessage> => { |
| 4283 | const text = |
| 4284 | message.type === "user" |
| 4285 | ? message.text |
| 4286 | : message.type === "assistant" |
| 4287 | ? textOf(message.content) |
| 4288 | : ""; |
| 4289 | if (text.length === 0 || (message.type !== "user" && message.type !== "assistant")) { |
| 4290 | return []; |
| 4291 | } |
| 4292 | const createdAt = message.time.created; |
| 4293 | return [ |
| 4294 | { |
| 4295 | createdBy: message.type === "user" ? "user" : "agent", |
| 4296 | creationSource: "provider", |
| 4297 | id: idAllocator.derive.messageFromProviderItem({ |
| 4298 | driver, |
| 4299 | nativeItemId: message.id, |
| 4300 | }), |
| 4301 | threadId: providerThread.appThreadId ?? input.threadId, |
| 4302 | runId: null, |
| 4303 | nodeId: null, |
| 4304 | role: message.type, |
| 4305 | text, |
| 4306 | attachments: [], |
| 4307 | streaming: false, |
| 4308 | createdAt, |
| 4309 | updatedAt: createdAt, |
| 4310 | }, |
| 4311 | ]; |
| 4312 | }); |
| 4313 | const lastUser = history.findLast((message) => message.type === "user")?.id; |
| 4314 | const state = threads.get(sessionId); |
| 4315 | return { |
| 4316 | providerThread: { |
| 4317 | ...providerThread, |
| 4318 | providerSessionId: input.providerSessionId, |
| 4319 | nativeConversationHeadRef: lastUser === undefined ? null : ref(lastUser, "weak"), |
| 4320 | status: "idle" as const, |
| 4321 | updatedAt: snapshotAt, |
| 4322 | }, |
| 4323 | providerTurns: state === undefined ? [] : [...state.providerTurns.values()], |
| 4324 | messages, |
| 4325 | runtimeRequests: [], |
| 4326 | }; |
| 4327 | }); |
| 4328 | |
| 4329 | const promptText = Effect.fnUntraced(function* ( |
| 4330 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 4331 | ) { |
| 4332 | return (yield* providerMessageTextWithAttachmentPaths({ |
| 4333 | text: turnInput.message.text, |
| 4334 | attachments: turnInput.message.attachments, |
| 4335 | resolveAttachmentPath: host.resolveAttachmentPath, |
| 4336 | resolveExtractedTextPath: host.resolveExtractedTextPath, |
| 4337 | })).trim(); |
| 4338 | }); |
| 4339 | |
| 4340 | const promptFiles = Effect.fnUntraced(function* (attachments: ReadonlyArray<ChatAttachment>) { |
| 4341 | const files: Array<{ uri: string; name: string }> = []; |
| 4342 | // An external server may not share T3's attachment directory. |
| 4343 | if (connection.external) return files; |
| 4344 | for (const attachment of attachments) { |
| 4345 | if (!isProviderNativeImageAttachment(attachment)) continue; |
| 4346 | const path = host.resolveAttachmentPath(attachment); |
| 4347 | if (path === null) continue; |
| 4348 | // OpenCode rejects the whole prompt if an attached file is missing. |
| 4349 | const exists = yield* fileSystem.exists(path).pipe(Effect.orElseSucceed(() => false)); |
| 4350 | if (exists) files.push({ uri: NodeURL.pathToFileURL(path).href, name: attachment.name }); |
| 4351 | } |
| 4352 | return files; |
| 4353 | }); |
| 4354 | |
| 4355 | const removeMcp = (mcp: { readonly name: string; readonly directory: string }) => |
| 4356 | Effect.suspend(() => |
| 4357 | client.mcp.remove({ server: mcp.name, location: { directory: mcp.directory } }), |
| 4358 | ).pipe(Effect.timeout("5 seconds"), Effect.ignore({ log: true })); |
| 4359 | |
| 4360 | yield* Effect.addFinalizer(() => |
| 4361 | Effect.forEach( |
| 4362 | [...threads.values()].flatMap((state) => (state.mcp === undefined ? [] : [state.mcp])), |
| 4363 | removeMcp, |
| 4364 | { concurrency: 8, discard: true }, |
| 4365 | ), |
| 4366 | ); |
| 4367 | |
| 4368 | const prepareTurn = Effect.fnUntraced(function* ( |
| 4369 | sessionId: string, |
| 4370 | state: ThreadState, |
| 4371 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 4372 | ) { |
| 4373 | const mcpSession = yield* mcpSessions.read(turnInput.threadId); |
| 4374 | const directory = turnInput.runtimePolicy.cwd ?? host.paths.cwd; |
| 4375 | const name = yield* mcpServerNameFor(turnInput.threadId); |
| 4376 | // An external server may not reach T3's MCP endpoint, as with 1.x. |
| 4377 | const wanted = |
| 4378 | mcpSession === undefined || connection.external |
| 4379 | ? undefined |
| 4380 | : { name, directory, credential: mcpSession.authorizationHeader }; |
| 4381 | if ( |
| 4382 | state.mcp !== undefined && |
| 4383 | (wanted === undefined || |
| 4384 | state.mcp.directory !== wanted.directory || |
| 4385 | state.mcp.credential !== wanted.credential) |
| 4386 | ) { |
| 4387 | yield* removeMcp(state.mcp); |
| 4388 | state.mcp = undefined; |
| 4389 | } |
| 4390 | // Idle Location eviction drops runtime MCP servers without clearing T3's cache. |
| 4391 | // Re-adding an unchanged config keeps its existing connection. |
| 4392 | let mcpAvailable = false; |
| 4393 | if (wanted !== undefined) { |
| 4394 | const fresh = state.mcp === undefined; |
| 4395 | mcpAvailable = yield* client.mcp |
| 4396 | .add({ |
| 4397 | server: name, |
| 4398 | location: { directory }, |
| 4399 | config: new Mcp.RemoteConfig({ |
| 4400 | type: "remote", |
| 4401 | url: mcpSession!.endpoint, |
| 4402 | headers: { Authorization: wanted.credential }, |
| 4403 | oauth: false, |
| 4404 | }), |
| 4405 | }) |
| 4406 | .pipe( |
| 4407 | Effect.timeout(INVENTORY_TIMEOUT), |
| 4408 | Effect.as(true), |
| 4409 | Effect.catchCause((cause) => |
| 4410 | Effect.logWarning("Could not add T3 Code's MCP server to OpenCode.", cause).pipe( |
| 4411 | Effect.as(false), |
| 4412 | ), |
| 4413 | ), |
| 4414 | ); |
| 4415 | if (mcpAvailable) state.mcp = wanted; |
| 4416 | // Before 2.2.6, OpenCode loads a new server's tools 100 ms after it connects, and a prompt sent sooner lacks them. |
| 4417 | if (mcpAvailable && fresh && compareSemverVersions(connection.version, "2.2.6") < 0) { |
| 4418 | yield* Effect.sleep(MCP_TOOL_RELOAD_SETTLE); |
| 4419 | } |
| 4420 | } |
| 4421 | const instructions = [ |
| 4422 | buildRuntimeInstructions({ harness: "OpenCode", model: turnInput.modelSelection.model }), |
| 4423 | t3OrchestrationSystemPrompt(mcpAvailable, mcpSession?.capabilities?.has("device") === true), |
| 4424 | mcpAvailable |
| 4425 | ? "To wait for a background shell you started (tests, a build), call `t3_background_wait` with its shell ID before you end your turn. Do not mark work you leave running, or PRs." |
| 4426 | : undefined, |
| 4427 | ] |
| 4428 | .filter((part) => part !== undefined && part.length > 0) |
| 4429 | .join("\n\n"); |
| 4430 | if (instructions !== state.instructions) { |
| 4431 | yield* client.session.instructions.entry.put({ |
| 4432 | sessionID: Session.ID.make(sessionId), |
| 4433 | key: INSTRUCTIONS_KEY, |
| 4434 | value: instructions, |
| 4435 | }); |
| 4436 | state.instructions = instructions; |
| 4437 | } |
| 4438 | }); |
| 4439 | |
| 4440 | const markBefore = (sessionId: string, before: string | null) => |
| 4441 | Effect.sync(() => { |
| 4442 | const turn = threads.get(sessionId)?.active; |
| 4443 | if (turn !== undefined) turn.before = before; |
| 4444 | }); |
| 4445 | |
| 4446 | const beginTurn = Effect.fn("OpenCode2Adapter.beginTurn")(function* ( |
| 4447 | state: ThreadState, |
| 4448 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 4449 | awaitingStart: boolean, |
| 4450 | ) { |
| 4451 | const startedAt = yield* DateTime.now; |
| 4452 | const nativeTurnId = `${state.sessionId}:attempt:${turnInput.attemptId}`; |
| 4453 | const providerTurn: OrchestrationV2ProviderTurn = { |
| 4454 | id: idAllocator.derive.providerTurn({ driver, nativeTurnId }), |
| 4455 | providerThreadId: turnInput.providerThread.id, |
| 4456 | nodeId: turnInput.rootNodeId, |
| 4457 | runAttemptId: turnInput.attemptId, |
| 4458 | nativeTurnRef: ref( |
| 4459 | isContinuation(turnInput) |
| 4460 | ? wakeTurnId(state.sessionId, turnInput.attemptId) |
| 4461 | : turnPromptId(state.sessionId, turnInput.attemptId), |
| 4462 | "weak", |
| 4463 | ), |
| 4464 | ordinal: turnInput.providerTurnOrdinal, |
| 4465 | status: "running", |
| 4466 | startedAt, |
| 4467 | completedAt: null, |
| 4468 | }; |
| 4469 | const turn = makeTurn(turnInput, providerTurn, { scope: "", awaitingStart }); |
| 4470 | if (streamFailure !== undefined) { |
| 4471 | return yield* new ProviderAdapter.ProviderAdapterEventStreamError({ |
| 4472 | driver, |
| 4473 | providerSessionId: input.providerSessionId, |
| 4474 | cause: streamFailure, |
| 4475 | }); |
| 4476 | } |
| 4477 | state.active = turn; |
| 4478 | state.sessionScopedBackground = false; |
| 4479 | yield* emitProviderTurn(state, turn, providerTurn); |
| 4480 | state.providerThread = { |
| 4481 | ...state.providerThread, |
| 4482 | status: "active", |
| 4483 | firstRunOrdinal: state.providerThread.firstRunOrdinal ?? turnInput.runOrdinal, |
| 4484 | lastRunOrdinal: turnInput.runOrdinal, |
| 4485 | updatedAt: startedAt, |
| 4486 | }; |
| 4487 | yield* emitProviderThread(state); |
| 4488 | yield* setSessionStatus("running", null); |
| 4489 | return turn; |
| 4490 | }); |
| 4491 | |
| 4492 | const replay = Effect.fnUntraced(function* (wake: Wake) { |
| 4493 | wake.dropped = true; |
| 4494 | replaying = wake; |
| 4495 | yield* Effect.forEach(wake.events, (event) => route(event, sessionOfEvent(event), true), { |
| 4496 | discard: true, |
| 4497 | }).pipe(Effect.ensuring(Effect.sync(() => (replaying = undefined)))); |
| 4498 | }); |
| 4499 | |
| 4500 | const discardWakes = (caller: ThreadState, wakes: ReadonlyArray<Wake>) => { |
| 4501 | const retired = new Set<string>(); |
| 4502 | const retire = (childId: string) => { |
| 4503 | const info = announced.get(childId); |
| 4504 | if (info === undefined) return; |
| 4505 | announced.delete(childId); |
| 4506 | childOwners.delete(childId); |
| 4507 | strays.set(childId, caller); |
| 4508 | retired.add(childId); |
| 4509 | threads.get(info.parentID ?? "")?.stoppedChildren.add(childId); |
| 4510 | }; |
| 4511 | for (const wake of wakes) { |
| 4512 | wake.dropped = true; |
| 4513 | for (const childId of wake.children) retire(childId); |
| 4514 | } |
| 4515 | for (let grew = retired.size > 0; grew;) { |
| 4516 | grew = false; |
| 4517 | for (const [childId, info] of announced) { |
| 4518 | if (info.parentID === undefined || !retired.has(info.parentID)) continue; |
| 4519 | retire(childId); |
| 4520 | grew = true; |
| 4521 | } |
| 4522 | } |
| 4523 | }; |
| 4524 | |
| 4525 | // Stop strays serially outside lock; an unresponsive child must not block all events. |
| 4526 | const stopStrays = (thread: ThreadState) => |
| 4527 | Effect.forEach( |
| 4528 | [...strays].flatMap(([childId, caller]) => (rootOf(caller) === thread ? [childId] : [])), |
| 4529 | (childId) => |
| 4530 | client.session.interrupt({ sessionID: Session.ID.make(childId) }).pipe( |
| 4531 | Effect.asVoid, |
| 4532 | Effect.catchTags({ SessionNotFoundError: () => Effect.void }), |
| 4533 | Effect.timeout(INTERRUPT_TIMEOUT), |
| 4534 | Effect.tap(() => Effect.sync(() => strays.delete(childId))), |
| 4535 | Effect.ignore({ log: true }), |
| 4536 | ), |
| 4537 | { discard: true }, |
| 4538 | ); |
| 4539 | |
| 4540 | // User prompts join running autonomous executions, taking ownership and replacing their continuation. |
| 4541 | const takeRunningWake = Effect.fnUntraced(function* (state: ThreadState) { |
| 4542 | const wake = state.wakes.at(-1); |
| 4543 | if (wake?.running !== true) return; |
| 4544 | state.wakes.pop(); |
| 4545 | yield* replay(wake); |
| 4546 | for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session); |
| 4547 | yield* syncRosterAncestors(state); |
| 4548 | }); |
| 4549 | |
| 4550 | const runWake = Effect.fnUntraced(function* ( |
| 4551 | state: ThreadState, |
| 4552 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 4553 | ) { |
| 4554 | yield* beginTurn(state, turnInput, false); |
| 4555 | yield* lock.withPermit( |
| 4556 | Effect.gen(function* () { |
| 4557 | const index = state.wakes.findIndex( |
| 4558 | (held) => held.messageId === turnInput.message.messageId, |
| 4559 | ); |
| 4560 | if (index < 0) return yield* finishTurn(state, { status: "completed" }); |
| 4561 | // Continuations cannot reorder; earlier wakes stranded by cancel or failed dispatch would pin the session. |
| 4562 | discardWakes(state, state.wakes.splice(0, index)); |
| 4563 | yield* Effect.forkIn(stopStrays(state), sessionScope); |
| 4564 | const wake = state.wakes.shift()!; |
| 4565 | const turn = state.active; |
| 4566 | if (turn !== undefined && wake.after !== undefined) turn.before = wake.after; |
| 4567 | // Fork and rollback cut where its history begins. |
| 4568 | if (turn !== undefined && wake.first !== undefined) { |
| 4569 | turn.providerTurn = { ...turn.providerTurn, nativeTurnRef: ref(wake.first, "weak") }; |
| 4570 | } |
| 4571 | if (wake.running) state.unsettled = false; |
| 4572 | yield* replay(wake); |
| 4573 | for (const session of sessionsOf(state).toReversed()) yield* syncRoster(session); |
| 4574 | yield* syncRosterAncestors(state); |
| 4575 | }), |
| 4576 | ); |
| 4577 | }); |
| 4578 | |
| 4579 | const stopBackground = Effect.fnUntraced(function* (state: ThreadState) { |
| 4580 | for (const [id, shell] of shells) { |
| 4581 | if (shell.running && sessionsOf(state).includes(shell.state)) |
| 4582 | yield* lock.withPermit(stopShell(id)).pipe(Effect.ignore({ log: true })); |
| 4583 | } |
| 4584 | const calls = runningCalls(state).filter((call) => call.background); |
| 4585 | const callers = sessionsOf(state); |
| 4586 | // Ended subagent calls can run again to answer their own background reports. |
| 4587 | const followUps = callers.filter( |
| 4588 | (caller) => |
| 4589 | caller.subagent !== undefined && |
| 4590 | busy.has(caller.sessionId) && |
| 4591 | !isOrchestrationV2WorkActive(caller.subagent.call.status), |
| 4592 | ); |
| 4593 | // Child sessions are announced before call progress names them; use announcements to stop unnamed children. |
| 4594 | const announcedTo = (caller: ThreadState) => |
| 4595 | [...announced.values()].flatMap((info) => |
| 4596 | info.parentID === caller.sessionId ? [info.sessionID] : [], |
| 4597 | ); |
| 4598 | const childrenOf = (call: SubagentCall) => |
| 4599 | call.child === undefined ? announcedTo(call.state) : [call.child.sessionId]; |
| 4600 | const children = new Map( |
| 4601 | calls.flatMap((call) => childrenOf(call).map((childId) => [childId, call.state] as const)), |
| 4602 | ); |
| 4603 | const unreached = new Set<string>(); |
| 4604 | for (const [childId, caller] of children) { |
| 4605 | caller.stoppedChildren.add(childId); |
| 4606 | const reached = yield* client.session |
| 4607 | .interrupt({ sessionID: Session.ID.make(childId) }) |
| 4608 | .pipe( |
| 4609 | Effect.catchTags({ SessionNotFoundError: () => Effect.void }), |
| 4610 | Effect.timeout(INTERRUPT_TIMEOUT), |
| 4611 | Effect.tapCause((cause) => |
| 4612 | Effect.logWarning("Could not stop an OpenCode subagent.", cause), |
| 4613 | ), |
| 4614 | Effect.exit, |
| 4615 | Effect.map(Exit.isSuccess), |
| 4616 | ); |
| 4617 | if (!reached) unreached.add(childId); |
| 4618 | } |
| 4619 | for (const followUp of followUps) { |
| 4620 | yield* client.session |
| 4621 | .interrupt({ sessionID: Session.ID.make(followUp.sessionId) }) |
| 4622 | .pipe( |
| 4623 | Effect.catchTags({ SessionNotFoundError: () => Effect.void }), |
| 4624 | Effect.timeout(INTERRUPT_TIMEOUT), |
| 4625 | Effect.ignore({ log: true }), |
| 4626 | ); |
| 4627 | } |
| 4628 | yield* lock.withPermit( |
| 4629 | Effect.gen(function* () { |
| 4630 | for (const call of calls) { |
| 4631 | if (childrenOf(call).some((childId) => unreached.has(childId))) continue; |
| 4632 | yield* settleCall(call, "interrupted"); |
| 4633 | } |
| 4634 | for (const caller of callers) { |
| 4635 | for (const report of caller.reports.values()) { |
| 4636 | caller.stoppedChildren.add(report.childId); |
| 4637 | } |
| 4638 | } |
| 4639 | const running = state.wakes.some((wake) => wake.running); |
| 4640 | discardWakes(state, state.wakes.splice(0)); |
| 4641 | yield* syncRosterAncestors(state); |
| 4642 | if (running) { |
| 4643 | markUnsettled(state); |
| 4644 | yield* client.session |
| 4645 | .interrupt({ sessionID: Session.ID.make(state.sessionId) }) |
| 4646 | .pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore({ log: true })); |
| 4647 | } |
| 4648 | }), |
| 4649 | ); |
| 4650 | yield* stopStrays(state); |
| 4651 | }); |
| 4652 | |
| 4653 | const listSkills = (location: { readonly directory: string }) => |
| 4654 | client.skill.list({ location }).pipe( |
| 4655 | Effect.timeout(INVENTORY_TIMEOUT), |
| 4656 | Effect.map((list) => new Set<string>(list.data.map((skill) => skill.id))), |
| 4657 | Effect.orElseSucceed(() => new Set<string>()), |
| 4658 | ); |
| 4659 | |
| 4660 | // A directory OpenCode is still scanning lists none or some of its skills. |
| 4661 | // OpenCode 2.2.5 answers its model list only once the scan has ended (observed, not documented). |
| 4662 | const skillsMentioned = Effect.fnUntraced(function* ( |
| 4663 | location: { readonly directory: string }, |
| 4664 | mentions: ReadonlyArray<string>, |
| 4665 | ) { |
| 4666 | const known = yield* listSkills(location); |
| 4667 | if (mentions.some((name) => !known.has(name))) { |
| 4668 | yield* readModels(location.directory); |
| 4669 | for (const name of yield* listSkills(location)) known.add(name); |
| 4670 | } |
| 4671 | return mentions.filter((name) => known.has(name)); |
| 4672 | }); |
| 4673 | |
| 4674 | const submit = Effect.fnUntraced(function* ( |
| 4675 | sessionId: string, |
| 4676 | turnInput: ProviderAdapter.ProviderAdapterV2TurnInput, |
| 4677 | state: ThreadState, |
| 4678 | turn: ActiveTurn, |
| 4679 | ) { |
| 4680 | const sessionID = Session.ID.make(sessionId); |
| 4681 | const sending = () => { |
| 4682 | if (state.active !== turn || turn.interrupted) return false; |
| 4683 | turn.unsent = false; |
| 4684 | return true; |
| 4685 | }; |
| 4686 | const finishControl = lock.withPermit( |
| 4687 | Effect.suspend(() => |
| 4688 | state.active === turn ? finishTurn(state, { status: "completed" }) : Effect.void, |
| 4689 | ), |
| 4690 | ); |
| 4691 | const text = turnInput.message.text.trim(); |
| 4692 | const bare = turnInput.message.attachments.length === 0; |
| 4693 | const id = turnPromptId(sessionId, turnInput.attemptId); |
| 4694 | const goalCommand = supportsNativeGoals() ? parseGoalCommand(turnInput.message) : null; |
| 4695 | if (goalCommand?.type === "show") { |
| 4696 | if (!sending()) return; |
| 4697 | yield* readGoal(state); |
| 4698 | return yield* finishControl; |
| 4699 | } |
| 4700 | if (bare && text === "/compact") { |
| 4701 | if (!sending()) return; |
| 4702 | return yield* client.session.compact({ sessionID, id }).pipe(Effect.asVoid); |
| 4703 | } |
| 4704 | const location = { directory: turnInput.runtimePolicy.cwd ?? host.paths.cwd }; |
| 4705 | const command = bare ? commandOf(text) : undefined; |
| 4706 | if (command !== undefined) { |
| 4707 | const commands = yield* client.command.list({ location }).pipe( |
| 4708 | Effect.timeout(INVENTORY_TIMEOUT), |
| 4709 | Effect.map((list) => list.data), |
| 4710 | Effect.orElseSucceed(() => []), |
| 4711 | ); |
| 4712 | if (commands.some((entry) => entry.name === command.name)) { |
| 4713 | // session.command neither accepts nor returns our ID; record the preceding history boundary. |
| 4714 | const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 }); |
| 4715 | yield* markBefore(sessionId, newest.data[0]?.id ?? null); |
| 4716 | if (!sending()) return; |
| 4717 | if (goalCommand?.type === "pause" || goalCommand?.type === "clear") { |
| 4718 | // OpenCode rejects pausing or clearing a missing goal; Codex treats that as a no-op. |
| 4719 | yield* client.session.command({ sessionID, ...command }).pipe( |
| 4720 | Effect.catchIf( |
| 4721 | (error) => |
| 4722 | error._tag === "CommandExecutionError" && error.message === "No goal is set.", |
| 4723 | () => Effect.void, |
| 4724 | ), |
| 4725 | ); |
| 4726 | return yield* finishControl; |
| 4727 | } |
| 4728 | return yield* client.session.command({ sessionID, ...command }).pipe(Effect.asVoid); |
| 4729 | } |
| 4730 | } |
| 4731 | const mentions = skillMentions(text); |
| 4732 | const skills = mentions.length === 0 ? [] : yield* skillsMentioned(location, mentions); |
| 4733 | const files = yield* promptFiles(turnInput.message.attachments); |
| 4734 | const messageText = turnInput.resume ? "" : yield* promptText(turnInput); |
| 4735 | if (!sending()) return; |
| 4736 | return yield* client.session |
| 4737 | .prompt({ |
| 4738 | sessionID, |
| 4739 | id, |
| 4740 | text: messageText, |
| 4741 | ...(files.length === 0 ? {} : { files }), |
| 4742 | ...(skills.length === 0 |
| 4743 | ? {} |
| 4744 | : { skills: skills.map((id) => ({ id: Skill.ID.make(id) })) }), |
| 4745 | }) |
| 4746 | .pipe(Effect.asVoid); |
| 4747 | }); |
| 4748 | |
| 4749 | const runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime = { |
| 4750 | instanceId, |
| 4751 | driver, |
| 4752 | providerSessionId: input.providerSessionId, |
| 4753 | get providerSession() { |
| 4754 | return session; |
| 4755 | }, |
| 4756 | events: Stream.fromQueue(events), |
| 4757 | // Idle release must wait for background children and held wakes after parent settlement. |
| 4758 | hasPendingBackgroundWork: Effect.sync(() => [...threads.values()].some(owesWork)), |
| 4759 | hasPendingBackgroundWorkForThread: (providerThread) => |
| 4760 | Effect.sync(() => { |
| 4761 | const nativeId = providerThread.nativeThreadRef?.nativeId; |
| 4762 | const state = nativeId == null ? undefined : threads.get(nativeId); |
| 4763 | return state !== undefined && hasBackground(state); |
| 4764 | }), |
| 4765 | getModelContextWindow: (selection, cwd) => |
| 4766 | selection.instanceId === instanceId |
| 4767 | ? windowOf(cwd === undefined ? session.cwd : cwd, selection.model) |
| 4768 | : undefined, |
| 4769 | ensureThread: Effect.fn("OpenCode2Adapter.ensureThread")( |
| 4770 | function* (threadInput) { |
| 4771 | if (threadInput.existingProviderThread?.nativeThreadRef != null) { |
| 4772 | return yield* runtime.resumeThread({ |
| 4773 | providerThread: threadInput.existingProviderThread, |
| 4774 | threadId: threadInput.threadId, |
| 4775 | modelSelection: threadInput.modelSelection, |
| 4776 | runtimePolicy: threadInput.runtimePolicy, |
| 4777 | }); |
| 4778 | } |
| 4779 | yield* readModelsOnce(threadInput.runtimePolicy.cwd); |
| 4780 | const model = listedModelRef(threadInput.modelSelection, threadInput.runtimePolicy.cwd); |
| 4781 | if (model === undefined) { |
| 4782 | return yield* new ProviderAdapter.ProviderAdapterProtocolError({ |
| 4783 | driver: OPENCODE_PROVIDER, |
| 4784 | detail: malformedModel(threadInput.modelSelection.model), |
| 4785 | }); |
| 4786 | } |
| 4787 | const directory = threadInput.runtimePolicy.cwd ?? host.paths.cwd; |
| 4788 | const policy = threadInput.runtimePolicy; |
| 4789 | const permissions = yield* rulesFor( |
| 4790 | { directory, agent: "build", grants: [] }, |
| 4791 | policy, |
| 4792 | threadInput.threadId, |
| 4793 | ); |
| 4794 | const title = threadInput.title?.trim() || undefined; |
| 4795 | // A session created with a title is never titled by OpenCode's own model. |
| 4796 | const created = yield* client.session.create({ |
| 4797 | location: Location.PublicRef.make({ directory: AbsolutePath.make(directory) }), |
| 4798 | model, |
| 4799 | permissions, |
| 4800 | ...(title === undefined ? {} : { title }), |
| 4801 | }); |
| 4802 | const createdAt = yield* DateTime.now; |
| 4803 | const providerThread: OrchestrationV2ProviderThread = { |
| 4804 | ...(threadInput.existingProviderThread ?? { |
| 4805 | id: idAllocator.derive.providerThread({ driver, nativeThreadId: created.id }), |
| 4806 | driver, |
| 4807 | providerInstanceId: instanceId, |
| 4808 | appThreadId: threadInput.threadId, |
| 4809 | ownerNodeId: null, |
| 4810 | firstRunOrdinal: null, |
| 4811 | lastRunOrdinal: null, |
| 4812 | handoffIds: [], |
| 4813 | forkedFrom: null, |
| 4814 | createdAt, |
| 4815 | }), |
| 4816 | providerSessionId: input.providerSessionId, |
| 4817 | nativeThreadRef: ref(created.id), |
| 4818 | nativeConversationHeadRef: null, |
| 4819 | status: "idle", |
| 4820 | updatedAt: createdAt, |
| 4821 | }; |
| 4822 | const state = register( |
| 4823 | providerThread, |
| 4824 | { |
| 4825 | id: created.id, |
| 4826 | model: created.model, |
| 4827 | agent: created.agent, |
| 4828 | title: title ?? created.title, |
| 4829 | permissions, |
| 4830 | }, |
| 4831 | directory, |
| 4832 | ); |
| 4833 | state.policy = policy; |
| 4834 | return state.providerThread; |
| 4835 | }, |
| 4836 | (effect, threadInput) => |
| 4837 | effect.pipe( |
| 4838 | Effect.mapError((cause) => |
| 4839 | isProviderAdapterError(cause) |
| 4840 | ? cause |
| 4841 | : new ProviderAdapter.ProviderAdapterEnsureThreadError({ |
| 4842 | driver, |
| 4843 | threadId: threadInput.threadId, |
| 4844 | cause, |
| 4845 | }), |
| 4846 | ), |
| 4847 | ), |
| 4848 | ), |
| 4849 | resumeThread: Effect.fn("OpenCode2Adapter.resumeThread")( |
| 4850 | function* (threadInput) { |
| 4851 | const sessionId = yield* sessionIdOf(threadInput.providerThread); |
| 4852 | if (threadInput.runtimePolicy !== undefined) { |
| 4853 | yield* readModelsOnce(threadInput.runtimePolicy.cwd); |
| 4854 | } |
| 4855 | const native = yield* client.session.get({ sessionID: Session.ID.make(sessionId) }); |
| 4856 | const providerThread: OrchestrationV2ProviderThread = { |
| 4857 | ...threadInput.providerThread, |
| 4858 | providerSessionId: input.providerSessionId, |
| 4859 | status: "idle", |
| 4860 | updatedAt: yield* DateTime.now, |
| 4861 | }; |
| 4862 | const cwd = threadInput.runtimePolicy?.cwd; |
| 4863 | const loaded = threads.has(sessionId); |
| 4864 | const state = register(providerThread, native, cwd ?? native.location.directory); |
| 4865 | if (!loaded) yield* stopLeftoverRequests(state); |
| 4866 | if (!loaded && supportsNativeGoals()) { |
| 4867 | yield* readGoal(state).pipe( |
| 4868 | Effect.timeout(INVENTORY_TIMEOUT), |
| 4869 | Effect.ignore({ log: true }), |
| 4870 | ); |
| 4871 | } |
| 4872 | if (!loaded) yield* recoverShells(state).pipe(Effect.ignore({ log: true })); |
| 4873 | yield* writeRules(state, threadInput.runtimePolicy ?? state.policy); |
| 4874 | if (cwd != null && native.location.directory !== cwd) { |
| 4875 | yield* client.session.move({ |
| 4876 | sessionID: Session.ID.make(sessionId), |
| 4877 | directory: AbsolutePath.make(cwd), |
| 4878 | }); |
| 4879 | } |
| 4880 | return state.providerThread; |
| 4881 | }, |
| 4882 | (effect, threadInput) => |
| 4883 | effect.pipe( |
| 4884 | Effect.mapError((cause) => |
| 4885 | isProviderAdapterError(cause) |
| 4886 | ? cause |
| 4887 | : new ProviderAdapter.ProviderAdapterResumeThreadError({ |
| 4888 | driver, |
| 4889 | providerSessionId: input.providerSessionId, |
| 4890 | providerThreadId: threadInput.providerThread.id, |
| 4891 | cause, |
| 4892 | }), |
| 4893 | ), |
| 4894 | ), |
| 4895 | ), |
| 4896 | compactThread: (turnInput) => |
| 4897 | runtime.startTurn({ ...turnInput, message: { ...turnInput.message, text: "/compact" } }), |
| 4898 | resumeTurn: (input) => runtime.startTurn(ProviderAdapter.resumeTurnInput(input)), |
| 4899 | startTurn: Effect.fn("OpenCode2Adapter.startTurn")( |
| 4900 | function* (turnInput) { |
| 4901 | // Waited out before the session's gate, so a rollback or fork is not |
| 4902 | // held behind a reconnect. |
| 4903 | if (streamFailure !== undefined) { |
| 4904 | yield* Deferred.await(reconnected).pipe(Effect.timeout(RECONNECT_WAIT), Effect.ignore); |
| 4905 | } |
| 4906 | if (streamFailure !== undefined) { |
| 4907 | return yield* new ProviderAdapter.ProviderAdapterEventStreamError({ |
| 4908 | driver, |
| 4909 | providerSessionId: input.providerSessionId, |
| 4910 | cause: streamFailure, |
| 4911 | }); |
| 4912 | } |
| 4913 | // Gate checks/setup so rollback/fork sees either no turn or the installed turn; prompt outside it. |
| 4914 | const started = yield* exclusive(turnInput.providerThread)( |
| 4915 | Effect.gen(function* () { |
| 4916 | const sessionId = yield* sessionIdOf(turnInput.providerThread); |
| 4917 | const state = threads.get(sessionId); |
| 4918 | if (state === undefined) { |
| 4919 | return yield* new ProviderAdapter.ProviderAdapterProtocolError({ |
| 4920 | driver: OPENCODE_PROVIDER, |
| 4921 | detail: `OpenCode session ${sessionId} is not registered`, |
| 4922 | }); |
| 4923 | } |
| 4924 | if (state.active !== undefined) { |
| 4925 | return yield* new ProviderAdapter.ProviderAdapterProtocolError({ |
| 4926 | driver: OPENCODE_PROVIDER, |
| 4927 | detail: `OpenCode session ${sessionId} already has an active turn`, |
| 4928 | reason: "previous_turn_active", |
| 4929 | }); |
| 4930 | } |
| 4931 | if (isContinuation(turnInput)) return yield* runWake(state, turnInput); |
| 4932 | const afterUnsettled = state.unsettled; |
| 4933 | let stillStopping = false; |
| 4934 | if (state.unsettled) { |
| 4935 | const active = yield* client.session |
| 4936 | .active() |
| 4937 | .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT)); |
| 4938 | stillStopping = sessionId in active; |
| 4939 | if (stillStopping) { |
| 4940 | yield* client.session |
| 4941 | .interrupt({ sessionID: Session.ID.make(sessionId) }) |
| 4942 | .pipe(Effect.timeout(INTERRUPT_TIMEOUT), Effect.ignore({ log: true })); |
| 4943 | } else { |
| 4944 | state.unsettled = false; |
| 4945 | } |
| 4946 | } |
| 4947 | const begin = beginTurn(state, turnInput, afterUnsettled); |
| 4948 | if (stillStopping) { |
| 4949 | yield* begin; |
| 4950 | return yield* finishTurn(state, { |
| 4951 | status: "failed", |
| 4952 | failure: makeProviderFailure({ |
| 4953 | message: OPENCODE_2_STILL_STOPPING, |
| 4954 | class: "provider_error", |
| 4955 | }), |
| 4956 | }); |
| 4957 | } |
| 4958 | const model = listedModelRef(turnInput.modelSelection, turnInput.runtimePolicy.cwd); |
| 4959 | if (model === undefined) { |
| 4960 | yield* begin; |
| 4961 | return yield* finishTurn(state, { |
| 4962 | status: "failed", |
| 4963 | failure: makeProviderFailure({ |
| 4964 | message: malformedModel(turnInput.modelSelection.model), |
| 4965 | class: "validation_error", |
| 4966 | }), |
| 4967 | }); |
| 4968 | } |
| 4969 | // Switch to the plan agent before writing rules to retain its own path allows. |
| 4970 | const agent = agentFor(turnInput); |
| 4971 | if (agent !== state.agent) { |
| 4972 | yield* client.session.switchAgent({ |
| 4973 | sessionID: Session.ID.make(sessionId), |
| 4974 | agent: Agent.ID.make(agent), |
| 4975 | }); |
| 4976 | state.agent = agent; |
| 4977 | } |
| 4978 | // Refresh stale mode rules; running subagent updates are best effort because they outlive this turn. |
| 4979 | yield* writeRules(state, turnInput.runtimePolicy); |
| 4980 | yield* writeTitle(state, turnInput.appThread.title).pipe( |
| 4981 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 4982 | Effect.ignore({ log: true }), |
| 4983 | ); |
| 4984 | for (const call of runningCalls(state)) { |
| 4985 | if (call.child === undefined) continue; |
| 4986 | yield* writeRules(call.child, turnInput.runtimePolicy).pipe( |
| 4987 | Effect.timeout(REQUEST_REPLY_TIMEOUT), |
| 4988 | Effect.ignore({ log: true }), |
| 4989 | ); |
| 4990 | } |
| 4991 | if (!sameModel(model, state.model)) { |
| 4992 | yield* client.session.switchModel({ sessionID: Session.ID.make(sessionId), model }); |
| 4993 | state.model = model; |
| 4994 | } |
| 4995 | // Old undelivered steers would run first; failed rollback stages would commit on this prompt. |
| 4996 | yield* cancelStrandedSteers(state); |
| 4997 | if (stagedReverts.has(sessionId)) yield* clearRevert(sessionId); |
| 4998 | yield* prepareTurn(sessionId, state, turnInput); |
| 4999 | const turn = yield* begin; |
| 5000 | turn.unsent = true; |
Showing first 5,000 of 5,560 lines.
View raw