The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { pipe } from "effect/Function"; |
| 2 | import * as DocumentText from "../../provider/DocumentText.ts"; |
| 3 | import { brokenRuntimeError } from "../../provider/providerCompatibility.ts"; |
| 4 | import { revertCodexThread } from "../../provider/CodexThreadRevert.ts"; |
| 5 | import { historyResponseItems } from "@t3tools/provider-core/server/handoffBudget"; |
| 6 | import { makeProviderTextDeltaCoalescer } from "./ProviderTextDeltaCoalescer.ts"; |
| 7 | import { |
| 8 | mcpToolPresentation, |
| 9 | type McpToolPresentation, |
| 10 | } from "../../provider/CodexToolPresentation.ts"; |
| 11 | import { |
| 12 | makeCodexTurnTokenUsageState, |
| 13 | getCodexTurnAccumulator, |
| 14 | accumulateCodexTurnTokenUsage, |
| 15 | completeCodexTurnTokenUsage, |
| 16 | type CodexTurnTokenUsageState, |
| 17 | } from "../../provider/CodexTurnTokenUsage.ts"; |
| 18 | import type { ManagedServerProvider } from "@t3tools/provider-core/server/snapshot"; |
| 19 | import type { CodexEffectiveRuntime } from "../../provider/CodexManagedRuntime.ts"; |
| 20 | import { classifyCodexManagedError } from "../../provider/CodexManagedErrors.ts"; |
| 21 | import { |
| 22 | buildCodexInitializeParams, |
| 23 | codexAppServerEnvironment, |
| 24 | codexDefaultReasoningEffortOverride, |
| 25 | } from "../../provider/CodexProvider.ts"; |
| 26 | import { |
| 27 | codexRateLimitsToUpdate, |
| 28 | mergeCodexRateLimits, |
| 29 | codexMessageResetAt, |
| 30 | codexTimeZone, |
| 31 | codexUsageLimitResetAt, |
| 32 | type CodexRateLimitSnapshot, |
| 33 | } from "../../provider/codexUsageLimits.ts"; |
| 34 | import { |
| 35 | CodexSettings, |
| 36 | defaultInstanceIdForDriver, |
| 37 | isOrchestrationV2WorkActive, |
| 38 | type OrchestrationV2GoalCommand, |
| 39 | OrchestrationV2ProviderGoal, |
| 40 | parseGoalCommand, |
| 41 | ProviderDriverKind, |
| 42 | ProviderMcpSignInError, |
| 43 | ProviderSetupError, |
| 44 | type ServerProviderCompatibilityAdvisory, |
| 45 | type ServerProviderModel, |
| 46 | isDelegatedAppThread, |
| 47 | ThreadId, |
| 48 | } from "@t3tools/contracts"; |
| 49 | import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens"; |
| 50 | import { AgentScope } from "@t3tools/shared/AgentScope"; |
| 51 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 52 | import { |
| 53 | COMPUTER_USE_TOOL_SOURCE, |
| 54 | dynamicToolSurface, |
| 55 | dynamicToolTitle, |
| 56 | } from "@t3tools/shared/toolActivity"; |
| 57 | import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model"; |
| 58 | import { appendGeneratedImageEmbeds } from "@t3tools/shared/generatedImageMarkdown"; |
| 59 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 60 | import { mcpToolResultOutput } from "@t3tools/shared/toolOutput"; |
| 61 | import { oauthCallbackUrl } from "@t3tools/shared/oauthCallback"; |
| 62 | import type { |
| 63 | ChatAttachment, |
| 64 | OrchestrationV2AppThread, |
| 65 | OrchestrationV2ConversationMessage, |
| 66 | OrchestrationV2ExecutionNode, |
| 67 | ModelSelection, |
| 68 | OrchestrationV2PlanArtifact, |
| 69 | OrchestrationV2ProviderCapabilities, |
| 70 | OrchestrationV2ProviderFailure, |
| 71 | OrchestrationV2ProviderRetry, |
| 72 | OrchestrationV2ProviderSession, |
| 73 | OrchestrationV2ProviderThread, |
| 74 | OrchestrationV2ProviderTurn, |
| 75 | OrchestrationV2PlanStep, |
| 76 | OrchestrationV2RuntimeRequest, |
| 77 | OrchestrationV2Subagent, |
| 78 | OrchestrationV2TurnItem, |
| 79 | ProviderUserInputAnswers, |
| 80 | ProviderApprovalDecision, |
| 81 | ProviderApprovalOption, |
| 82 | ProviderRequestKind, |
| 83 | ProviderThreadId, |
| 84 | ProviderTurnId, |
| 85 | ProviderInstanceId, |
| 86 | RuntimeMode, |
| 87 | } from "@t3tools/contracts"; |
| 88 | import * as CodexClient from "effect-codex-app-server/client"; |
| 89 | import * as CodexErrors from "effect-codex-app-server/errors"; |
| 90 | import * as CodexSchema from "effect-codex-app-server/schema"; |
| 91 | import * as Cause from "effect/Cause"; |
| 92 | import * as Context from "effect/Context"; |
| 93 | import * as Digest from "effect/crypto/Digest"; |
| 94 | import * as DateTime from "effect/DateTime"; |
| 95 | import * as Deferred from "effect/Deferred"; |
| 96 | import * as Effect from "effect/Effect"; |
| 97 | import * as Exit from "effect/Exit"; |
| 98 | import * as Fiber from "effect/Fiber"; |
| 99 | import * as FileSystem from "effect/FileSystem"; |
| 100 | import * as Function from "effect/Function"; |
| 101 | import * as Layer from "effect/Layer"; |
| 102 | import * as Option from "effect/Option"; |
| 103 | import * as Path from "effect/Path"; |
| 104 | import * as Queue from "effect/Queue"; |
| 105 | import * as Ref from "effect/Ref"; |
| 106 | import * as Schema from "effect/Schema"; |
| 107 | import * as Scope from "effect/Scope"; |
| 108 | import * as Semaphore from "effect/Semaphore"; |
| 109 | import * as Stream from "effect/Stream"; |
| 110 | import { FetchHttpClient, HttpClient } from "effect/http"; |
| 111 | import { ChildProcess, ChildProcessSpawner } from "effect/process"; |
| 112 | |
| 113 | import { resolveAttachmentPath, resolveAttachmentPathById } from "../../attachmentStore.ts"; |
| 114 | import * as PortScanner from "../../preview/PortScanner.ts"; |
| 115 | import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts"; |
| 116 | import { ServerConfig } from "../../config.ts"; |
| 117 | import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; |
| 118 | import { buildCodexAdditionalContext } from "../../provider/CodexDeveloperInstructions.ts"; |
| 119 | import { |
| 120 | describeMcpElicitation, |
| 121 | toMcpElicitationResponse, |
| 122 | } from "../../provider/CodexMcpElicitation.ts"; |
| 123 | import { |
| 124 | codexHomeLaunchArgs, |
| 125 | materializeCodexShadowHome, |
| 126 | resolveCodexHomeLayout, |
| 127 | } from "../../provider/Drivers/CodexHomeLayout.ts"; |
| 128 | import { |
| 129 | boundProviderEventForLogging, |
| 130 | shouldPersistProviderEvent, |
| 131 | } from "../../provider/EventNdjsonLogger.ts"; |
| 132 | import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers"; |
| 133 | import { codexAppServerArgs, resolveCodexLaunchArgs } from "../../provider/codexLaunchArgs.ts"; |
| 134 | import { mergeProviderInstanceEnvironment } from "@t3tools/provider-core/server/instanceEnvironment"; |
| 135 | import * as McpProviderSession from "@t3tools/provider-core/server/mcpSession"; |
| 136 | import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; |
| 137 | import { |
| 138 | MCP_APP_EXTENSION_ID, |
| 139 | MCP_APP_MIME_TYPE, |
| 140 | MCP_APP_OUTPUT_KEY, |
| 141 | MCP_APP_RESOURCE_SCHEME, |
| 142 | } from "@t3tools/shared/mcpApp"; |
| 143 | import { snapshotMcpApp } from "../../mcpApps/McpAppSnapshot.ts"; |
| 144 | import { |
| 145 | ProviderAdapterDriverCreateError, |
| 146 | type ProviderAdapterDriverCreateInput, |
| 147 | } from "@t3tools/provider-core/server/adapterDriver"; |
| 148 | import * as ProviderContinuationRequests from "@t3tools/provider-core/server/ProviderContinuationRequests"; |
| 149 | import { backgroundWorkNotification } from "@t3tools/provider-core/server/notification"; |
| 150 | import { |
| 151 | makeProviderFailure, |
| 152 | makeProviderFailureTurnItem, |
| 153 | makeProviderRetryTurnItem, |
| 154 | PROVIDER_RETRY_BUDGET_MS, |
| 155 | } from "@t3tools/provider-core/server/failure"; |
| 156 | import { turnScopedSelectionTransition } from "@t3tools/provider-core/server/selectionTransition"; |
| 157 | import { |
| 158 | isProviderNativeImageAttachment, |
| 159 | providerMessageTextWithAttachmentPaths, |
| 160 | } from "@t3tools/provider-core/server/attachmentPrompt"; |
| 161 | import { |
| 162 | makeSubagentChildThread, |
| 163 | makeSubagentConversationArtifacts, |
| 164 | subagentThreadTitle, |
| 165 | } from "@t3tools/provider-core/server/subagentProjection"; |
| 166 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 167 | import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; |
| 168 | |
| 169 | const CODEX_PROVIDER = ProviderDriverKind.make("codex"); |
| 170 | const CODEX_CAPACITY_MAX_RETRIES = 5; |
| 171 | // How long Stop waits for Codex to end the turn before the user is offered Force stop. |
| 172 | const CODEX_STOP_CONFIRM_TIMEOUT_MS = 10_000; |
| 173 | export const CODEX_DRIVER_KIND = CODEX_PROVIDER; |
| 174 | export const CODEX_DEFAULT_INSTANCE_ID = defaultInstanceIdForDriver(CODEX_DRIVER_KIND); |
| 175 | |
| 176 | type CodexFileChangeKinds = Readonly< |
| 177 | Record<string, CodexSchema.V2ItemStartedNotification__PatchChangeKind> |
| 178 | >; |
| 179 | |
| 180 | function codexFileChangeApprovalPrompt(input: { |
| 181 | readonly reason?: string | null; |
| 182 | readonly grantRoot?: string | null; |
| 183 | readonly fileChanges?: CodexFileChangeKinds; |
| 184 | }): string | undefined { |
| 185 | const reason = input.reason?.trim(); |
| 186 | if (reason) return reason; |
| 187 | const entries = Object.entries(input.fileChanges ?? {}).toSorted(([left], [right]) => |
| 188 | left.localeCompare(right), |
| 189 | ); |
| 190 | if (entries.length > 0) { |
| 191 | const described = entries.slice(0, 20).map(([path, change]) => { |
| 192 | const movePath = change.type === "update" ? change.move_path : undefined; |
| 193 | return movePath ? `${change.type} ${path} -> ${movePath}` : `${change.type} ${path}`; |
| 194 | }); |
| 195 | const remaining = entries.length - described.length; |
| 196 | return remaining > 0 ? `${described.join("\n")}\n+${remaining} more` : described.join("\n"); |
| 197 | } |
| 198 | return input.grantRoot?.trim() || undefined; |
| 199 | } |
| 200 | |
| 201 | export function normalizeCodexThreadLoadModelSelection(selection: ModelSelection): ModelSelection { |
| 202 | // Codex applies effort on turn/start; resume discards its pinned request effort. |
| 203 | const { options, ...rest } = selection; |
| 204 | const loadOptions = options?.filter((option) => option.id !== "reasoningEffort"); |
| 205 | return { ...rest, ...(loadOptions?.length ? { options: loadOptions } : {}) }; |
| 206 | } |
| 207 | |
| 208 | // Reasoning-effort changes preserve the tokenizer and context window; other changes need fresh telemetry. |
| 209 | export function canReuseCodexContextUsage(previous: ModelSelection, next: ModelSelection): boolean { |
| 210 | return modelSelectionsEqual( |
| 211 | { |
| 212 | ...previous, |
| 213 | options: (previous.options ?? []).filter((option) => option.id !== "reasoningEffort"), |
| 214 | }, |
| 215 | { ...next, options: (next.options ?? []).filter((option) => option.id !== "reasoningEffort") }, |
| 216 | ); |
| 217 | } |
| 218 | |
| 219 | export function codexProviderTurnTokenUsage( |
| 220 | tokenUsage: CodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"], |
| 221 | updatedAt: string, |
| 222 | ) { |
| 223 | return { |
| 224 | usedTokens: Math.max(0, tokenUsage.last.totalTokens), |
| 225 | maxTokens: tokenUsage.modelContextWindow ?? null, |
| 226 | inputTokens: Math.max(0, tokenUsage.last.inputTokens), |
| 227 | cachedInputTokens: Math.max(0, tokenUsage.last.cachedInputTokens), |
| 228 | outputTokens: Math.max(0, tokenUsage.last.outputTokens), |
| 229 | reasoningOutputTokens: Math.max(0, tokenUsage.last.reasoningOutputTokens), |
| 230 | updatedAt, |
| 231 | }; |
| 232 | } |
| 233 | const CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS = 50; |
| 234 | // Plan flushes store three copies; use the client's assistant-text cadence. |
| 235 | const CODEX_PLAN_DELTA_FLUSH_INTERVAL_MS = 400; |
| 236 | const CodexBackgroundTerminalTerminateResponse = Schema.Struct({ |
| 237 | terminated: Schema.Boolean, |
| 238 | }); |
| 239 | const CodexBackgroundTerminalsListResponse = Schema.Struct({ |
| 240 | data: Schema.Array( |
| 241 | Schema.Struct({ |
| 242 | processId: Schema.String, |
| 243 | }), |
| 244 | ), |
| 245 | nextCursor: Schema.NullOr(Schema.String), |
| 246 | }); |
| 247 | type CodexBackgroundTerminalsListPage = typeof CodexBackgroundTerminalsListResponse.Type; |
| 248 | const decodeCodexBackgroundTerminalTerminateResponse = Schema.decodeUnknownEffect( |
| 249 | CodexBackgroundTerminalTerminateResponse, |
| 250 | ); |
| 251 | const decodeCodexBackgroundTerminalsListResponse = Schema.decodeUnknownEffect( |
| 252 | CodexBackgroundTerminalsListResponse, |
| 253 | ); |
| 254 | // Initialize normally answers in under a second; leave room for a slow first launch. |
| 255 | const CODEX_INITIALIZE_TIMEOUT = "30 seconds"; |
| 256 | const CodexThreadSampleResponse = Schema.Struct({ text: Schema.NullOr(Schema.String) }); |
| 257 | const decodeCodexThreadSampleResponse = Schema.decodeUnknownEffect(CodexThreadSampleResponse); |
| 258 | export const CODEX_PROMPT_SUGGESTION_PROMPT = |
| 259 | "Predict the next message the user will send in this conversation. Reply with only that message, written as the user would type it, in under 20 words. Do not use tools. If there is no clear next step, reply with nothing."; |
| 260 | const CODEX_CLIENT_CAPABILITIES = { |
| 261 | experimentalApi: true, |
| 262 | optOutNotificationMethods: ["turn/diff/updated"], |
| 263 | extensions: { [MCP_APP_EXTENSION_ID]: { mimeTypes: [MCP_APP_MIME_TYPE] } }, |
| 264 | } as const; |
| 265 | |
| 266 | export const CodexProviderCapabilitiesV2 = { |
| 267 | sessions: { |
| 268 | supportsMultipleProviderThreadsPerSession: true, |
| 269 | supportsModelSwitchInSession: true, |
| 270 | supportsProviderSwitchingViaHandoff: true, |
| 271 | supportsRuntimeModeSwitchInSession: true, |
| 272 | pendingRequestsSurviveRestart: false, |
| 273 | }, |
| 274 | threads: { |
| 275 | canCreateEmptyThread: true, |
| 276 | canReadThreadSnapshot: true, |
| 277 | canRollbackThread: true, |
| 278 | canForkThread: true, |
| 279 | canForkFromTurn: true, |
| 280 | canForkWhileSourceRunning: true, |
| 281 | canForkFromSubagentThread: true, |
| 282 | exposesNativeThreadId: true, |
| 283 | }, |
| 284 | turns: { |
| 285 | exposesNativeTurnId: true, |
| 286 | emitsTurnStarted: true, |
| 287 | emitsTurnCompleted: true, |
| 288 | supportsInterrupt: true, |
| 289 | supportsNativeResume: true, |
| 290 | supportsActiveSteering: true, |
| 291 | activeSteeringDuringCompaction: true, |
| 292 | supportsSteeringByInterruptRestart: true, |
| 293 | supportsQueuedMessages: true, |
| 294 | terminalStatusQuality: "strong", |
| 295 | }, |
| 296 | streaming: { |
| 297 | streamsAssistantText: true, |
| 298 | streamsReasoning: true, |
| 299 | streamsToolOutput: true, |
| 300 | streamsPlanText: true, |
| 301 | emitsMessageCompleted: true, |
| 302 | }, |
| 303 | tools: { |
| 304 | exposesToolItemIds: true, |
| 305 | emitsToolStarted: true, |
| 306 | emitsToolCompleted: true, |
| 307 | emitsToolOutput: true, |
| 308 | supportsMcpTools: true, |
| 309 | supportsDynamicToolCallbacks: true, |
| 310 | }, |
| 311 | approvals: { |
| 312 | supportsCommandApproval: true, |
| 313 | supportsFileReadApproval: true, |
| 314 | supportsFileChangeApproval: true, |
| 315 | supportsApplyPatchApproval: true, |
| 316 | approvalsHaveNativeRequestIds: true, |
| 317 | approvalCallbacksAreLiveOnly: true, |
| 318 | approvalsCanOriginateFromSubagents: true, |
| 319 | }, |
| 320 | planning: { |
| 321 | emitsPlanUpdated: true, |
| 322 | emitsTodoList: true, |
| 323 | emitsProposedPlan: true, |
| 324 | supportsStructuredQuestions: true, |
| 325 | planDeltasHaveItemIds: true, |
| 326 | }, |
| 327 | subagents: { |
| 328 | supportsSubagents: true, |
| 329 | exposesSubagentThreadIds: true, |
| 330 | emitsSubagentLifecycle: true, |
| 331 | canWaitForSubagents: true, |
| 332 | canCloseSubagents: true, |
| 333 | canForkSubagentThread: true, |
| 334 | }, |
| 335 | context: { |
| 336 | acceptsSystemContext: true, |
| 337 | acceptsDeveloperContext: true, |
| 338 | acceptsSyntheticUserContext: true, |
| 339 | canGenerateSummaries: true, |
| 340 | canConsumeHandoffSummaries: true, |
| 341 | supportsDeltaHandoff: true, |
| 342 | supportsFullThreadHandoff: true, |
| 343 | maxRecommendedHandoffChars: null, |
| 344 | }, |
| 345 | checkpointing: { |
| 346 | appCanCheckpointFilesystem: true, |
| 347 | supportsNestedCheckpointScopes: true, |
| 348 | providerCanRollbackConversation: true, |
| 349 | providerRollbackReturnsSnapshot: true, |
| 350 | providerCanReadConversationSnapshot: true, |
| 351 | }, |
| 352 | identity: { |
| 353 | nativeThreadIds: "strong", |
| 354 | nativeTurnIds: "strong", |
| 355 | nativeItemIds: "strong", |
| 356 | nativeRequestIds: "strong", |
| 357 | }, |
| 358 | runtimePolicy: { |
| 359 | enforcement: "native", |
| 360 | }, |
| 361 | } satisfies OrchestrationV2ProviderCapabilities; |
| 362 | |
| 363 | function toProtocolError( |
| 364 | detail: string, |
| 365 | payload?: unknown, |
| 366 | ): ProviderAdapter.ProviderAdapterProtocolError { |
| 367 | return new ProviderAdapter.ProviderAdapterProtocolError({ |
| 368 | driver: CODEX_PROVIDER, |
| 369 | detail, |
| 370 | ...(payload === undefined ? {} : { payload }), |
| 371 | }); |
| 372 | } |
| 373 | |
| 374 | const CODEX_THREAD_IN_USE_MESSAGE = |
| 375 | "This conversation is open in another Codex client, such as the Codex app, the Codex CLI, or an IDE extension. Codex lets one client write to a conversation at a time. Quit that client, then send your message again."; |
| 376 | |
| 377 | const isCodexAppServerRequestError = Schema.is(CodexErrors.CodexAppServerRequestError); |
| 378 | |
| 379 | // Codex holds a per-thread writer lock for as long as a thread stays loaded in |
| 380 | // any app-server sharing the same CODEX_HOME, and reports a conflict this way. |
| 381 | function isCodexActiveWriterError(error: unknown): boolean { |
| 382 | return ( |
| 383 | isCodexAppServerRequestError(error) && |
| 384 | error.code === -32600 && |
| 385 | error.errorMessage.includes("already has an active writer") |
| 386 | ); |
| 387 | } |
| 388 | |
| 389 | function isCodexThreadNotFoundError(error: unknown): boolean { |
| 390 | return ( |
| 391 | isCodexAppServerRequestError(error) && |
| 392 | error.code === -32600 && |
| 393 | error.errorMessage.startsWith("thread not found:") |
| 394 | ); |
| 395 | } |
| 396 | |
| 397 | function codexTimestamp(seconds: number | null | undefined): DateTime.Utc { |
| 398 | return seconds === null || seconds === undefined |
| 399 | ? DateTime.nowUnsafe() |
| 400 | : DateTime.makeUnsafe(seconds * 1000); |
| 401 | } |
| 402 | |
| 403 | function codexUserMessageText( |
| 404 | content: ReadonlyArray<CodexSchema.V2ItemCompletedNotification__UserInput>, |
| 405 | ): string { |
| 406 | return content |
| 407 | .flatMap((item) => (item.type === "text" ? [item.text] : [])) |
| 408 | .join("\n") |
| 409 | .trim(); |
| 410 | } |
| 411 | |
| 412 | function mapCodexTurnStatus( |
| 413 | status: CodexSchema.V2TurnCompletedNotification__TurnStatus, |
| 414 | ): OrchestrationV2ProviderTurn["status"] { |
| 415 | switch (status) { |
| 416 | case "completed": |
| 417 | return "completed"; |
| 418 | case "interrupted": |
| 419 | return "interrupted"; |
| 420 | case "failed": |
| 421 | return "failed"; |
| 422 | case "inProgress": |
| 423 | return "running"; |
| 424 | } |
| 425 | } |
| 426 | |
| 427 | function providerTurnStatusToTerminal( |
| 428 | status: OrchestrationV2ProviderTurn["status"], |
| 429 | ): Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }>["status"] { |
| 430 | switch (status) { |
| 431 | case "completed": |
| 432 | return "completed"; |
| 433 | case "interrupted": |
| 434 | return "interrupted"; |
| 435 | case "failed": |
| 436 | return "failed"; |
| 437 | case "cancelled": |
| 438 | return "cancelled"; |
| 439 | case "pending": |
| 440 | case "running": |
| 441 | return "failed"; |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | function codexItemStatus(status: "inProgress" | "completed" | "failed" | "declined"): { |
| 446 | readonly node: OrchestrationV2ExecutionNode["status"]; |
| 447 | readonly turnItem: OrchestrationV2TurnItem["status"]; |
| 448 | readonly completed: boolean; |
| 449 | } { |
| 450 | switch (status) { |
| 451 | case "inProgress": |
| 452 | return { node: "running", turnItem: "running", completed: false }; |
| 453 | case "completed": |
| 454 | return { |
| 455 | node: "completed", |
| 456 | turnItem: "completed", |
| 457 | completed: true, |
| 458 | }; |
| 459 | case "failed": |
| 460 | return { node: "failed", turnItem: "failed", completed: true }; |
| 461 | case "declined": |
| 462 | return { |
| 463 | node: "cancelled", |
| 464 | turnItem: "cancelled", |
| 465 | completed: true, |
| 466 | }; |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | /** |
| 471 | * The composers let a skill be typed with any currency sigil (`€review`), but |
| 472 | * Codex only parses `$name` as a skill mention. |
| 473 | */ |
| 474 | function codexSkillMentionText(text: string): string { |
| 475 | return text.replace(SKILL_MENTION_PATTERN, "$1$$$2"); |
| 476 | } |
| 477 | |
| 478 | const BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH = 200; |
| 479 | const BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH = 1_000; |
| 480 | |
| 481 | function codexBackgroundCommandDetail(item: { |
| 482 | readonly command: string; |
| 483 | readonly exitCode?: number | null | undefined; |
| 484 | readonly aggregatedOutput?: string | null | undefined; |
| 485 | }): string { |
| 486 | // Codex rejects a turn/start with a lone surrogate and never answers it, so cut on code points. |
| 487 | let commandEnd = BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH; |
| 488 | const finalCommandUnit = item.command.charCodeAt(commandEnd - 1); |
| 489 | if (finalCommandUnit >= 0xd800 && finalCommandUnit <= 0xdbff) commandEnd -= 1; |
| 490 | const command = |
| 491 | item.command.length > BACKGROUND_COMMAND_DETAIL_COMMAND_MAX_LENGTH |
| 492 | ? `${item.command.slice(0, commandEnd)}...` |
| 493 | : item.command; |
| 494 | const exit = |
| 495 | item.exitCode === null || item.exitCode === undefined ? "" : ` (exit ${item.exitCode})`; |
| 496 | const output = (item.aggregatedOutput ?? "").trimEnd(); |
| 497 | let outputStart = output.length - BACKGROUND_COMMAND_DETAIL_OUTPUT_TAIL_MAX_LENGTH; |
| 498 | const firstOutputUnit = output.charCodeAt(outputStart); |
| 499 | if (firstOutputUnit >= 0xdc00 && firstOutputUnit <= 0xdfff) outputStart += 1; |
| 500 | const outputTail = outputStart > 0 ? `...${output.slice(outputStart)}` : output; |
| 501 | const header = `Background command completed${exit}: ${command}`; |
| 502 | return outputTail.length === 0 ? header : `${header}\n\nOutput tail:\n${outputTail}`; |
| 503 | } |
| 504 | |
| 505 | // Codex spawns can omit the prompt, which registers as an empty string. |
| 506 | function codexNativeSubagentLabel(task: OrchestrationV2Subagent): string | undefined { |
| 507 | return task.title?.trim() || task.prompt.trim() || undefined; |
| 508 | } |
| 509 | |
| 510 | function codexNativeSubagentDetail(task: OrchestrationV2Subagent): string { |
| 511 | const header = `Subagent ${task.status}: ${codexNativeSubagentLabel(task) ?? task.id}`; |
| 512 | return task.result == null || task.result.length === 0 |
| 513 | ? header |
| 514 | : `${header}\n\nResult:\n${task.result}`; |
| 515 | } |
| 516 | |
| 517 | export interface CodexDynamicToolProjection extends McpToolPresentation { |
| 518 | readonly toolName: string; |
| 519 | readonly title?: string; |
| 520 | readonly input: unknown; |
| 521 | readonly output?: unknown; |
| 522 | readonly status: OrchestrationV2TurnItem["status"]; |
| 523 | } |
| 524 | |
| 525 | function codexMcpToolOutput( |
| 526 | item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>, |
| 527 | ): unknown | undefined { |
| 528 | const resultOutput = |
| 529 | item.result === null || item.result === undefined |
| 530 | ? undefined |
| 531 | : mcpToolResultOutput(item.result); |
| 532 | |
| 533 | if (item.error === null || item.error === undefined) { |
| 534 | return resultOutput; |
| 535 | } |
| 536 | return resultOutput === undefined |
| 537 | ? { error: item.error.message } |
| 538 | : { error: item.error.message, result: resultOutput }; |
| 539 | } |
| 540 | |
| 541 | // A hung MCP resource read must not hold run ingestion open. |
| 542 | const MCP_APP_CAPTURE_TIMEOUT = "20 seconds"; |
| 543 | |
| 544 | function codexMcpAppResourceUri(item: CodexDynamicToolItem): string | undefined { |
| 545 | if (item.type !== "mcpToolCall") return undefined; |
| 546 | const uri = item.mcpAppUi?.resourceUri ?? item.mcpAppResourceUri ?? item.appContext?.resourceUri; |
| 547 | return typeof uri === "string" && uri.startsWith(MCP_APP_RESOURCE_SCHEME) ? uri : undefined; |
| 548 | } |
| 549 | |
| 550 | const CODEX_IMAGE_DATA_URL = /^data:(image\/[a-z0-9.+-]+);base64,([A-Za-z0-9+/=]+)$/i; |
| 551 | |
| 552 | export function codexDynamicToolOutput( |
| 553 | item: Extract<CodexDynamicToolItem, { readonly type: "dynamicToolCall" }>, |
| 554 | ): unknown | undefined { |
| 555 | if (item.contentItems !== null && item.contentItems !== undefined) { |
| 556 | return item.contentItems.map((content) => { |
| 557 | if (content.type !== "inputImage") return content; |
| 558 | const match = CODEX_IMAGE_DATA_URL.exec(content.imageUrl); |
| 559 | return match?.[1] && match[2] |
| 560 | ? { type: "image", mimeType: match[1].toLowerCase(), data: match[2] } |
| 561 | : content; |
| 562 | }); |
| 563 | } |
| 564 | return item.success === false ? { success: false } : undefined; |
| 565 | } |
| 566 | |
| 567 | const projectCodexDynamicToolItem = Effect.fn("CodexAdapterV2.projectDynamicToolItem")(function* ( |
| 568 | item: CodexDynamicToolItem, |
| 569 | ): Effect.fn.Return<CodexDynamicToolProjection, never, Digest.Digest> { |
| 570 | const output = |
| 571 | item.type === "mcpToolCall" ? codexMcpToolOutput(item) : codexDynamicToolOutput(item); |
| 572 | const toolName = |
| 573 | item.type === "mcpToolCall" |
| 574 | ? `${item.server}.${item.tool}` |
| 575 | : [trimText(item.namespace), item.tool].filter(Boolean).join("."); |
| 576 | const presentation: McpToolPresentation = |
| 577 | item.type === "mcpToolCall" ? yield* mcpToolPresentation(item) : {}; |
| 578 | const title = |
| 579 | dynamicToolTitle(toolName, item.arguments, presentation.title) ?? presentation.title; |
| 580 | const toolSurface = presentation.toolSurface ?? dynamicToolSurface(toolName, item.arguments); |
| 581 | const toolSource = |
| 582 | toolSurface === "computer" && presentation.toolSource?.kind !== "computer" |
| 583 | ? COMPUTER_USE_TOOL_SOURCE |
| 584 | : presentation.toolSource; |
| 585 | const projection: CodexDynamicToolProjection = { |
| 586 | ...presentation, |
| 587 | ...(toolSurface ? { toolSurface } : {}), |
| 588 | ...(toolSource ? { toolSource } : {}), |
| 589 | toolName, |
| 590 | ...(title ? { title } : {}), |
| 591 | input: item.arguments, |
| 592 | status: codexItemStatus(item.status).turnItem, |
| 593 | }; |
| 594 | return output === undefined ? projection : { ...projection, output }; |
| 595 | }); |
| 596 | |
| 597 | function codexNativeItemRef(nativeItemId: string) { |
| 598 | return { |
| 599 | driver: CODEX_PROVIDER, |
| 600 | nativeId: nativeItemId, |
| 601 | strength: "strong" as const, |
| 602 | }; |
| 603 | } |
| 604 | |
| 605 | function trimText(value: string | null | undefined): string | undefined { |
| 606 | const trimmed = value?.trim(); |
| 607 | return trimmed && trimmed.length > 0 ? trimmed : undefined; |
| 608 | } |
| 609 | |
| 610 | function nonEmptyText(value: string | null | undefined, fallback: string): string { |
| 611 | return trimText(value) ?? fallback; |
| 612 | } |
| 613 | |
| 614 | function codexPlanStepStatus( |
| 615 | status: CodexSchema.V2TurnPlanUpdatedNotification__TurnPlanStepStatus, |
| 616 | ): OrchestrationV2PlanStep["status"] { |
| 617 | switch (status) { |
| 618 | case "completed": |
| 619 | return "completed"; |
| 620 | case "inProgress": |
| 621 | return "running"; |
| 622 | case "pending": |
| 623 | return "pending"; |
| 624 | } |
| 625 | } |
| 626 | |
| 627 | function approvalDecisionToLegacyReviewDecision( |
| 628 | decision: ProviderApprovalDecision, |
| 629 | ): CodexSchema.ExecCommandApprovalResponse__ReviewDecision { |
| 630 | switch (decision) { |
| 631 | case "accept": |
| 632 | return "approved"; |
| 633 | case "acceptForSession": |
| 634 | case "acceptAlways": |
| 635 | return "approved_for_session"; |
| 636 | case "decline": |
| 637 | return { denied: { rejection: "User declined the request." } }; |
| 638 | case "cancel": |
| 639 | return "abort"; |
| 640 | } |
| 641 | } |
| 642 | |
| 643 | function providerRequestKindFromPermissions( |
| 644 | permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"], |
| 645 | ): ProviderRequestKind { |
| 646 | // Codex leaves the legacy `read`/`write` lists out when a path is a glob or |
| 647 | // special path, and is replacing them with `entries`. |
| 648 | const requests = (access: "read" | "write") => |
| 649 | (permissions.fileSystem?.[access]?.length ?? 0) > 0 || |
| 650 | permissions.fileSystem?.entries?.some((entry) => entry.access === access); |
| 651 | if (requests("write")) { |
| 652 | return "file-change"; |
| 653 | } |
| 654 | if (requests("read")) { |
| 655 | return "file-read"; |
| 656 | } |
| 657 | return "command"; |
| 658 | } |
| 659 | |
| 660 | function permissionsResponseFromDecision(input: { |
| 661 | readonly decision: ProviderApprovalDecision; |
| 662 | readonly permissions: CodexSchema.PermissionsRequestApprovalParams["permissions"]; |
| 663 | }): CodexSchema.PermissionsRequestApprovalResponse { |
| 664 | if (input.decision !== "accept" && input.decision !== "acceptForSession") { |
| 665 | return { permissions: {}, scope: "turn" }; |
| 666 | } |
| 667 | |
| 668 | return { |
| 669 | permissions: input.permissions, |
| 670 | scope: input.decision === "acceptForSession" ? "session" : "turn", |
| 671 | }; |
| 672 | } |
| 673 | |
| 674 | function answerValueToStrings(value: unknown): ReadonlyArray<string> { |
| 675 | if (Array.isArray(value)) { |
| 676 | return value.map((item) => String(item)); |
| 677 | } |
| 678 | if (typeof value === "string") { |
| 679 | return [value]; |
| 680 | } |
| 681 | if (value === null || value === undefined) { |
| 682 | return []; |
| 683 | } |
| 684 | if (typeof value === "number" || typeof value === "boolean") { |
| 685 | return [String(value)]; |
| 686 | } |
| 687 | return [JSON.stringify(value)]; |
| 688 | } |
| 689 | |
| 690 | function toCodexUserInputAnswers( |
| 691 | answers: ProviderUserInputAnswers, |
| 692 | nativeQuestionIds: ReadonlyMap<string, string>, |
| 693 | ): CodexSchema.ToolRequestUserInputResponse["answers"] { |
| 694 | return Object.fromEntries( |
| 695 | Object.entries(answers).flatMap(([questionId, value]) => { |
| 696 | const nativeId = nativeQuestionIds.get(questionId); |
| 697 | return nativeId === undefined |
| 698 | ? [] |
| 699 | : [[nativeId, { answers: [...answerValueToStrings(value)] }]]; |
| 700 | }), |
| 701 | ); |
| 702 | } |
| 703 | |
| 704 | function compactStrings(values: ReadonlyArray<string | null | undefined>): ReadonlyArray<string> { |
| 705 | // Codex derives the item's `query` from its action, so it often repeats an action value. |
| 706 | return [ |
| 707 | ...new Set( |
| 708 | values.flatMap((value) => { |
| 709 | const trimmed = trimText(value); |
| 710 | return trimmed === undefined ? [] : [trimmed]; |
| 711 | }), |
| 712 | ), |
| 713 | ]; |
| 714 | } |
| 715 | |
| 716 | function webSearchPatterns(item: CodexWebSearchItem): ReadonlyArray<string> { |
| 717 | if (item.action === null || item.action === undefined) { |
| 718 | return compactStrings([item.query]); |
| 719 | } |
| 720 | |
| 721 | switch (item.action.type) { |
| 722 | case "search": |
| 723 | return compactStrings([...(item.action.queries ?? []), item.action.query, item.query]); |
| 724 | case "openPage": |
| 725 | return compactStrings([item.action.url, item.query]); |
| 726 | case "findInPage": |
| 727 | return compactStrings([item.action.pattern, item.action.url, item.query]); |
| 728 | case "other": |
| 729 | return compactStrings([item.query]); |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | const decodeTurnApprovalPolicy = Schema.decodeUnknownEffect( |
| 734 | Schema.Union([CodexSchema.V2TurnStartParams__AskForApproval, Schema.Null]), |
| 735 | ); |
| 736 | const decodeTurnSandboxPolicy = Schema.decodeUnknownEffect( |
| 737 | Schema.Union([CodexSchema.V2TurnStartParams__SandboxPolicy, Schema.Null]), |
| 738 | ); |
| 739 | const decodeTurnReasoningEffort = Schema.decodeUnknownEffect( |
| 740 | Schema.Union([CodexSchema.V2TurnStartParams__ReasoningEffort, Schema.Null]), |
| 741 | ); |
| 742 | |
| 743 | type CodexTurnStartParams = typeof CodexClient.V2TurnStartParams.Type; |
| 744 | const decodeCodexTurnStartParams = Schema.decodeUnknownEffect(CodexClient.V2TurnStartParams); |
| 745 | const isProviderMcpSignInError = Schema.is(ProviderMcpSignInError); |
| 746 | const isProviderAdapterRuntimeRequestResponseError = Schema.is( |
| 747 | ProviderAdapter.ProviderAdapterRuntimeRequestResponseError, |
| 748 | ); |
| 749 | |
| 750 | function codexRuntimeModeTurnDefaults(runtimeMode: RuntimeMode): { |
| 751 | readonly approvalPolicy: CodexSchema.V2TurnStartParams__AskForApproval; |
| 752 | readonly approvalsReviewer: CodexSchema.V2TurnStartParams__ApprovalsReviewer; |
| 753 | readonly sandboxPolicy: CodexSchema.V2TurnStartParams__SandboxPolicy; |
| 754 | } { |
| 755 | switch (runtimeMode) { |
| 756 | case "approval-required": |
| 757 | return { |
| 758 | approvalPolicy: "untrusted", |
| 759 | approvalsReviewer: "user", |
| 760 | sandboxPolicy: { |
| 761 | type: "readOnly", |
| 762 | }, |
| 763 | }; |
| 764 | case "auto-accept-edits": |
| 765 | return { |
| 766 | approvalPolicy: "on-request", |
| 767 | approvalsReviewer: "user", |
| 768 | sandboxPolicy: { |
| 769 | type: "workspaceWrite", |
| 770 | }, |
| 771 | }; |
| 772 | case "auto": |
| 773 | return { |
| 774 | approvalPolicy: "on-request", |
| 775 | approvalsReviewer: "auto_review", |
| 776 | sandboxPolicy: { |
| 777 | type: "workspaceWrite", |
| 778 | }, |
| 779 | }; |
| 780 | case "full-access": |
| 781 | return { |
| 782 | // `never` also rejects browser and app access prompts before the client sees them. |
| 783 | approvalPolicy: { |
| 784 | granular: { |
| 785 | mcp_elicitations: true, |
| 786 | request_permissions: false, |
| 787 | rules: false, |
| 788 | sandbox_approval: false, |
| 789 | skill_approval: false, |
| 790 | }, |
| 791 | }, |
| 792 | approvalsReviewer: "user", |
| 793 | sandboxPolicy: { |
| 794 | type: "dangerFullAccess", |
| 795 | }, |
| 796 | }; |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | const isCodexCyberAccessProgram = Schema.is(CodexSchema.V2TurnStartParams__CyberAccessProgram); |
| 801 | |
| 802 | function codexCyberAccess( |
| 803 | models: ReadonlyArray<ServerProviderModel>, |
| 804 | model: string, |
| 805 | ): { readonly defaultProgram: string | undefined } | undefined { |
| 806 | const descriptor = models |
| 807 | .find((candidate) => candidate.slug === model) |
| 808 | ?.capabilities?.optionDescriptors?.find((candidate) => candidate.id === "cyberAccessProgram"); |
| 809 | return descriptor?.type === "select" ? { defaultProgram: descriptor.currentValue } : undefined; |
| 810 | } |
| 811 | |
| 812 | export const buildCodexTurnStartParams = Effect.fn("CodexAdapterV2.buildCodexTurnStartParams")( |
| 813 | function* (input: { |
| 814 | readonly nativeThreadId: string; |
| 815 | readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>; |
| 816 | readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; |
| 817 | readonly modelSelection: ModelSelection; |
| 818 | readonly hasT3Mcp?: boolean; |
| 819 | readonly browserToolsAvailable?: boolean; |
| 820 | readonly deviceToolsAvailable?: boolean; |
| 821 | /** ChatGPT token sharing does not accept service tiers. */ |
| 822 | readonly omitServiceTier?: boolean; |
| 823 | readonly appContext?: ProviderAdapter.ProviderAdapterV2TurnInput["appContext"]; |
| 824 | /** Set only for a model that offers Cyber Access; custom models never do. */ |
| 825 | readonly cyberAccess?: { readonly defaultProgram: string | undefined } | undefined; |
| 826 | /** The user's `model_reasoning_summary` from the Codex config, when set. */ |
| 827 | readonly configuredReasoningSummary?: CodexSchema.V2TurnStartParams__ReasoningSummary; |
| 828 | }) { |
| 829 | const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode); |
| 830 | const approvalPolicy = |
| 831 | input.runtimePolicy.approvalPolicy === undefined |
| 832 | ? runtimeModeDefaults.approvalPolicy |
| 833 | : yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy); |
| 834 | const sandboxPolicy = |
| 835 | input.runtimePolicy.sandboxPolicy === undefined |
| 836 | ? runtimeModeDefaults.sandboxPolicy |
| 837 | : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy); |
| 838 | const selectedEffort = |
| 839 | getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort") ?? |
| 840 | codexDefaultReasoningEffortOverride(input.modelSelection.model); |
| 841 | const effort = |
| 842 | selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort); |
| 843 | const serviceTier = |
| 844 | input.omitServiceTier === true |
| 845 | ? undefined |
| 846 | : getCodexServiceTierOptionValue(input.modelSelection); |
| 847 | // A chosen program goes as is, even one the model lacks, so Codex rejects it visibly. |
| 848 | const cyberAccessProgram = |
| 849 | input.cyberAccess === undefined |
| 850 | ? undefined |
| 851 | : [ |
| 852 | getModelSelectionStringOptionValue(input.modelSelection, "cyberAccessProgram"), |
| 853 | input.cyberAccess.defaultProgram, |
| 854 | ].find(isCodexCyberAccessProgram); |
| 855 | // MCP-written app context must be quoted user input, not developer instructions. |
| 856 | const appContext = Object.fromEntries( |
| 857 | (input.appContext ?? []).map((entry) => [ |
| 858 | entry.key, |
| 859 | { kind: "untrusted" as const, value: entry.text }, |
| 860 | ]), |
| 861 | ); |
| 862 | const t3Context = |
| 863 | input.hasT3Mcp === true |
| 864 | ? buildCodexAdditionalContext( |
| 865 | { model: input.modelSelection.model, reasoningEffort: effort ?? undefined }, |
| 866 | { |
| 867 | browser: input.browserToolsAvailable ?? true, |
| 868 | device: input.deviceToolsAvailable ?? false, |
| 869 | }, |
| 870 | ) |
| 871 | : undefined; |
| 872 | const additionalContext = |
| 873 | t3Context === undefined && Object.keys(appContext).length === 0 |
| 874 | ? undefined |
| 875 | : { ...t3Context, ...appContext }; |
| 876 | return yield* decodeCodexTurnStartParams({ |
| 877 | threadId: input.nativeThreadId, |
| 878 | input: input.codexInput, |
| 879 | ...(additionalContext ? { additionalContext } : {}), |
| 880 | cwd: input.runtimePolicy.cwd, |
| 881 | model: input.modelSelection.model, |
| 882 | // Catalogues can default summaries to "none", and turn/start overrides the user's config, |
| 883 | // so pass theirs through or `auto`: some providers (Amazon Bedrock) reject `detailed`. |
| 884 | summary: input.configuredReasoningSummary ?? "auto", |
| 885 | // Omitting the reviewer on resume preserves the previous Auto reviewer. |
| 886 | approvalsReviewer: runtimeModeDefaults.approvalsReviewer, |
| 887 | ...(approvalPolicy === undefined ? {} : { approvalPolicy }), |
| 888 | ...(sandboxPolicy === undefined ? {} : { sandboxPolicy }), |
| 889 | ...(effort === undefined ? {} : { effort }), |
| 890 | ...(serviceTier === undefined ? {} : { serviceTier }), |
| 891 | // Codex keeps no per-thread choice for this, so every turn must carry it. |
| 892 | ...(cyberAccessProgram === undefined ? {} : { cyberAccessProgram }), |
| 893 | // Codex supplies its own mode instructions; send both modes to clear Plan on exit. |
| 894 | collaborationMode: { |
| 895 | mode: input.runtimePolicy.interactionMode, |
| 896 | settings: { |
| 897 | model: input.modelSelection.model, |
| 898 | ...(effort === undefined ? {} : { reasoning_effort: effort }), |
| 899 | }, |
| 900 | }, |
| 901 | }); |
| 902 | }, |
| 903 | ); |
| 904 | |
| 905 | function providerSession(input: { |
| 906 | readonly providerSessionId: OrchestrationV2ProviderSession["id"]; |
| 907 | readonly providerInstanceId: ProviderInstanceId; |
| 908 | readonly cwd: string | null; |
| 909 | readonly model: string; |
| 910 | readonly now: DateTime.Utc; |
| 911 | }): OrchestrationV2ProviderSession { |
| 912 | return { |
| 913 | id: input.providerSessionId, |
| 914 | driver: CODEX_PROVIDER, |
| 915 | providerInstanceId: input.providerInstanceId, |
| 916 | status: "ready", |
| 917 | cwd: input.cwd ?? process.cwd(), |
| 918 | model: input.model, |
| 919 | capabilities: CodexProviderCapabilitiesV2, |
| 920 | createdAt: input.now, |
| 921 | updatedAt: input.now, |
| 922 | lastError: null, |
| 923 | }; |
| 924 | } |
| 925 | |
| 926 | interface CodexMcpStartupFailure { |
| 927 | readonly message: string; |
| 928 | readonly signIn: boolean; |
| 929 | } |
| 930 | |
| 931 | /** Codex names an expired sign-in, but a missing one only in text that says to run `codex mcp login`. */ |
| 932 | const codexMcpStartupNeedsSignIn = (payload: { |
| 933 | readonly failureReason?: string | null; |
| 934 | readonly error?: string | null; |
| 935 | }) => |
| 936 | payload.failureReason === "reauthenticationRequired" || |
| 937 | (payload.error ?? "").includes("mcp login"); |
| 938 | |
| 939 | /** A sign-in Codex started, waiting for its callback page on this machine to be opened. */ |
| 940 | interface CodexMcpSignIn { |
| 941 | readonly redirectUri: string; |
| 942 | readonly state: string; |
| 943 | readonly succeeded: Deferred.Deferred<boolean>; |
| 944 | } |
| 945 | |
| 946 | const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "localhost", "[::1]"]); |
| 947 | |
| 948 | const getNativeThreadId = Effect.fn("CodexAdapterV2.getNativeThreadId")(function* ( |
| 949 | providerThread: OrchestrationV2ProviderThread, |
| 950 | ) { |
| 951 | const nativeThreadId = providerThread.nativeThreadRef?.nativeId; |
| 952 | if (nativeThreadId === undefined || nativeThreadId === null) { |
| 953 | return yield* toProtocolError( |
| 954 | `Provider thread ${providerThread.id} is missing a native Codex thread id.`, |
| 955 | ); |
| 956 | } |
| 957 | return nativeThreadId; |
| 958 | }); |
| 959 | |
| 960 | function providerThreadFromCodexThread(input: { |
| 961 | readonly appThreadId: ThreadId | null; |
| 962 | readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; |
| 963 | readonly ownerNodeId: OrchestrationV2ProviderThread["ownerNodeId"]; |
| 964 | readonly providerSessionId: OrchestrationV2ProviderThread["providerSessionId"]; |
| 965 | readonly providerInstanceId: ProviderInstanceId; |
| 966 | readonly thread: { |
| 967 | readonly createdAt: number; |
| 968 | readonly forkedFromId?: string | null; |
| 969 | readonly id: string; |
| 970 | readonly updatedAt: number; |
| 971 | }; |
| 972 | readonly forkedFrom?: OrchestrationV2ProviderThread["forkedFrom"]; |
| 973 | }): OrchestrationV2ProviderThread { |
| 974 | return { |
| 975 | id: input.idAllocator.derive.providerThread({ |
| 976 | driver: CODEX_PROVIDER, |
| 977 | nativeThreadId: input.thread.id, |
| 978 | }), |
| 979 | driver: CODEX_PROVIDER, |
| 980 | providerInstanceId: input.providerInstanceId, |
| 981 | providerSessionId: input.providerSessionId, |
| 982 | appThreadId: input.appThreadId, |
| 983 | ownerNodeId: input.ownerNodeId, |
| 984 | nativeThreadRef: { |
| 985 | driver: CODEX_PROVIDER, |
| 986 | nativeId: input.thread.id, |
| 987 | strength: "strong" as const, |
| 988 | }, |
| 989 | nativeConversationHeadRef: null, |
| 990 | status: "idle", |
| 991 | firstRunOrdinal: null, |
| 992 | lastRunOrdinal: null, |
| 993 | handoffIds: [], |
| 994 | forkedFrom: input.forkedFrom ?? null, |
| 995 | createdAt: codexTimestamp(input.thread.createdAt), |
| 996 | updatedAt: codexTimestamp(input.thread.updatedAt), |
| 997 | }; |
| 998 | } |
| 999 | |
| 1000 | // /goal control turns never reach Codex and must not count toward native rollback. |
| 1001 | const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean => |
| 1002 | turn.nativeTurnRef !== null && |
| 1003 | (turn.status === "completed" || |
| 1004 | turn.status === "interrupted" || |
| 1005 | turn.status === "failed" || |
| 1006 | turn.status === "cancelled"); |
| 1007 | |
| 1008 | class CodexGoalObjectiveTooLongError extends Schema.TaggedError<CodexGoalObjectiveTooLongError>()( |
| 1009 | "CodexGoalObjectiveTooLongError", |
| 1010 | { length: Schema.Number, limit: Schema.Number }, |
| 1011 | ) { |
| 1012 | override get message() { |
| 1013 | return `The goal objective is ${this.length} characters; Codex supports at most ${this.limit}. Shorten it and send /goal again. The current goal was not changed.`; |
| 1014 | } |
| 1015 | } |
| 1016 | |
| 1017 | function validateCodexGoalObjective(objective: string) { |
| 1018 | let length = 0; |
| 1019 | for (const _ of objective) length++; |
| 1020 | return length > CodexSchema.MAX_THREAD_GOAL_OBJECTIVE_CHARS |
| 1021 | ? Effect.fail( |
| 1022 | new CodexGoalObjectiveTooLongError({ |
| 1023 | length, |
| 1024 | limit: CodexSchema.MAX_THREAD_GOAL_OBJECTIVE_CHARS, |
| 1025 | }), |
| 1026 | ) |
| 1027 | : Effect.void; |
| 1028 | } |
| 1029 | |
| 1030 | type CodexThreadGoal = CodexSchema.V2ThreadGoalUpdatedNotification["goal"]; |
| 1031 | |
| 1032 | const CODEX_GOAL_STATUSES = { |
| 1033 | active: "active", |
| 1034 | paused: "paused", |
| 1035 | blocked: "blocked", |
| 1036 | usageLimited: "usage_limited", |
| 1037 | budgetLimited: "budget_limited", |
| 1038 | complete: "complete", |
| 1039 | } as const satisfies Record<CodexThreadGoal["status"], OrchestrationV2ProviderGoal["status"]>; |
| 1040 | |
| 1041 | function providerGoalFromCodex(goal: CodexThreadGoal): OrchestrationV2ProviderGoal | null { |
| 1042 | const objective = goal.objective.trim(); |
| 1043 | if (objective.length === 0) return null; |
| 1044 | return { |
| 1045 | objective, |
| 1046 | status: CODEX_GOAL_STATUSES[goal.status], |
| 1047 | tokensUsed: Math.max(0, goal.tokensUsed), |
| 1048 | tokenBudget: goal.tokenBudget ?? null, |
| 1049 | timeUsedSeconds: Math.max(0, goal.timeUsedSeconds), |
| 1050 | }; |
| 1051 | } |
| 1052 | |
| 1053 | const providerGoalsEqual = Schema.toEquivalence(Schema.NullOr(OrchestrationV2ProviderGoal)); |
| 1054 | |
| 1055 | function describeCodexGoal(goal: OrchestrationV2ProviderGoal): string { |
| 1056 | return `Goal ${goal.status.replace("_", " ")}: ${goal.objective}`; |
| 1057 | } |
| 1058 | |
| 1059 | // Codex starts the next goal turn milliseconds after the last one completes. |
| 1060 | const CODEX_GOAL_CONTINUATION_GRACE = "5 seconds"; |
| 1061 | |
| 1062 | const providerTurnsForThread = ( |
| 1063 | providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>, |
| 1064 | providerThread: OrchestrationV2ProviderThread, |
| 1065 | ): ReadonlyArray<OrchestrationV2ProviderTurn> => |
| 1066 | providerTurns.filter((turn) => turn.providerThreadId === providerThread.id); |
| 1067 | |
| 1068 | const countTerminalTurnsAfterBoundary = ( |
| 1069 | providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>, |
| 1070 | providerTurnId: ProviderTurnId, |
| 1071 | ): number | null => { |
| 1072 | const boundaryTurn = providerTurns.find((turn) => turn.id === providerTurnId); |
| 1073 | if (boundaryTurn === undefined) { |
| 1074 | return null; |
| 1075 | } |
| 1076 | |
| 1077 | return providerTurns.filter( |
| 1078 | (turn) => turn.ordinal > boundaryTurn.ordinal && isTerminalProviderTurn(turn), |
| 1079 | ).length; |
| 1080 | }; |
| 1081 | |
| 1082 | const resolveCodexForkRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveForkRollbackTurnCount")( |
| 1083 | function* (input: ProviderAdapter.ProviderAdapterV2ForkThreadInput) { |
| 1084 | if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) { |
| 1085 | return 0; |
| 1086 | } |
| 1087 | |
| 1088 | const rollbackTurnCount = countTerminalTurnsAfterBoundary( |
| 1089 | providerTurnsForThread(input.sourceProviderTurns, input.sourceProviderThread), |
| 1090 | input.providerTurnId, |
| 1091 | ); |
| 1092 | if (rollbackTurnCount === null) { |
| 1093 | return yield* new ProviderAdapter.ProviderAdapterForkThreadError({ |
| 1094 | driver: CODEX_PROVIDER, |
| 1095 | providerThreadId: input.sourceProviderThread.id, |
| 1096 | cause: `Cannot fork Codex thread from provider turn ${input.providerTurnId}: source turn was not found in provider thread ${input.sourceProviderThread.id}.`, |
| 1097 | }); |
| 1098 | } |
| 1099 | |
| 1100 | return rollbackTurnCount; |
| 1101 | }, |
| 1102 | ); |
| 1103 | |
| 1104 | /** Codex lastTurnId is inclusive, atomically omitting later turns even in paginated threads. */ |
| 1105 | export const resolveCodexForkBoundary = Effect.fn("CodexAdapterV2.resolveForkBoundary")(function* ( |
| 1106 | input: ProviderAdapter.ProviderAdapterV2ForkThreadInput, |
| 1107 | ) { |
| 1108 | const rollbackTurnCount = yield* resolveCodexForkRollbackTurnCount(input); |
| 1109 | if (input.providerTurnId === undefined || input.sourceProviderTurns === undefined) { |
| 1110 | return { lastTurnId: undefined, rollbackTurnCount }; |
| 1111 | } |
| 1112 | |
| 1113 | const boundaryTurn = providerTurnsForThread( |
| 1114 | input.sourceProviderTurns, |
| 1115 | input.sourceProviderThread, |
| 1116 | ).find((turn) => turn.id === input.providerTurnId); |
| 1117 | const nativeTurnId = boundaryTurn?.nativeTurnRef?.nativeId; |
| 1118 | if (nativeTurnId === null || nativeTurnId === undefined) { |
| 1119 | return { lastTurnId: undefined, rollbackTurnCount }; |
| 1120 | } |
| 1121 | |
| 1122 | return { lastTurnId: nativeTurnId, rollbackTurnCount: 0 }; |
| 1123 | }); |
| 1124 | |
| 1125 | /** Generated thread/read schemas omit historyMode; probe through the raw request channel. */ |
| 1126 | const CodexThreadHistoryMetadata = Schema.Struct({ |
| 1127 | thread: Schema.Struct({ |
| 1128 | historyMode: Schema.optionalKey(Schema.Literals(["legacy", "paginated"])), |
| 1129 | status: Schema.optionalKey(Schema.Struct({ type: Schema.String })), |
| 1130 | }), |
| 1131 | }); |
| 1132 | const decodeCodexThreadHistoryMetadata = Schema.decodeUnknownEffect(CodexThreadHistoryMetadata); |
| 1133 | |
| 1134 | const readCodexThreadHistoryMetadata = Effect.fn("CodexAdapterV2.readThreadHistoryMetadata")( |
| 1135 | function* ( |
| 1136 | raw: Pick<CodexClient.CodexAppServerClient["Service"]["raw"], "request">, |
| 1137 | threadId: string, |
| 1138 | ) { |
| 1139 | const response = yield* raw.request("thread/read", { threadId, includeTurns: false }); |
| 1140 | const metadata = yield* decodeCodexThreadHistoryMetadata(response).pipe( |
| 1141 | Effect.mapError((error) => |
| 1142 | CodexErrors.CodexAppServerRequestError.invalidPayload( |
| 1143 | "thread/read", |
| 1144 | "decode-payload", |
| 1145 | error, |
| 1146 | ), |
| 1147 | ), |
| 1148 | ); |
| 1149 | return { |
| 1150 | historyMode: metadata.thread.historyMode, |
| 1151 | loaded: metadata.thread.status?.type !== "notLoaded", |
| 1152 | }; |
| 1153 | }, |
| 1154 | ); |
| 1155 | |
| 1156 | export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRollbackTurnCount")( |
| 1157 | function* (input: ProviderAdapter.ProviderAdapterV2RollbackThreadInput) { |
| 1158 | const providerTurns = input.providerThreadTurns; |
| 1159 | switch (input.target.type) { |
| 1160 | case "thread_start": |
| 1161 | return providerTurns.filter(isTerminalProviderTurn).length; |
| 1162 | case "provider_turn": { |
| 1163 | if (input.target.providerTurn.providerThreadId !== input.providerThread.id) { |
| 1164 | return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({ |
| 1165 | driver: CODEX_PROVIDER, |
| 1166 | providerThreadId: input.providerThread.id, |
| 1167 | cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn belongs to provider thread ${input.target.providerTurn.providerThreadId}.`, |
| 1168 | }); |
| 1169 | } |
| 1170 | |
| 1171 | const rollbackTurnCount = countTerminalTurnsAfterBoundary( |
| 1172 | providerTurns, |
| 1173 | input.target.providerTurn.id, |
| 1174 | ); |
| 1175 | if (rollbackTurnCount === null) { |
| 1176 | return yield* new ProviderAdapter.ProviderAdapterRollbackThreadError({ |
| 1177 | driver: CODEX_PROVIDER, |
| 1178 | providerThreadId: input.providerThread.id, |
| 1179 | cause: `Cannot roll back Codex thread ${input.providerThread.id} to provider turn ${input.target.providerTurn.id}: target turn was not found in durable provider turn history.`, |
| 1180 | }); |
| 1181 | } |
| 1182 | |
| 1183 | return rollbackTurnCount; |
| 1184 | } |
| 1185 | } |
| 1186 | }, |
| 1187 | ); |
| 1188 | |
| 1189 | function parseCodexRetryProgress( |
| 1190 | message: string, |
| 1191 | ): Pick<OrchestrationV2ProviderRetry, "attempt" | "maxAttempts"> | null { |
| 1192 | const match = /\b(\d+)\s*\/\s*(\d+)\b/u.exec(message); |
| 1193 | if (match?.[1] === undefined || match[2] === undefined) { |
| 1194 | return null; |
| 1195 | } |
| 1196 | const attempt = Number.parseInt(match[1], 10); |
| 1197 | const maxAttempts = Number.parseInt(match[2], 10); |
| 1198 | if (attempt < 1 || maxAttempts < 1) { |
| 1199 | return null; |
| 1200 | } |
| 1201 | return { attempt, maxAttempts }; |
| 1202 | } |
| 1203 | |
| 1204 | function codexErrorInfoCode(value: unknown): string | null { |
| 1205 | if (typeof value === "string") { |
| 1206 | return value; |
| 1207 | } |
| 1208 | if (typeof value !== "object" || value === null) { |
| 1209 | return null; |
| 1210 | } |
| 1211 | return Object.keys(value)[0] ?? null; |
| 1212 | } |
| 1213 | |
| 1214 | type CodexErrorInfo = CodexSchema.ServerNotification__CodexErrorInfo; |
| 1215 | |
| 1216 | /** |
| 1217 | * Retry exhaustion only says why it failed through the last attempt's HTTP |
| 1218 | * status. Exhaustion on 429 is a usage or rate limit, so it keeps the Limited |
| 1219 | * state and resume controls; other statuses stay provider or transport errors. |
| 1220 | */ |
| 1221 | function codexExhaustionHttpStatus(errorInfo: CodexErrorInfo | null | undefined): number | null { |
| 1222 | return typeof errorInfo === "object" && |
| 1223 | errorInfo !== null && |
| 1224 | "responseTooManyFailedAttempts" in errorInfo |
| 1225 | ? (errorInfo.responseTooManyFailedAttempts.httpStatusCode ?? null) |
| 1226 | : null; |
| 1227 | } |
| 1228 | |
| 1229 | function codexErrorHttpStatus(errorInfo: CodexErrorInfo | null | undefined): number | null { |
| 1230 | const detail = |
| 1231 | typeof errorInfo === "object" && errorInfo !== null ? Object.values(errorInfo)[0] : undefined; |
| 1232 | return typeof detail === "object" && |
| 1233 | detail !== null && |
| 1234 | "httpStatusCode" in detail && |
| 1235 | typeof detail.httpStatusCode === "number" |
| 1236 | ? detail.httpStatusCode |
| 1237 | : null; |
| 1238 | } |
| 1239 | |
| 1240 | function codexUsageLimitError( |
| 1241 | code: string | null, |
| 1242 | errorInfo: CodexErrorInfo | null | undefined, |
| 1243 | ): boolean { |
| 1244 | return ( |
| 1245 | code === "usageLimitExceeded" || |
| 1246 | code === "rateLimitExceeded" || |
| 1247 | codexExhaustionHttpStatus(errorInfo) === 429 |
| 1248 | ); |
| 1249 | } |
| 1250 | |
| 1251 | function codexTerminalFailureClass( |
| 1252 | errorInfo: CodexErrorInfo | null | undefined, |
| 1253 | code: string | null, |
| 1254 | ) { |
| 1255 | if (codexUsageLimitError(code, errorInfo)) return "usage_limit"; |
| 1256 | if (typeof errorInfo === "object" && errorInfo !== null) { |
| 1257 | const transport = |
| 1258 | "responseStreamDisconnected" in errorInfo |
| 1259 | ? errorInfo.responseStreamDisconnected |
| 1260 | : "responseStreamConnectionFailed" in errorInfo |
| 1261 | ? errorInfo.responseStreamConnectionFailed |
| 1262 | : "httpConnectionFailed" in errorInfo |
| 1263 | ? errorInfo.httpConnectionFailed |
| 1264 | : undefined; |
| 1265 | if (transport !== undefined && transport.httpStatusCode == null) return "transport_error"; |
| 1266 | } |
| 1267 | return "provider_error"; |
| 1268 | } |
| 1269 | |
| 1270 | function codexTerminalErrorNeedsEvidence( |
| 1271 | errorInfo: CodexErrorInfo | null | undefined, |
| 1272 | code: string | null, |
| 1273 | ) { |
| 1274 | return ( |
| 1275 | code === "other" || |
| 1276 | (code === "responseTooManyFailedAttempts" && codexExhaustionHttpStatus(errorInfo) === null) |
| 1277 | ); |
| 1278 | } |
| 1279 | |
| 1280 | /** |
| 1281 | * ChatGPT sharing reports its own reason inside Codex's generic turn error, so |
| 1282 | * the code it names replaces Codex's, and clients pick a recovery from it. Its |
| 1283 | * allowance limits get the usage-limit recovery; other sharing failures keep their class. |
| 1284 | */ |
| 1285 | function withCodexManagedFailure( |
| 1286 | failure: OrchestrationV2ProviderFailure, |
| 1287 | nativeError: unknown, |
| 1288 | ): OrchestrationV2ProviderFailure { |
| 1289 | const managed = classifyCodexManagedError(nativeError); |
| 1290 | return managed === undefined |
| 1291 | ? failure |
| 1292 | : { |
| 1293 | ...failure, |
| 1294 | message: managed.message, |
| 1295 | code: managed.code, |
| 1296 | ...(managed.usageLimit ? { class: "usage_limit" } : {}), |
| 1297 | }; |
| 1298 | } |
| 1299 | |
| 1300 | function failureResetAt( |
| 1301 | failure: OrchestrationV2ProviderFailure, |
| 1302 | snapshot: CodexRateLimitSnapshot | undefined, |
| 1303 | /** Read the failure text against when Codex reported it; omit to use the snapshot only. */ |
| 1304 | text?: { readonly failedAt: DateTime.Utc; readonly zone: DateTime.TimeZone }, |
| 1305 | ) { |
| 1306 | // Sharing caps have no reset timestamp in the ordinary Codex allowance snapshot. |
| 1307 | if (classifyCodexManagedError(failure.code)?.usageLimit) return null; |
| 1308 | return ( |
| 1309 | codexUsageLimitResetAt(snapshot) ?? |
| 1310 | (text === undefined ? null : codexMessageResetAt(failure.message, text.failedAt, text.zone)) |
| 1311 | ); |
| 1312 | } |
| 1313 | |
| 1314 | interface ActiveCodexTurnContext { |
| 1315 | hookStopReason?: string; |
| 1316 | appliedServiceTier?: string; |
| 1317 | capacityRetryAttempt?: number; |
| 1318 | capacityRetryPending?: Deferred.Deferred<ActiveCodexTurnContext | undefined>; |
| 1319 | closedCommandItemIds?: ReadonlySet<string>; |
| 1320 | latestProviderFailure?: { |
| 1321 | readonly nativeMessage: string; |
| 1322 | readonly nativeCode: string | null; |
| 1323 | readonly errorInfo?: CodexErrorInfo | null; |
| 1324 | readonly failure: OrchestrationV2ProviderFailure; |
| 1325 | }; |
| 1326 | readonly nativeStartReady?: Deferred.Deferred<void>; |
| 1327 | readonly input: ProviderAdapter.ProviderAdapterV2TurnInput; |
| 1328 | readonly projectionAppThread: OrchestrationV2AppThread; |
| 1329 | readonly projectionThreadId: ThreadId; |
| 1330 | readonly projectionRunId: ProviderAdapter.ProviderAdapterV2TurnInput["runId"] | null; |
| 1331 | readonly nativeTurnId: string; |
| 1332 | readonly providerThread: OrchestrationV2ProviderThread; |
| 1333 | readonly providerTurnId: ProviderTurnId; |
| 1334 | readonly providerTurnOrdinal: number; |
| 1335 | readonly providerNodeId: OrchestrationV2ExecutionNode["id"]; |
| 1336 | readonly providerNodeStartedAt: DateTime.Utc | null; |
| 1337 | readonly itemParentNodeId: OrchestrationV2ExecutionNode["id"]; |
| 1338 | readonly rootNodeId: OrchestrationV2ExecutionNode["id"]; |
| 1339 | readonly subagent: CodexSubagentThreadContext | null; |
| 1340 | readonly startedAt: DateTime.Utc; |
| 1341 | readonly runningCompactionItemIds: Set<string>; |
| 1342 | readonly runningWebSearchItems: Map<string, CodexWebSearchItem>; |
| 1343 | // Modern approval requests omit paths; keep the kinds without retaining patch bodies. |
| 1344 | readonly fileChangeKindsByItem: Map<string, CodexFileChangeKinds>; |
| 1345 | readonly messagePhases: Map<string, "commentary" | "partial_answer" | "final_answer">; |
| 1346 | readonly itemPositions: Map< |
| 1347 | string, |
| 1348 | { readonly ordinal: number; readonly startedAt: DateTime.Utc } |
| 1349 | >; |
| 1350 | } |
| 1351 | |
| 1352 | interface ActiveCodexProviderRetry { |
| 1353 | readonly context?: ActiveCodexTurnContext; |
| 1354 | readonly nativeMessage: string; |
| 1355 | readonly nativeCode: string | null; |
| 1356 | readonly nativeDetails?: string; |
| 1357 | readonly errorInfo?: CodexErrorInfo | null; |
| 1358 | readonly retry: OrchestrationV2ProviderRetry; |
| 1359 | readonly failure: OrchestrationV2ProviderFailure; |
| 1360 | readonly startedAt: DateTime.Utc; |
| 1361 | readonly itemOrdinal: number; |
| 1362 | } |
| 1363 | |
| 1364 | function codexRetryTurnItem( |
| 1365 | activeContext: ActiveCodexTurnContext, |
| 1366 | state: ActiveCodexProviderRetry, |
| 1367 | status: Parameters<typeof makeProviderRetryTurnItem>[0]["status"], |
| 1368 | updatedAt: DateTime.Utc, |
| 1369 | ) { |
| 1370 | // A continuation keeps the retry row attached to the native turn that failed. |
| 1371 | const context = state.context ?? activeContext; |
| 1372 | return makeProviderRetryTurnItem({ |
| 1373 | driver: CODEX_PROVIDER, |
| 1374 | threadId: context.projectionThreadId, |
| 1375 | runId: context.projectionRunId, |
| 1376 | nodeId: context.providerNodeId, |
| 1377 | providerThreadId: context.providerThread.id, |
| 1378 | providerTurnId: context.providerTurnId, |
| 1379 | itemOrdinal: state.itemOrdinal, |
| 1380 | failure: state.failure, |
| 1381 | retry: state.retry, |
| 1382 | status, |
| 1383 | startedAt: state.startedAt, |
| 1384 | updatedAt, |
| 1385 | }); |
| 1386 | } |
| 1387 | |
| 1388 | interface TrackedRunningCommandItem { |
| 1389 | readonly id: string; |
| 1390 | readonly command: string; |
| 1391 | readonly aggregatedOutput?: string; |
| 1392 | readonly processId?: string; |
| 1393 | } |
| 1394 | |
| 1395 | function isPersistentCodexDynamicTool(item: CodexDynamicToolItem): boolean { |
| 1396 | const input = item.arguments; |
| 1397 | if (input === null || typeof input !== "object" || Array.isArray(input)) { |
| 1398 | return false; |
| 1399 | } |
| 1400 | return Reflect.get(input, "persistent") === true; |
| 1401 | } |
| 1402 | |
| 1403 | type CodexRootTerminalEvent = Extract< |
| 1404 | ProviderAdapter.ProviderAdapterV2Event, |
| 1405 | { readonly type: "turn.terminal" } |
| 1406 | >; |
| 1407 | |
| 1408 | interface CodexGoalHold { |
| 1409 | readonly context: ActiveCodexTurnContext; |
| 1410 | readonly event: Extract<CodexRootTerminalEvent, { readonly failure: null }>; |
| 1411 | readonly completedTurn: OrchestrationV2ProviderTurn; |
| 1412 | readonly next: Deferred.Deferred<ActiveCodexTurnContext | undefined>; |
| 1413 | } |
| 1414 | |
| 1415 | interface DeferredCodexRootTerminal { |
| 1416 | readonly context: ActiveCodexTurnContext; |
| 1417 | readonly event: CodexRootTerminalEvent; |
| 1418 | } |
| 1419 | |
| 1420 | interface CodexSubagentThreadContext { |
| 1421 | parentContext: ActiveCodexTurnContext; |
| 1422 | readonly providerThread: OrchestrationV2ProviderThread; |
| 1423 | readonly childThread: OrchestrationV2AppThread; |
| 1424 | readonly subagentNodeId: OrchestrationV2ExecutionNode["id"]; |
| 1425 | readonly childRootNodeId: OrchestrationV2ExecutionNode["id"]; |
| 1426 | readonly childThreadId: ThreadId; |
| 1427 | readonly nativeTurnIds: Set<string>; |
| 1428 | startedAt: DateTime.Utc; |
| 1429 | readonly turnItemId: OrchestrationV2TurnItem["id"]; |
| 1430 | readonly turnItemOrdinal: number; |
| 1431 | task: OrchestrationV2Subagent; |
| 1432 | } |
| 1433 | |
| 1434 | const approvalOwnerCodexTurn = ( |
| 1435 | context: ActiveCodexTurnContext, |
| 1436 | ): { |
| 1437 | readonly owner: ActiveCodexTurnContext; |
| 1438 | readonly subagent: CodexSubagentThreadContext | null; |
| 1439 | } => { |
| 1440 | let owner = context; |
| 1441 | let subagent: CodexSubagentThreadContext | null = null; |
| 1442 | while (owner.subagent !== null) { |
| 1443 | subagent = owner.subagent; |
| 1444 | owner = owner.subagent.parentContext; |
| 1445 | } |
| 1446 | return { owner, subagent }; |
| 1447 | }; |
| 1448 | |
| 1449 | const isDescendantCodexTurn = ( |
| 1450 | candidate: ActiveCodexTurnContext, |
| 1451 | ancestor: ActiveCodexTurnContext, |
| 1452 | ): boolean => { |
| 1453 | let parent = candidate.subagent?.parentContext; |
| 1454 | while (parent !== undefined) { |
| 1455 | if (parent === ancestor) { |
| 1456 | return true; |
| 1457 | } |
| 1458 | parent = parent.subagent?.parentContext; |
| 1459 | } |
| 1460 | return false; |
| 1461 | }; |
| 1462 | |
| 1463 | interface PendingCodexSubagentTurnStarted { |
| 1464 | readonly nativeTurnId: string; |
| 1465 | readonly startedAt: DateTime.Utc; |
| 1466 | } |
| 1467 | |
| 1468 | type PendingCodexRuntimeRequest = |
| 1469 | | { |
| 1470 | readonly type: "approval"; |
| 1471 | readonly requestKind: ProviderRequestKind; |
| 1472 | readonly decision: Deferred.Deferred<ProviderApprovalDecision, never>; |
| 1473 | } |
| 1474 | | { |
| 1475 | readonly type: "user_input"; |
| 1476 | readonly answers: Deferred.Deferred<ProviderUserInputAnswers, never>; |
| 1477 | }; |
| 1478 | |
| 1479 | type CodexWebSearchItem = { |
| 1480 | readonly id: string; |
| 1481 | readonly type: "webSearch"; |
| 1482 | readonly query?: string | null; |
| 1483 | readonly action?: |
| 1484 | | CodexSchema.V2ItemStartedNotification__WebSearchAction |
| 1485 | | CodexSchema.V2ItemCompletedNotification__WebSearchAction |
| 1486 | | null; |
| 1487 | }; |
| 1488 | |
| 1489 | export type CodexDynamicToolItem = Extract< |
| 1490 | | CodexSchema.V2ItemStartedNotification__ThreadItem |
| 1491 | | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 1492 | { readonly type: "mcpToolCall" | "dynamicToolCall" } |
| 1493 | >; |
| 1494 | |
| 1495 | type CodexCollabAgentToolCallItem = Extract< |
| 1496 | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 1497 | { readonly type: "collabAgentToolCall" } |
| 1498 | >; |
| 1499 | |
| 1500 | type CodexSubAgentActivityItem = Extract< |
| 1501 | | CodexSchema.V2ItemStartedNotification__ThreadItem |
| 1502 | | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 1503 | { readonly type: "subAgentActivity" } |
| 1504 | >; |
| 1505 | |
| 1506 | export interface CodexAppServerClientFactoryShape { |
| 1507 | readonly open: (input: { |
| 1508 | readonly instanceId: ProviderInstanceId; |
| 1509 | readonly threadId: ThreadId; |
| 1510 | readonly providerSessionId: OrchestrationV2ProviderSession["id"]; |
| 1511 | readonly runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy; |
| 1512 | readonly settings: CodexSettings; |
| 1513 | readonly environment: NodeJS.ProcessEnv; |
| 1514 | }) => Effect.Effect< |
| 1515 | CodexClient.CodexAppServerClient["Service"], |
| 1516 | ProviderAdapter.ProviderAdapterOpenSessionError, |
| 1517 | Scope.Scope |
| 1518 | >; |
| 1519 | } |
| 1520 | |
| 1521 | export class CodexAppServerClientFactory extends Context.Service< |
| 1522 | CodexAppServerClientFactory, |
| 1523 | CodexAppServerClientFactoryShape |
| 1524 | >()("t3/orchestration-v2/Adapters/CodexAdapterV2/CodexAppServerClientFactory") {} |
| 1525 | |
| 1526 | /** MCP startup grace in milliseconds; the 1 s default excludes cold npx/uvx servers from the first model request. */ |
| 1527 | export const CODEX_THREAD_CONFIG = { |
| 1528 | "tools.update_plan.enabled": true, |
| 1529 | mcp_optional_startup_grace_ms: 10_000, |
| 1530 | // Tool calls stop waiting on the detailed reasoning summary. Codex applies it only to its |
| 1531 | // built-in OpenAI provider and sends each summary section whole, not as token deltas. |
| 1532 | "features.concurrent_reasoning_summaries": true, |
| 1533 | } as const; |
| 1534 | |
| 1535 | // request_secret can wait an hour; keep Codex's MCP timeout above that. |
| 1536 | const CODEX_T3_MCP_TOOL_TIMEOUT_SEC = 65 * 60; |
| 1537 | // Holds T3 tools Codex must call directly, never from Code Mode. Calls arrive as |
| 1538 | // `t3-code-direct.<tool>`; t3McpToolPresentation.ts must keep resolving that form. |
| 1539 | const CODEX_T3_DIRECT_MCP_SERVER = "t3-code-direct"; |
| 1540 | const CODEX_DIRECT_ONLY_T3_TOOLS = ["t3_thread_wait", "delegate_task"]; |
| 1541 | |
| 1542 | /** Names of the stdio MCP servers in a `config/read` config, the ones Codex starts per thread. */ |
| 1543 | function codexStdioMcpServerNames(mcpServers: unknown): ReadonlyArray<string> { |
| 1544 | if (mcpServers === null || typeof mcpServers !== "object") return []; |
| 1545 | return Object.entries(mcpServers) |
| 1546 | .filter( |
| 1547 | ([name, server]) => |
| 1548 | // Codex splits config override keys on every dot. |
| 1549 | !name.includes(".") && |
| 1550 | server !== null && |
| 1551 | typeof server === "object" && |
| 1552 | typeof Reflect.get(server, "command") === "string", |
| 1553 | ) |
| 1554 | .map(([name]) => name); |
| 1555 | } |
| 1556 | |
| 1557 | function codexThreadRuntimeParams(input: { |
| 1558 | readonly threadId: ThreadId | null; |
| 1559 | readonly mcpSession: McpProviderSession.McpProviderSessionConfig | undefined; |
| 1560 | readonly stdioMcpServers?: ReadonlyArray<string>; |
| 1561 | readonly modelSelection?: { readonly model: string }; |
| 1562 | readonly runtimePolicy?: ProviderAdapter.ProviderAdapterV2RuntimePolicy; |
| 1563 | }): { |
| 1564 | readonly cwd?: string; |
| 1565 | readonly model?: string; |
| 1566 | readonly config: Readonly<Record<string, Schema.Json>>; |
| 1567 | } { |
| 1568 | const { mcpSession } = input; |
| 1569 | const t3Server = |
| 1570 | mcpSession === undefined |
| 1571 | ? undefined |
| 1572 | : { |
| 1573 | url: mcpSession.endpoint, |
| 1574 | tool_timeout_sec: CODEX_T3_MCP_TOOL_TIMEOUT_SEC, |
| 1575 | http_headers: { Authorization: mcpSession.authorizationHeader }, |
| 1576 | }; |
| 1577 | return { |
| 1578 | ...(input.runtimePolicy?.cwd == null ? {} : { cwd: input.runtimePolicy.cwd }), |
| 1579 | ...(input.modelSelection === undefined ? {} : { model: input.modelSelection.model }), |
| 1580 | config: { |
| 1581 | ...CODEX_THREAD_CONFIG, |
| 1582 | // One app-server serves many threads, so the id goes in per-thread shell config, not its env. |
| 1583 | ...(input.threadId === null |
| 1584 | ? {} |
| 1585 | : { |
| 1586 | [`shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`]: input.threadId, |
| 1587 | // Codex starts the user's stdio MCP servers per thread, outside the shell policy. |
| 1588 | ...Object.fromEntries( |
| 1589 | (input.stdioMcpServers ?? []).map((name) => [ |
| 1590 | `mcp_servers.${name}.env.${PortScanner.AGENT_THREAD_ENV}`, |
| 1591 | input.threadId, |
| 1592 | ]), |
| 1593 | ), |
| 1594 | }), |
| 1595 | ...(t3Server === undefined |
| 1596 | ? {} |
| 1597 | : { |
| 1598 | // Override only T3's servers so launch-argument MCP servers survive. |
| 1599 | "mcp_servers.t3-code": { ...t3Server, disabled_tools: CODEX_DIRECT_ONLY_T3_TOOLS }, |
| 1600 | // Code Mode runs a blocking wait or delegate wait as a nested call, and the model |
| 1601 | // keeps polling it. A second, direct-only registration makes it a plain tool call. |
| 1602 | [`mcp_servers.${CODEX_T3_DIRECT_MCP_SERVER}`]: { |
| 1603 | ...t3Server, |
| 1604 | enabled_tools: CODEX_DIRECT_ONLY_T3_TOOLS, |
| 1605 | omit_tools_from: ["code_mode", "deferred"], |
| 1606 | }, |
| 1607 | }), |
| 1608 | }, |
| 1609 | }; |
| 1610 | } |
| 1611 | |
| 1612 | const decodeCodexResumeMetadata = Schema.decodeUnknownEffect( |
| 1613 | Schema.Struct({ thread: Schema.Struct({ id: Schema.String, updatedAt: Schema.Number }) }), |
| 1614 | ); |
| 1615 | |
| 1616 | const CodexChildSelection = Schema.Struct({ |
| 1617 | thread: Schema.Struct({ id: Schema.String }), |
| 1618 | model: Schema.NullOr(Schema.String), |
| 1619 | reasoningEffort: Schema.optional(Schema.NullOr(Schema.String)), |
| 1620 | serviceTier: Schema.optional(Schema.NullOr(Schema.String)), |
| 1621 | }); |
| 1622 | const decodeCodexChildModel = Schema.decodeUnknownEffect(CodexChildSelection); |
| 1623 | |
| 1624 | const decodeCodexChildThread = Schema.decodeUnknownEffect( |
| 1625 | Schema.Struct({ |
| 1626 | thread: Schema.Struct({ |
| 1627 | id: Schema.String, |
| 1628 | model: Schema.optional(Schema.NullOr(Schema.String)), |
| 1629 | reasoningEffort: Schema.optional(Schema.NullOr(Schema.String)), |
| 1630 | }), |
| 1631 | }), |
| 1632 | ); |
| 1633 | |
| 1634 | // Without a deadline the spawner waits indefinitely for a process that ignores SIGTERM. |
| 1635 | const CODEX_APP_SERVER_FORCE_KILL_AFTER = "2 seconds"; |
| 1636 | |
| 1637 | export const makeCodexAppServerSpawnCommand = Effect.fn( |
| 1638 | "CodexAdapterV2.makeCodexAppServerSpawnCommand", |
| 1639 | )(function* (input: { |
| 1640 | readonly command: string; |
| 1641 | readonly args: ReadonlyArray<string>; |
| 1642 | readonly cwd?: string | undefined; |
| 1643 | readonly env?: NodeJS.ProcessEnv | undefined; |
| 1644 | readonly extendEnv?: boolean | undefined; |
| 1645 | readonly threadId?: string | undefined; |
| 1646 | }) { |
| 1647 | const launch = yield* (yield* AgentScope).wrap({ |
| 1648 | command: input.command, |
| 1649 | args: input.args, |
| 1650 | name: "codex", |
| 1651 | threadId: input.threadId, |
| 1652 | env: input.env, |
| 1653 | shared: true, |
| 1654 | }); |
| 1655 | const spawnCommand = yield* resolveSpawnCommand(launch.command, launch.args, { |
| 1656 | ...(input.env === undefined ? {} : { env: input.env }), |
| 1657 | ...(input.extendEnv === undefined ? {} : { extendEnv: input.extendEnv }), |
| 1658 | }); |
| 1659 | return ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 1660 | ...(input.cwd === undefined ? {} : { cwd: input.cwd }), |
| 1661 | ...(input.env === undefined ? {} : { env: input.env }), |
| 1662 | ...(input.extendEnv === undefined ? {} : { extendEnv: input.extendEnv }), |
| 1663 | shell: spawnCommand.shell, |
| 1664 | forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER, |
| 1665 | }); |
| 1666 | }); |
| 1667 | |
| 1668 | function readCodexProtocolPath(value: unknown, ...path: ReadonlyArray<string>): unknown { |
| 1669 | let current = value; |
| 1670 | for (const key of path) { |
| 1671 | if (current === null || typeof current !== "object") return undefined; |
| 1672 | current = Reflect.get(current, key); |
| 1673 | } |
| 1674 | return current; |
| 1675 | } |
| 1676 | |
| 1677 | /** Codex sets this on every command it starts, to that command's item id. */ |
| 1678 | const CODEX_COMMAND_ITEM_ENV = "CODEX_TOOL_CALL_ID"; |
| 1679 | const CODEX_THREAD_ENV_CONFIG_KEY = `shell_environment_policy.set.${PortScanner.AGENT_THREAD_ENV}`; |
| 1680 | |
| 1681 | /** |
| 1682 | * One app-server serves every Codex thread on an instance, so each frame is routed to the |
| 1683 | * T3 thread it belongs to. Frames tied to no thread, such as `initialize`, go to the global log. |
| 1684 | */ |
| 1685 | function makeCodexProtocolThreadRouter() { |
| 1686 | const threadIdsByNativeId = new Map<string, ThreadId>(); |
| 1687 | const threadIdsByRequest = new Map<string, ThreadId>(); |
| 1688 | return (direction: "incoming" | "outgoing", frame: unknown): ThreadId | null => { |
| 1689 | const id = readCodexProtocolPath(frame, "id"); |
| 1690 | const method = readCodexProtocolPath(frame, "method"); |
| 1691 | const isRequest = typeof method === "string"; |
| 1692 | const requestKey = |
| 1693 | typeof id === "string" || typeof id === "number" |
| 1694 | ? `${isRequest === (direction === "outgoing") ? "client" : "server"}:${id}` |
| 1695 | : undefined; |
| 1696 | if (!isRequest) { |
| 1697 | if (requestKey === undefined) return null; |
| 1698 | const threadId = threadIdsByRequest.get(requestKey); |
| 1699 | threadIdsByRequest.delete(requestKey); |
| 1700 | const nativeThreadId = readCodexProtocolPath(frame, "result", "thread", "id"); |
| 1701 | if (threadId !== undefined && typeof nativeThreadId === "string") { |
| 1702 | threadIdsByNativeId.set(nativeThreadId, threadId); |
| 1703 | } |
| 1704 | return threadId ?? null; |
| 1705 | } |
| 1706 | |
| 1707 | const params = readCodexProtocolPath(frame, "params"); |
| 1708 | const configuredThreadId = readCodexProtocolPath(params, "config", CODEX_THREAD_ENV_CONFIG_KEY); |
| 1709 | const nativeThreadId = |
| 1710 | readCodexProtocolPath(params, "threadId") ?? readCodexProtocolPath(params, "thread", "id"); |
| 1711 | let threadId = |
| 1712 | typeof configuredThreadId === "string" |
| 1713 | ? ThreadId.make(configuredThreadId) |
| 1714 | : typeof nativeThreadId === "string" |
| 1715 | ? threadIdsByNativeId.get(nativeThreadId) |
| 1716 | : undefined; |
| 1717 | if (threadId === undefined && typeof nativeThreadId === "string") { |
| 1718 | const parentNativeThreadId = readCodexProtocolPath( |
| 1719 | params, |
| 1720 | "thread", |
| 1721 | "source", |
| 1722 | "subAgent", |
| 1723 | "thread_spawn", |
| 1724 | "parent_thread_id", |
| 1725 | ); |
| 1726 | threadId = |
| 1727 | typeof parentNativeThreadId === "string" |
| 1728 | ? threadIdsByNativeId.get(parentNativeThreadId) |
| 1729 | : undefined; |
| 1730 | if (threadId !== undefined) threadIdsByNativeId.set(nativeThreadId, threadId); |
| 1731 | } |
| 1732 | if (threadId !== undefined && requestKey !== undefined) { |
| 1733 | threadIdsByRequest.set(requestKey, threadId); |
| 1734 | } |
| 1735 | return threadId ?? null; |
| 1736 | }; |
| 1737 | } |
| 1738 | |
| 1739 | export function makeCodexAppServerProtocolLogger(input: { |
| 1740 | readonly nativeEventLogger: ProviderEventLoggers.EventNdjsonLogger | undefined; |
| 1741 | readonly providerSessionId: OrchestrationV2ProviderSession["id"]; |
| 1742 | }): CodexClient.CodexAppServerClientOptions["logger"] | undefined { |
| 1743 | const { nativeEventLogger } = input; |
| 1744 | if (nativeEventLogger === undefined) { |
| 1745 | return undefined; |
| 1746 | } |
| 1747 | |
| 1748 | const routeThread = makeCodexProtocolThreadRouter(); |
| 1749 | return (event) => { |
| 1750 | if (!shouldPersistProviderEvent("native", event)) return Effect.void; |
| 1751 | const threadId = event.stage === "decoded" ? routeThread(event.direction, event.payload) : null; |
| 1752 | return nativeEventLogger |
| 1753 | .write( |
| 1754 | { |
| 1755 | provider: CODEX_PROVIDER, |
| 1756 | protocol: "codex.app-server", |
| 1757 | kind: "protocol", |
| 1758 | providerSessionId: input.providerSessionId, |
| 1759 | event: redactCodexProtocolValue(boundProviderEventForLogging(event)), |
| 1760 | }, |
| 1761 | threadId, |
| 1762 | ) |
| 1763 | .pipe(Effect.ignore); |
| 1764 | }; |
| 1765 | } |
| 1766 | |
| 1767 | function redactCodexProtocolValue(value: unknown): unknown { |
| 1768 | if (Array.isArray(value)) { |
| 1769 | return value.map(redactCodexProtocolValue); |
| 1770 | } |
| 1771 | if (value === null || typeof value !== "object") { |
| 1772 | if (typeof value !== "string") { |
| 1773 | return value; |
| 1774 | } |
| 1775 | if (/^Bearer\s+/i.test(value)) { |
| 1776 | return "[REDACTED]"; |
| 1777 | } |
| 1778 | const trimmed = value.trim(); |
| 1779 | if ( |
| 1780 | !( |
| 1781 | (trimmed.startsWith("{") && trimmed.endsWith("}")) || |
| 1782 | (trimmed.startsWith("[") && trimmed.endsWith("]")) |
| 1783 | ) |
| 1784 | ) { |
| 1785 | return value; |
| 1786 | } |
| 1787 | try { |
| 1788 | return pipe( |
| 1789 | JSON.parse(trimmed) as unknown, |
| 1790 | boundProviderEventForLogging, |
| 1791 | redactCodexProtocolValue, |
| 1792 | JSON.stringify, |
| 1793 | ); |
| 1794 | } catch { |
| 1795 | return value; |
| 1796 | } |
| 1797 | } |
| 1798 | return Object.fromEntries( |
| 1799 | Object.entries(value).map(([key, nested]) => [ |
| 1800 | key, |
| 1801 | isSensitiveCodexProtocolKey(key) ? "[REDACTED]" : redactCodexProtocolValue(nested), |
| 1802 | ]), |
| 1803 | ); |
| 1804 | } |
| 1805 | |
| 1806 | function isSensitiveCodexProtocolKey(key: string): boolean { |
| 1807 | const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase(); |
| 1808 | return ( |
| 1809 | normalized.endsWith("authorization") || |
| 1810 | normalized.endsWith("apikey") || |
| 1811 | normalized.endsWith("token") || |
| 1812 | normalized.endsWith("password") || |
| 1813 | normalized.endsWith("secret") |
| 1814 | ); |
| 1815 | } |
| 1816 | |
| 1817 | export const layerAppServerClientFactory: Layer.Layer< |
| 1818 | CodexAppServerClientFactory, |
| 1819 | never, |
| 1820 | | ChildProcessSpawner.ChildProcessSpawner |
| 1821 | | PortScanner.PortDiscovery |
| 1822 | | ProviderEventLoggers.ProviderEventLoggers |
| 1823 | > = Layer.effect( |
| 1824 | CodexAppServerClientFactory, |
| 1825 | Effect.gen(function* () { |
| 1826 | const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; |
| 1827 | const { native: nativeEventLogger } = yield* ProviderEventLoggers.ProviderEventLoggers; |
| 1828 | const agentScope = yield* AgentScope; |
| 1829 | const portDiscovery = yield* PortScanner.PortDiscovery; |
| 1830 | |
| 1831 | return CodexAppServerClientFactory.of({ |
| 1832 | open: Effect.fn("CodexAdapterV2.open")(function* (input) { |
| 1833 | const scope = yield* Scope.Scope; |
| 1834 | const environment = { |
| 1835 | ...codexAppServerEnvironment(input.environment), |
| 1836 | ...(input.settings.homePath ? { CODEX_HOME: input.settings.homePath } : {}), |
| 1837 | }; |
| 1838 | const command = yield* makeCodexAppServerSpawnCommand({ |
| 1839 | command: input.settings.binaryPath || "codex", |
| 1840 | args: codexAppServerArgs( |
| 1841 | resolveCodexLaunchArgs(input.settings.launchArgs, input.environment), |
| 1842 | ), |
| 1843 | env: environment, |
| 1844 | threadId: input.threadId, |
| 1845 | }).pipe(Effect.provideService(AgentScope, agentScope)); |
| 1846 | const handle = yield* spawner.spawn(command).pipe( |
| 1847 | Effect.provideService(Scope.Scope, scope), |
| 1848 | Effect.mapError( |
| 1849 | (cause) => |
| 1850 | new ProviderAdapter.ProviderAdapterOpenSessionError({ |
| 1851 | driver: CODEX_PROVIDER, |
| 1852 | providerSessionId: input.providerSessionId, |
| 1853 | cause, |
| 1854 | }), |
| 1855 | ), |
| 1856 | ); |
| 1857 | // Its shells carry each thread's T3CODE_THREAD_ID, so port discovery reads listeners' threads. |
| 1858 | yield* Effect.acquireRelease(Effect.sync(portDiscovery.trackAgent), (release) => |
| 1859 | Effect.sync(release), |
| 1860 | ); |
| 1861 | const protocolLogger = makeCodexAppServerProtocolLogger({ |
| 1862 | nativeEventLogger, |
| 1863 | providerSessionId: input.providerSessionId, |
| 1864 | }); |
| 1865 | const clientOptions: CodexClient.CodexAppServerClientOptions = |
| 1866 | protocolLogger === undefined |
| 1867 | ? {} |
| 1868 | : { |
| 1869 | logIncoming: true, |
| 1870 | logOutgoing: true, |
| 1871 | logger: protocolLogger, |
| 1872 | }; |
| 1873 | const context = yield* Layer.build(CodexClient.layerChildProcess(handle, clientOptions)); |
| 1874 | return yield* Effect.service(CodexClient.CodexAppServerClient).pipe( |
| 1875 | Effect.provide(context), |
| 1876 | ); |
| 1877 | }), |
| 1878 | }); |
| 1879 | }), |
| 1880 | ); |
| 1881 | |
| 1882 | export type CodexAdapterV2DriverEnv = |
| 1883 | | CodexAppServerClientFactory |
| 1884 | | Digest.Digest |
| 1885 | | FileSystem.FileSystem |
| 1886 | | IdAllocator.IdAllocatorV2 |
| 1887 | | McpProviderSessions.McpProviderSessions |
| 1888 | | Path.Path |
| 1889 | | PortScanner.PortDiscovery |
| 1890 | | ServerConfig; |
| 1891 | |
| 1892 | export const createCodexAdapterV2 = Effect.fn("CodexAdapterV2.createCodexAdapterV2")(function* ( |
| 1893 | { instanceId, environment, enabled, config }: ProviderAdapterDriverCreateInput<CodexSettings>, |
| 1894 | hooks: Pick< |
| 1895 | CodexAdapterV2Options, |
| 1896 | "onUsageLimits" | "resolveRuntime" | "compatibility" | "models" |
| 1897 | > = {}, |
| 1898 | ) { |
| 1899 | const clientFactory = yield* CodexAppServerClientFactory; |
| 1900 | const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; |
| 1901 | const digest = yield* Digest.Digest; |
| 1902 | const fileSystem = yield* FileSystem.FileSystem; |
| 1903 | const hostEnvironment = yield* HostProcess.Environment; |
| 1904 | const idAllocator = yield* IdAllocator.IdAllocatorV2; |
| 1905 | const portDiscovery = yield* PortScanner.PortDiscovery; |
| 1906 | const serverConfig = yield* ServerConfig; |
| 1907 | const homeLayout = yield* resolveCodexHomeLayout(config); |
| 1908 | |
| 1909 | yield* materializeCodexShadowHome(homeLayout).pipe( |
| 1910 | Effect.mapError( |
| 1911 | (cause) => |
| 1912 | new ProviderAdapterDriverCreateError({ |
| 1913 | driver: CODEX_DRIVER_KIND, |
| 1914 | instanceId, |
| 1915 | detail: "Failed to materialize the Codex shadow home.", |
| 1916 | cause, |
| 1917 | }), |
| 1918 | ), |
| 1919 | ); |
| 1920 | |
| 1921 | const settings = { |
| 1922 | ...config, |
| 1923 | enabled, |
| 1924 | binaryPath: expandHomePath(config.binaryPath, yield* HostProcess.HomeDirectory), |
| 1925 | homePath: homeLayout.effectiveHomePath ?? "", |
| 1926 | launchArgs: codexHomeLaunchArgs(yield* Path.Path, homeLayout, config.launchArgs), |
| 1927 | } satisfies CodexSettings; |
| 1928 | |
| 1929 | return yield* makeCodexAdapterV2({ |
| 1930 | instanceId, |
| 1931 | settings, |
| 1932 | environment: yield* mergeProviderInstanceEnvironment(environment, hostEnvironment), |
| 1933 | clientFactory, |
| 1934 | digest, |
| 1935 | fileSystem, |
| 1936 | idAllocator, |
| 1937 | serverConfig, |
| 1938 | continuationRequests, |
| 1939 | watchCommandStops: portDiscovery.watchAgentCommandStops, |
| 1940 | ...hooks, |
| 1941 | }); |
| 1942 | }); |
| 1943 | |
| 1944 | export interface CodexAdapterV2Options { |
| 1945 | readonly instanceId: ProviderInstanceId; |
| 1946 | readonly settings: CodexSettings; |
| 1947 | readonly environment: NodeJS.ProcessEnv; |
| 1948 | readonly clientFactory: CodexAppServerClientFactoryShape; |
| 1949 | readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"]; |
| 1950 | /** The provider's published models, read per turn for catalog defaults. */ |
| 1951 | readonly models?: Effect.Effect<ReadonlyArray<ServerProviderModel>>; |
| 1952 | readonly resolveRuntime?: Effect.Effect<CodexEffectiveRuntime, ProviderSetupError, Scope.Scope>; |
| 1953 | readonly compatibility?: ( |
| 1954 | version: string, |
| 1955 | ) => Effect.Effect<ServerProviderCompatibilityAdvisory | undefined>; |
| 1956 | readonly digest: Digest.Digest["Service"]; |
| 1957 | readonly fileSystem: FileSystem.FileSystem; |
| 1958 | readonly idAllocator: IdAllocator.IdAllocatorV2["Service"]; |
| 1959 | readonly serverConfig: ServerConfig["Service"]; |
| 1960 | /** Omitting this leaves late completions projection-only. */ |
| 1961 | readonly continuationRequests?: { |
| 1962 | readonly offer: ( |
| 1963 | request: ProviderContinuationRequests.ProviderContinuationRequest, |
| 1964 | ) => Effect.Effect<void>; |
| 1965 | }; |
| 1966 | /** Omitting this reports a command the user stopped as one that finished by itself. */ |
| 1967 | readonly watchCommandStops?: PortScanner.PortDiscovery["Service"]["watchAgentCommandStops"]; |
| 1968 | } |
| 1969 | |
| 1970 | export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( |
| 1971 | adapterOptions: CodexAdapterV2Options, |
| 1972 | ) { |
| 1973 | const mcpSessions = yield* McpProviderSessions.McpProviderSessions; |
| 1974 | const readMcpSession = (threadId: ThreadId | null) => |
| 1975 | threadId === null ? Effect.undefined : mcpSessions.read(threadId); |
| 1976 | const { clientFactory, digest, fileSystem, idAllocator, serverConfig } = adapterOptions; |
| 1977 | const continuationRequests = adapterOptions.continuationRequests; |
| 1978 | |
| 1979 | return ProviderAdapter.ProviderAdapterV2.of({ |
| 1980 | instanceId: adapterOptions.instanceId, |
| 1981 | driver: CODEX_PROVIDER, |
| 1982 | checksVersionAtHandshake: adapterOptions.compatibility !== undefined, |
| 1983 | getCapabilities: Effect.fn("CodexAdapterV2.getCapabilities")(function () { |
| 1984 | return Effect.succeed(CodexProviderCapabilitiesV2); |
| 1985 | }), |
| 1986 | planSelectionTransition: Effect.fn("CodexAdapterV2.planSelectionTransition")(function () { |
| 1987 | return Effect.succeed(turnScopedSelectionTransition()); |
| 1988 | }), |
| 1989 | openSession: Effect.fn("CodexAdapterV2.openSession")( |
| 1990 | function* (input) { |
| 1991 | const scope = yield* Scope.Scope; |
| 1992 | const resolvedRuntime = |
| 1993 | adapterOptions.resolveRuntime === undefined |
| 1994 | ? undefined |
| 1995 | : yield* adapterOptions.resolveRuntime.pipe( |
| 1996 | Effect.mapError( |
| 1997 | (cause) => |
| 1998 | new ProviderAdapter.ProviderAdapterOpenSessionError({ |
| 1999 | driver: CODEX_PROVIDER, |
| 2000 | providerSessionId: input.providerSessionId, |
| 2001 | cause, |
| 2002 | }), |
| 2003 | ), |
| 2004 | ); |
| 2005 | const client = yield* clientFactory.open({ |
| 2006 | instanceId: adapterOptions.instanceId, |
| 2007 | threadId: input.threadId, |
| 2008 | providerSessionId: input.providerSessionId, |
| 2009 | runtimePolicy: input.runtimePolicy, |
| 2010 | settings: resolvedRuntime?.config ?? adapterOptions.settings, |
| 2011 | environment: resolvedRuntime?.environment ?? adapterOptions.environment, |
| 2012 | }); |
| 2013 | const codexZone = codexTimeZone(resolvedRuntime?.environment ?? adapterOptions.environment); |
| 2014 | const additionalContextByThread = yield* Ref.make( |
| 2015 | new Map<string, NonNullable<CodexTurnStartParams["additionalContext"]>>(), |
| 2016 | ); |
| 2017 | const threadsAwaitingContextRestore = yield* Ref.make(new Set<string>()); |
| 2018 | // Codex drops client developer messages during compaction but only resends additionalContext |
| 2019 | // when it changes. Restore after turn/completed: items injected mid-turn make the turn sample again. |
| 2020 | const restoreAdditionalContext = Effect.fn("CodexAdapterV2.restoreAdditionalContext")( |
| 2021 | function* (threadId: string) { |
| 2022 | const context = (yield* Ref.get(additionalContextByThread)).get(threadId); |
| 2023 | if (!context) return; |
| 2024 | yield* client.request("thread/inject_items", { |
| 2025 | threadId, |
| 2026 | items: Object.entries(context).map(([key, entry]) => |
| 2027 | entry.kind === "untrusted" |
| 2028 | ? { |
| 2029 | type: "message", |
| 2030 | role: "user", |
| 2031 | content: [ |
| 2032 | { |
| 2033 | type: "input_text", |
| 2034 | text: `<external_${key}>${entry.value}</external_${key}>`, |
| 2035 | }, |
| 2036 | ], |
| 2037 | } |
| 2038 | : { |
| 2039 | type: "message", |
| 2040 | role: "developer", |
| 2041 | content: [{ type: "input_text", text: `<${key}>${entry.value}</${key}>` }], |
| 2042 | }, |
| 2043 | ), |
| 2044 | }); |
| 2045 | }, |
| 2046 | Effect.timeout("10 seconds"), |
| 2047 | Effect.catch((cause) => |
| 2048 | Effect.logWarning("Failed to restore Codex additional context after compaction.", { |
| 2049 | cause, |
| 2050 | }), |
| 2051 | ), |
| 2052 | ); |
| 2053 | const events = yield* Queue.unbounded< |
| 2054 | ProviderAdapter.ProviderAdapterV2Event, |
| 2055 | ProviderAdapter.ProviderAdapterEventStreamError |
| 2056 | >(); |
| 2057 | const initialized = yield* Ref.make(false); |
| 2058 | // After a timeout the session is retiring; waiters must not re-send to the hung app-server. |
| 2059 | const initializeTimeout = yield* Ref.make< |
| 2060 | ProviderAdapter.ProviderAdapterEventStreamError | undefined |
| 2061 | >(undefined); |
| 2062 | // Codex rejects a second initialize on the shared app-server. |
| 2063 | const initializePermit = yield* Semaphore.make(1); |
| 2064 | const ensureInitialized = initializePermit.withPermit( |
| 2065 | Effect.gen(function* () { |
| 2066 | const alreadyInitialized = yield* Ref.get(initialized); |
| 2067 | if (alreadyInitialized) { |
| 2068 | return; |
| 2069 | } |
| 2070 | const timedOut = yield* Ref.get(initializeTimeout); |
| 2071 | if (timedOut !== undefined) return yield* timedOut; |
| 2072 | |
| 2073 | const userAgent = yield* client |
| 2074 | .request("initialize", { |
| 2075 | clientInfo: buildCodexInitializeParams().clientInfo, |
| 2076 | capabilities: CODEX_CLIENT_CAPABILITIES, |
| 2077 | }) |
| 2078 | .pipe( |
| 2079 | Effect.map((response) => response.userAgent), |
| 2080 | Effect.catchTags({ |
| 2081 | // Interruption can leave Codex initialized before the local flag is set. |
| 2082 | CodexAppServerRequestError: (error) => |
| 2083 | error.code === -32600 && error.errorMessage === "Already initialized" |
| 2084 | ? Effect.succeed(null) |
| 2085 | : Effect.fail(error), |
| 2086 | }), |
| 2087 | // A hung app-server never answers, and every thread on this shared |
| 2088 | // session waits behind the permit. Failing the event stream retires |
| 2089 | // the session, so the next turn spawns a fresh app-server. |
| 2090 | Effect.timeoutOrElse({ |
| 2091 | duration: CODEX_INITIALIZE_TIMEOUT, |
| 2092 | orElse: () => { |
| 2093 | const error = new ProviderAdapter.ProviderAdapterEventStreamError({ |
| 2094 | driver: CODEX_PROVIDER, |
| 2095 | providerSessionId: input.providerSessionId, |
| 2096 | cause: `Codex app-server did not answer initialize within ${CODEX_INITIALIZE_TIMEOUT}.`, |
| 2097 | }); |
| 2098 | return Ref.set(initializeTimeout, error).pipe( |
| 2099 | Effect.andThen(Queue.fail(events, error)), |
| 2100 | Effect.andThen(Effect.fail(error)), |
| 2101 | ); |
| 2102 | }, |
| 2103 | }), |
| 2104 | ); |
| 2105 | const version = userAgent && /\/(\S+)/u.exec(userAgent)?.[1]; |
| 2106 | const advisory = |
| 2107 | version && adapterOptions.compatibility |
| 2108 | ? yield* adapterOptions.compatibility(version) |
| 2109 | : undefined; |
| 2110 | const refused = |
| 2111 | version && |
| 2112 | brokenRuntimeError({ |
| 2113 | instanceId: adapterOptions.instanceId, |
| 2114 | name: "Codex", |
| 2115 | version, |
| 2116 | advisory, |
| 2117 | }); |
| 2118 | if (refused) return yield* refused; |
| 2119 | yield* client.notify("initialized", undefined); |
| 2120 | yield* Ref.set(initialized, true); |
| 2121 | }), |
| 2122 | ); |
| 2123 | // A failed open is discarded, so the next turn spawns the updated binary. |
| 2124 | if (adapterOptions.compatibility !== undefined) yield* ensureInitialized; |
| 2125 | // Read per thread: a workspace's project config can add its own servers. |
| 2126 | const readStdioMcpServers = (cwd: string | null | undefined) => |
| 2127 | ensureInitialized.pipe( |
| 2128 | Effect.andThen( |
| 2129 | client.request("config/read", { |
| 2130 | ...(cwd == null ? {} : { cwd }), |
| 2131 | includeLayers: false, |
| 2132 | }), |
| 2133 | ), |
| 2134 | Effect.map((response) => codexStdioMcpServerNames(response.config.mcp_servers)), |
| 2135 | Effect.catch(() => |
| 2136 | Effect.logDebug("Codex config read failed.").pipe( |
| 2137 | Effect.as<ReadonlyArray<string>>([]), |
| 2138 | ), |
| 2139 | ), |
| 2140 | ); |
| 2141 | const now = yield* DateTime.now; |
| 2142 | const session = providerSession({ |
| 2143 | providerSessionId: input.providerSessionId, |
| 2144 | providerInstanceId: adapterOptions.instanceId, |
| 2145 | cwd: input.runtimePolicy.cwd, |
| 2146 | model: input.modelSelection.model, |
| 2147 | now, |
| 2148 | }); |
| 2149 | // Drain final notifications before the session manager retires the dead process. |
| 2150 | // Queue.fail lets readers take items already buffered before they see the failure. |
| 2151 | yield* client.awaitTermination.pipe( |
| 2152 | Effect.catch((cause) => |
| 2153 | Queue.fail( |
| 2154 | events, |
| 2155 | new ProviderAdapter.ProviderAdapterEventStreamError({ |
| 2156 | driver: CODEX_PROVIDER, |
| 2157 | providerSessionId: input.providerSessionId, |
| 2158 | cause, |
| 2159 | }), |
| 2160 | ), |
| 2161 | ), |
| 2162 | Effect.forkScoped, |
| 2163 | ); |
| 2164 | const rateLimitSnapshot = yield* Ref.make<CodexRateLimitSnapshot | undefined>(undefined); |
| 2165 | const limitedTurnItems = yield* Ref.make( |
| 2166 | new Map<ProviderThreadId, Extract<OrchestrationV2TurnItem, { type: "error" }>>(), |
| 2167 | ); |
| 2168 | const activeTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>()); |
| 2169 | // Codex reports MCP startup on thread start, usually before the turn context exists. |
| 2170 | const mcpStartupFailures = new Map<string, Map<string, CodexMcpStartupFailure>>(); |
| 2171 | // By server name: the shared app-server signs a server in for every thread at once. |
| 2172 | const mcpSignIns = new Map<string, CodexMcpSignIn>(); |
| 2173 | const turnTokenUsageByThread = new Map<string, CodexTurnTokenUsageState>(); |
| 2174 | const usageStateForThread = (nativeThreadId: string) => { |
| 2175 | let state = turnTokenUsageByThread.get(nativeThreadId); |
| 2176 | if (!state) { |
| 2177 | state = makeCodexTurnTokenUsageState(); |
| 2178 | turnTokenUsageByThread.set(nativeThreadId, state); |
| 2179 | } |
| 2180 | return state; |
| 2181 | }; |
| 2182 | const beginTurnTokenUsage = (context: ActiveCodexTurnContext) => { |
| 2183 | const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; |
| 2184 | if (!nativeThreadId) return; |
| 2185 | const state = usageStateForThread(nativeThreadId); |
| 2186 | if (state.activeTurnId !== context.nativeTurnId) { |
| 2187 | state.byTurnId.clear(); |
| 2188 | state.activeTurnId = context.nativeTurnId; |
| 2189 | getCodexTurnAccumulator(state, context.nativeTurnId); |
| 2190 | } |
| 2191 | }; |
| 2192 | const markSubagentUsage = (context: ActiveCodexTurnContext) => { |
| 2193 | const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; |
| 2194 | if (!nativeThreadId) return; |
| 2195 | getCodexTurnAccumulator( |
| 2196 | usageStateForThread(nativeThreadId), |
| 2197 | context.nativeTurnId, |
| 2198 | ).hasSubagents = true; |
| 2199 | }; |
| 2200 | const pendingRootTurns = yield* Ref.make( |
| 2201 | new Map<string, ProviderAdapter.ProviderAdapterV2TurnInput>(), |
| 2202 | ); |
| 2203 | const turnWaiters = yield* Ref.make(new Map<string, Deferred.Deferred<void, never>>()); |
| 2204 | const subagentThreads = yield* Ref.make(new Map<string, CodexSubagentThreadContext>()); |
| 2205 | const subagentSelections = new Map<string, Omit<ModelSelection, "instanceId">>(); |
| 2206 | // A reroute names one turn; until new settings arrive, the thread's model is unknown. |
| 2207 | const reroutedTurnModels = new Map<string, string>(); |
| 2208 | const reroutedThreads = new Set<string>(); |
| 2209 | const reportedTurnModel = (nativeThreadId: string, nativeTurnId: string) => { |
| 2210 | const rerouted = reroutedTurnModels.get(nativeTurnId); |
| 2211 | reroutedTurnModels.delete(nativeTurnId); |
| 2212 | if (rerouted !== undefined) return rerouted; |
| 2213 | return reroutedThreads.has(nativeThreadId) |
| 2214 | ? undefined |
| 2215 | : subagentSelections.get(nativeThreadId)?.model; |
| 2216 | }; |
| 2217 | const pendingSubagentTurns = yield* Ref.make( |
| 2218 | new Map<string, ReadonlyArray<PendingCodexSubagentTurnStarted>>(), |
| 2219 | ); |
| 2220 | const nextProviderTurnOrdinals = yield* Ref.make(new Map<string, number>()); |
| 2221 | const providerRetries = yield* Ref.make( |
| 2222 | new Map<ProviderTurnId, ActiveCodexProviderRetry>(), |
| 2223 | ); |
| 2224 | const planIds = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact["id"]>()); |
| 2225 | const pendingRuntimeRequests = yield* Ref.make( |
| 2226 | new Map<string, PendingCodexRuntimeRequest>(), |
| 2227 | ); |
| 2228 | /** Completed by thread/closed after this connection unsubscribes from the native thread. */ |
| 2229 | const threadClosings = new Map<string, Deferred.Deferred<void>>(); |
| 2230 | /** Codex acceptForSession covers only the exact command or patch, not future commands. */ |
| 2231 | const sessionApprovals = new Map< |
| 2232 | string, |
| 2233 | { readonly runtimeMode: RuntimeMode; readonly kinds: Set<ProviderRequestKind> } |
| 2234 | >(); |
| 2235 | // `codex resume` and the Codex app list the native name. A failed rename, including on a |
| 2236 | // Codex without thread/name/set, is forgotten so the next turn sends it again. |
| 2237 | const appliedThreadNames = new Map<string, string>(); |
| 2238 | const applyThreadName = Effect.fn("CodexAdapterV2.applyThreadName")(function* ( |
| 2239 | threadId: string, |
| 2240 | name: string, |
| 2241 | ) { |
| 2242 | if (appliedThreadNames.get(threadId) === name) return; |
| 2243 | const renamed = yield* client |
| 2244 | .request("thread/name/set", { threadId, name }) |
| 2245 | .pipe(Effect.timeout("10 seconds"), Effect.isSuccess); |
| 2246 | if (renamed) appliedThreadNames.set(threadId, name); |
| 2247 | else appliedThreadNames.delete(threadId); |
| 2248 | }); |
| 2249 | /** Bind answers to the request's approval set so mode changes invalidate late answers. */ |
| 2250 | const endSessionApprovalsOnModeChange = (context: ActiveCodexTurnContext) => { |
| 2251 | const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; |
| 2252 | if ( |
| 2253 | nativeThreadId != null && |
| 2254 | sessionApprovals.get(nativeThreadId)?.runtimeMode !== |
| 2255 | context.input.runtimePolicy.runtimeMode |
| 2256 | ) { |
| 2257 | sessionApprovals.delete(nativeThreadId); |
| 2258 | } |
| 2259 | }; |
| 2260 | const sessionAllowance = ( |
| 2261 | nativeThreadId: string, |
| 2262 | context: ActiveCodexTurnContext, |
| 2263 | ): Set<ProviderRequestKind> => { |
| 2264 | const runtimeMode = context.input.runtimePolicy.runtimeMode; |
| 2265 | const allowed = sessionApprovals.get(nativeThreadId); |
| 2266 | if (allowed?.runtimeMode === runtimeMode) return allowed.kinds; |
| 2267 | if (allowed !== undefined) return new Set(); |
| 2268 | const kinds = new Set<ProviderRequestKind>(); |
| 2269 | sessionApprovals.set(nativeThreadId, { runtimeMode, kinds }); |
| 2270 | return kinds; |
| 2271 | }; |
| 2272 | /** Retain settled contexts while background commands run so late item events still project. */ |
| 2273 | const settledTurns = yield* Ref.make(new Map<string, ActiveCodexTurnContext>()); |
| 2274 | const runningCommandItemsByTurn = yield* Ref.make( |
| 2275 | new Map<string, Map<string, TrackedRunningCommandItem>>(), |
| 2276 | ); |
| 2277 | const runningDynamicToolsByTurn = yield* Ref.make( |
| 2278 | new Map<string, Map<string, CodexDynamicToolItem>>(), |
| 2279 | ); |
| 2280 | const interruptingNativeTurns = yield* Ref.make(new Set<string>()); |
| 2281 | // Running commands the user is stopping outside a turn interrupt; their exit wakes nobody. |
| 2282 | const userStoppedCommandItemIds = yield* Ref.make(new Set<string>()); |
| 2283 | if (adapterOptions.watchCommandStops !== undefined) { |
| 2284 | yield* adapterOptions.watchCommandStops({ |
| 2285 | variable: CODEX_COMMAND_ITEM_ENV, |
| 2286 | onStop: Effect.fn("CodexAdapterV2.onCommandStop")(function* (itemId) { |
| 2287 | const running = yield* Ref.get(runningCommandItemsByTurn); |
| 2288 | if (![...running.values()].some((items) => items.has(itemId))) return; |
| 2289 | yield* Ref.update(userStoppedCommandItemIds, (current) => |
| 2290 | new Set(current).add(itemId), |
| 2291 | ); |
| 2292 | }), |
| 2293 | onStopAbandoned: (itemId) => |
| 2294 | Ref.update(userStoppedCommandItemIds, (current) => { |
| 2295 | const updated = new Set(current); |
| 2296 | updated.delete(itemId); |
| 2297 | return updated; |
| 2298 | }), |
| 2299 | }); |
| 2300 | } |
| 2301 | const terminalizedNonCompletedNativeTurns = yield* Ref.make(new Set<string>()); |
| 2302 | // Keep the stream open until descendants settle to avoid stranding child projections. |
| 2303 | const deferredRootTerminals = yield* Ref.make(new Map<string, DeferredCodexRootTerminal>()); |
| 2304 | const offeredContinuationItemsByTurn = yield* Ref.make(new Map<string, Set<string>>()); |
| 2305 | const finalAnswerItemIdsByTurn = yield* Ref.make(new Map<string, Set<string>>()); |
| 2306 | const completedFinalAnswerTextsByTurn = yield* Ref.make(new Map<string, Set<string>>()); |
| 2307 | const imageTurns = new Map< |
| 2308 | string, |
| 2309 | { |
| 2310 | readonly running: Map< |
| 2311 | string, |
| 2312 | { |
| 2313 | readonly revisedPrompt: string | null; |
| 2314 | readonly transparentBackground: boolean | null; |
| 2315 | } |
| 2316 | >; |
| 2317 | readonly saved: Map<string, string>; |
| 2318 | pending: boolean; |
| 2319 | answer?: { readonly id: string; readonly text: string }; |
| 2320 | } |
| 2321 | >(); |
| 2322 | const imageTurn = (nativeTurnId: string) => { |
| 2323 | let state = imageTurns.get(nativeTurnId); |
| 2324 | if (state === undefined) { |
| 2325 | state = { running: new Map(), saved: new Map(), pending: false }; |
| 2326 | imageTurns.set(nativeTurnId, state); |
| 2327 | } |
| 2328 | return state; |
| 2329 | }; |
| 2330 | // Serialize native completion and interrupt timeout so only one publishes terminal events. |
| 2331 | const turnTerminalizationPermit = yield* Semaphore.make(1); |
| 2332 | const goalsByNativeThread = new Map<string, OrchestrationV2ProviderGoal | null>(); |
| 2333 | const rootProviderThreads = new Map<string, OrchestrationV2ProviderThread>(); |
| 2334 | const goalHolds = new Map<string, CodexGoalHold>(); |
| 2335 | const continuedRuns = new Map<ProviderTurnId, Array<ActiveCodexTurnContext>>(); |
| 2336 | const capacityContinuations = new Map< |
| 2337 | string, |
| 2338 | { readonly context: ActiveCodexTurnContext; readonly retry: ActiveCodexProviderRetry } |
| 2339 | >(); |
| 2340 | const goalActivations = new Map<string, { stopped: boolean }>(); |
| 2341 | // Held runs must not complete while Stop resolves its target. |
| 2342 | const goalStops = new Map<string, number>(); |
| 2343 | // Goals paused because a delegated task will wake the thread; the next ordinary turn resumes them. |
| 2344 | const goalsPausedForWake = new Set<string>(); |
| 2345 | const latestRunTurnId = (providerTurnId: ProviderTurnId) => |
| 2346 | continuedRuns.get(providerTurnId)?.at(-1)?.providerTurnId ?? providerTurnId; |
| 2347 | const isContinuedRunDescendant = ( |
| 2348 | candidate: ActiveCodexTurnContext, |
| 2349 | context: ActiveCodexTurnContext, |
| 2350 | ) => |
| 2351 | (continuedRuns.get(context.providerTurnId) ?? [context]).some((ancestor) => |
| 2352 | isDescendantCodexTurn(candidate, ancestor), |
| 2353 | ); |
| 2354 | |
| 2355 | const emitProviderEvent = (event: ProviderAdapter.ProviderAdapterV2Event) => |
| 2356 | Queue.offer(events, event).pipe(Effect.asVoid); |
| 2357 | |
| 2358 | const promptSuggestionsEnabled = input.promptSuggestions ?? Effect.succeed(false); |
| 2359 | // Best effort: older Codex lacks thread/sample, and a sample fails once the user sends again. |
| 2360 | // Delegated threads share this session but have no one typing, so they never sample. |
| 2361 | const samplePromptSuggestion = Effect.fn("CodexAdapterV2.samplePromptSuggestion")( |
| 2362 | function* ( |
| 2363 | context: ActiveCodexTurnContext, |
| 2364 | nativeThreadId: string, |
| 2365 | nativeTurnId: string, |
| 2366 | ) { |
| 2367 | if ( |
| 2368 | isDelegatedAppThread(context.input.appThread) || |
| 2369 | !(yield* promptSuggestionsEnabled) |
| 2370 | ) { |
| 2371 | return; |
| 2372 | } |
| 2373 | const response = yield* client.raw.request("thread/sample", { |
| 2374 | threadId: nativeThreadId, |
| 2375 | expectedTurnId: nativeTurnId, |
| 2376 | prompt: CODEX_PROMPT_SUGGESTION_PROMPT, |
| 2377 | effort: "low", |
| 2378 | }); |
| 2379 | const suggestion = |
| 2380 | (yield* decodeCodexThreadSampleResponse(response)).text?.trim() ?? ""; |
| 2381 | // Delegated completion wakes arrive as user input, so samples can imitate one. |
| 2382 | if (suggestion.length === 0 || suggestion.startsWith("Delegated task")) return; |
| 2383 | yield* emitProviderEvent({ |
| 2384 | type: "prompt_suggestion.updated", |
| 2385 | driver: CODEX_PROVIDER, |
| 2386 | threadId: context.projectionThreadId, |
| 2387 | runId: context.input.runId, |
| 2388 | text: suggestion, |
| 2389 | }); |
| 2390 | }, |
| 2391 | Effect.catchCause((cause) => |
| 2392 | Effect.logDebug("orchestration-v2.codex-prompt-suggestion-failed", { cause }), |
| 2393 | ), |
| 2394 | ); |
| 2395 | |
| 2396 | const emitImageWorkState = |
| 2397 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2398 | Effect.fnUntraced(function* (context: ActiveCodexTurnContext, pending: boolean) { |
| 2399 | const state = imageTurns.get(context.nativeTurnId); |
| 2400 | if (state === undefined || state.pending === pending) return; |
| 2401 | state.pending = pending; |
| 2402 | yield* emitProviderEvent({ |
| 2403 | type: "background_work.updated", |
| 2404 | driver: CODEX_PROVIDER, |
| 2405 | providerTurnId: context.providerTurnId, |
| 2406 | pending, |
| 2407 | }); |
| 2408 | }); |
| 2409 | |
| 2410 | const clearImageWork = Effect.fn("CodexAdapterV2.clearImageWork")(function* ( |
| 2411 | context: ActiveCodexTurnContext, |
| 2412 | ) { |
| 2413 | for (const [id, input] of imageTurns.get(context.nativeTurnId)?.running ?? []) { |
| 2414 | yield* emitImageGenerationItem( |
| 2415 | context, |
| 2416 | { |
| 2417 | type: "imageGeneration", |
| 2418 | id, |
| 2419 | ...input, |
| 2420 | status: "cancelled", |
| 2421 | result: "", |
| 2422 | }, |
| 2423 | true, |
| 2424 | ); |
| 2425 | } |
| 2426 | yield* emitImageWorkState(context, false); |
| 2427 | imageTurns.delete(context.nativeTurnId); |
| 2428 | }); |
| 2429 | |
| 2430 | // Setting a goal passes through cleared and paused states; publish only the result. |
| 2431 | const goalUpdatesHeld = new Set<string>(); |
| 2432 | const emitGoalUpdate = Effect.fnUntraced(function* (nativeThreadId: string) { |
| 2433 | const providerThread = rootProviderThreads.get(nativeThreadId); |
| 2434 | if ( |
| 2435 | providerThread === undefined || |
| 2436 | !goalsByNativeThread.has(nativeThreadId) || |
| 2437 | goalUpdatesHeld.has(nativeThreadId) |
| 2438 | ) { |
| 2439 | return; |
| 2440 | } |
| 2441 | const goal = goalsByNativeThread.get(nativeThreadId) ?? null; |
| 2442 | if (providerGoalsEqual(providerThread.goal ?? null, goal)) return; |
| 2443 | const updated = { ...providerThread, goal, updatedAt: yield* DateTime.now }; |
| 2444 | rootProviderThreads.set(nativeThreadId, updated); |
| 2445 | yield* emitProviderEvent({ |
| 2446 | type: "provider_thread.updated", |
| 2447 | driver: CODEX_PROVIDER, |
| 2448 | providerThread: updated, |
| 2449 | }); |
| 2450 | }); |
| 2451 | |
| 2452 | const rememberRootProviderThread = Effect.fnUntraced(function* ( |
| 2453 | providerThread: OrchestrationV2ProviderThread, |
| 2454 | ) { |
| 2455 | const nativeThreadId = providerThread.nativeThreadRef?.nativeId; |
| 2456 | if (nativeThreadId == null) return; |
| 2457 | rootProviderThreads.set(nativeThreadId, providerThread); |
| 2458 | yield* emitGoalUpdate(nativeThreadId); |
| 2459 | }); |
| 2460 | |
| 2461 | const emitMcpStartupFailures = Effect.fn("CodexAdapterV2.emitMcpStartupFailures")( |
| 2462 | function* (context: ActiveCodexTurnContext) { |
| 2463 | const nativeThreadId = context.providerThread.nativeThreadRef?.nativeId; |
| 2464 | if (nativeThreadId == null) return; |
| 2465 | const failures = mcpStartupFailures.get(nativeThreadId); |
| 2466 | if (failures === undefined) return; |
| 2467 | mcpStartupFailures.delete(nativeThreadId); |
| 2468 | for (const [name, failure] of failures) { |
| 2469 | const nativeItemId = `mcp-startup-failed:${context.providerTurnId}:${name}`; |
| 2470 | const { ordinal, startedAt } = yield* resolveItemPosition(context, nativeItemId); |
| 2471 | yield* emitProviderEvent({ |
| 2472 | type: "turn_item.updated", |
| 2473 | driver: CODEX_PROVIDER, |
| 2474 | turnItem: { |
| 2475 | id: idAllocator.derive.turnItemFromProviderItem({ |
| 2476 | driver: CODEX_PROVIDER, |
| 2477 | nativeItemId, |
| 2478 | }), |
| 2479 | threadId: context.projectionThreadId, |
| 2480 | runId: context.projectionRunId, |
| 2481 | nodeId: context.providerNodeId, |
| 2482 | providerThreadId: context.providerThread.id, |
| 2483 | providerTurnId: context.providerTurnId, |
| 2484 | nativeItemRef: { ...codexNativeItemRef(nativeItemId), strength: "weak" }, |
| 2485 | parentItemId: null, |
| 2486 | ordinal, |
| 2487 | type: "system_notice", |
| 2488 | status: "completed", |
| 2489 | title: `MCP server ${name} failed to start`, |
| 2490 | message: failure.message, |
| 2491 | ...(failure.signIn ? { mcpSignIn: { server: name } } : {}), |
| 2492 | startedAt, |
| 2493 | completedAt: startedAt, |
| 2494 | updatedAt: startedAt, |
| 2495 | }, |
| 2496 | }); |
| 2497 | } |
| 2498 | }, |
| 2499 | ); |
| 2500 | |
| 2501 | const releaseGoalUpdates = (nativeThreadId: string) => |
| 2502 | Effect.suspend(() => { |
| 2503 | goalUpdatesHeld.delete(nativeThreadId); |
| 2504 | return emitGoalUpdate(nativeThreadId); |
| 2505 | }); |
| 2506 | |
| 2507 | // Only new model output proves recovery; local item/completed can arrive during upstream retries. |
| 2508 | // Runs on every model output frame and is almost always a no-op; only a pending retry gets a span. |
| 2509 | const completeProviderRetry = Effect.fnUntraced(function* ( |
| 2510 | context: ActiveCodexTurnContext, |
| 2511 | updatedAt: DateTime.Utc, |
| 2512 | ) { |
| 2513 | const providerRetry = yield* Ref.modify(providerRetries, (current) => { |
| 2514 | const retry = current.get(context.providerTurnId); |
| 2515 | if (retry === undefined) { |
| 2516 | return [undefined, current] as const; |
| 2517 | } |
| 2518 | const updated = new Map(current); |
| 2519 | updated.delete(context.providerTurnId); |
| 2520 | return [retry, updated] as const; |
| 2521 | }); |
| 2522 | if (providerRetry === undefined) { |
| 2523 | return; |
| 2524 | } |
| 2525 | yield* emitProviderEvent({ |
| 2526 | type: "turn_item.updated", |
| 2527 | driver: CODEX_PROVIDER, |
| 2528 | turnItem: codexRetryTurnItem(context, providerRetry, "completed", updatedAt), |
| 2529 | }).pipe(Effect.withSpan("CodexAdapterV2.completeProviderRetry")); |
| 2530 | }); |
| 2531 | |
| 2532 | const registerRootTurn = Effect.fn("CodexAdapterV2.registerRootTurn")(function* (input: { |
| 2533 | readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; |
| 2534 | readonly nativeTurnId: string; |
| 2535 | readonly startedAt: DateTime.Utc; |
| 2536 | readonly waitForNativeStart?: boolean; |
| 2537 | }) { |
| 2538 | const existing = (yield* Ref.get(activeTurns)).get(input.nativeTurnId); |
| 2539 | if (existing !== undefined) { |
| 2540 | return existing; |
| 2541 | } |
| 2542 | const providerTurnId = idAllocator.derive.providerTurn({ |
| 2543 | driver: CODEX_PROVIDER, |
| 2544 | nativeTurnId: input.nativeTurnId, |
| 2545 | }); |
| 2546 | const context: ActiveCodexTurnContext = { |
| 2547 | ...(input.waitForNativeStart ? { nativeStartReady: yield* Deferred.make<void>() } : {}), |
| 2548 | input: input.turnInput, |
| 2549 | projectionAppThread: input.turnInput.appThread, |
| 2550 | projectionThreadId: input.turnInput.threadId, |
| 2551 | projectionRunId: input.turnInput.runId, |
| 2552 | nativeTurnId: input.nativeTurnId, |
| 2553 | providerThread: input.turnInput.providerThread, |
| 2554 | providerTurnId, |
| 2555 | providerTurnOrdinal: input.turnInput.providerTurnOrdinal, |
| 2556 | providerNodeId: input.turnInput.rootNodeId, |
| 2557 | providerNodeStartedAt: input.startedAt, |
| 2558 | itemParentNodeId: input.turnInput.rootNodeId, |
| 2559 | rootNodeId: input.turnInput.rootNodeId, |
| 2560 | subagent: null, |
| 2561 | startedAt: input.startedAt, |
| 2562 | itemPositions: new Map(), |
| 2563 | fileChangeKindsByItem: new Map(), |
| 2564 | messagePhases: new Map(), |
| 2565 | runningCompactionItemIds: new Set(), |
| 2566 | runningWebSearchItems: new Map(), |
| 2567 | }; |
| 2568 | const nativeThreadId = input.turnInput.providerThread.nativeThreadRef?.nativeId; |
| 2569 | const continuation = |
| 2570 | nativeThreadId == null ? undefined : capacityContinuations.get(nativeThreadId); |
| 2571 | if (continuation !== undefined) { |
| 2572 | context.capacityRetryAttempt = continuation.context.capacityRetryAttempt ?? 0; |
| 2573 | yield* Ref.update(providerRetries, (current) => |
| 2574 | new Map(current).set(providerTurnId, continuation.retry), |
| 2575 | ); |
| 2576 | const turns = continuedRuns.get(continuation.context.providerTurnId) ?? [ |
| 2577 | continuation.context, |
| 2578 | ]; |
| 2579 | turns.push(context); |
| 2580 | continuedRuns.set(continuation.context.providerTurnId, turns); |
| 2581 | continuedRuns.set(providerTurnId, turns); |
| 2582 | if (continuation.context.capacityRetryPending !== undefined) { |
| 2583 | yield* Deferred.succeed(continuation.context.capacityRetryPending, context); |
| 2584 | } |
| 2585 | } |
| 2586 | yield* Ref.update(limitedTurnItems, (current) => { |
| 2587 | const next = new Map(current); |
| 2588 | next.delete(context.providerThread.id); |
| 2589 | return next; |
| 2590 | }); |
| 2591 | beginTurnTokenUsage(context); |
| 2592 | endSessionApprovalsOnModeChange(context); |
| 2593 | yield* Ref.update(activeTurns, (current) => { |
| 2594 | const updated = new Map(current); |
| 2595 | updated.set(input.nativeTurnId, context); |
| 2596 | return updated; |
| 2597 | }); |
| 2598 | if (continuation !== undefined && nativeThreadId != null) { |
| 2599 | capacityContinuations.delete(nativeThreadId); |
| 2600 | } |
| 2601 | yield* emitProviderEvent({ |
| 2602 | type: "provider_turn.updated", |
| 2603 | driver: CODEX_PROVIDER, |
| 2604 | threadId: input.turnInput.threadId, |
| 2605 | providerTurn: { |
| 2606 | id: providerTurnId, |
| 2607 | providerThreadId: input.turnInput.providerThread.id, |
| 2608 | nodeId: input.turnInput.rootNodeId, |
| 2609 | runAttemptId: input.turnInput.attemptId, |
| 2610 | nativeTurnRef: { |
| 2611 | driver: CODEX_PROVIDER, |
| 2612 | nativeId: input.nativeTurnId, |
| 2613 | strength: "strong", |
| 2614 | }, |
| 2615 | ordinal: input.turnInput.providerTurnOrdinal, |
| 2616 | status: "running", |
| 2617 | startedAt: input.startedAt, |
| 2618 | completedAt: null, |
| 2619 | }, |
| 2620 | }); |
| 2621 | yield* rememberRootProviderThread(input.turnInput.providerThread); |
| 2622 | yield* emitMcpStartupFailures(context); |
| 2623 | return context; |
| 2624 | }); |
| 2625 | |
| 2626 | const findActiveTurnByNativeThreadId = |
| 2627 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2628 | Effect.fnUntraced(function* (nativeThreadId: string) { |
| 2629 | const turns = Array.from((yield* Ref.get(activeTurns)).values()); |
| 2630 | return turns.find( |
| 2631 | (context) => context.providerThread.nativeThreadRef?.nativeId === nativeThreadId, |
| 2632 | ); |
| 2633 | }); |
| 2634 | |
| 2635 | // Native events can arrive before their turn registers, so lookups retry briefly. |
| 2636 | const awaitRegisteredTurn = Effect.fnUntraced(function* ( |
| 2637 | lookup: Effect.Effect<ActiveCodexTurnContext | undefined>, |
| 2638 | attemptsRemaining = 1_000, |
| 2639 | ): Effect.fn.Return<ActiveCodexTurnContext | undefined> { |
| 2640 | const context = yield* lookup; |
| 2641 | if (context !== undefined || attemptsRemaining <= 0) { |
| 2642 | return context; |
| 2643 | } |
| 2644 | yield* Effect.yieldNow; |
| 2645 | return yield* awaitRegisteredTurn(lookup, attemptsRemaining - 1); |
| 2646 | }); |
| 2647 | |
| 2648 | // Streaming updates repeatedly await this context; avoid a span for each update. |
| 2649 | const awaitActiveTurn = (nativeTurnId: string) => |
| 2650 | awaitRegisteredTurn( |
| 2651 | Ref.get(activeTurns).pipe(Effect.map((turns) => turns.get(nativeTurnId))), |
| 2652 | ); |
| 2653 | |
| 2654 | const resolveItemEventContext = |
| 2655 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2656 | Effect.fnUntraced(function* (nativeTurnId: string) { |
| 2657 | const settled = (yield* Ref.get(settledTurns)).get(nativeTurnId); |
| 2658 | if (settled !== undefined) { |
| 2659 | return { context: settled, settled: true } as const; |
| 2660 | } |
| 2661 | const context = yield* awaitActiveTurn(nativeTurnId); |
| 2662 | return context === undefined ? undefined : ({ context, settled: false } as const); |
| 2663 | }); |
| 2664 | |
| 2665 | const trackRunningCommandItem = (nativeTurnId: string, item: TrackedRunningCommandItem) => |
| 2666 | Ref.update(runningCommandItemsByTurn, (current) => { |
| 2667 | const updated = new Map(current); |
| 2668 | const items = new Map(updated.get(nativeTurnId) ?? []); |
| 2669 | items.set(item.id, item); |
| 2670 | updated.set(nativeTurnId, items); |
| 2671 | return updated; |
| 2672 | }); |
| 2673 | |
| 2674 | const clearRunningCommandItem = (nativeTurnId: string, nativeItemId: string) => |
| 2675 | Ref.modify(runningCommandItemsByTurn, (current) => { |
| 2676 | const items = current.get(nativeTurnId); |
| 2677 | if (items === undefined || !items.has(nativeItemId)) { |
| 2678 | return [items === undefined || items.size === 0, current] as const; |
| 2679 | } |
| 2680 | const remaining = new Map(items); |
| 2681 | remaining.delete(nativeItemId); |
| 2682 | const updated = new Map(current); |
| 2683 | if (remaining.size === 0) { |
| 2684 | updated.delete(nativeTurnId); |
| 2685 | } else { |
| 2686 | updated.set(nativeTurnId, remaining); |
| 2687 | } |
| 2688 | return [remaining.size === 0, updated] as const; |
| 2689 | }); |
| 2690 | |
| 2691 | interface PendingMcpAppCapture { |
| 2692 | readonly item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>; |
| 2693 | readonly fiber: Fiber.Fiber<void>; |
| 2694 | } |
| 2695 | const pendingMcpAppCaptures = yield* Ref.make( |
| 2696 | new Map<string, ReadonlyMap<string, PendingMcpAppCapture>>(), |
| 2697 | ); |
| 2698 | const takePendingMcpAppCapture = (nativeTurnId: string, nativeItemId: string) => |
| 2699 | Ref.modify(pendingMcpAppCaptures, (current) => { |
| 2700 | const captures = current.get(nativeTurnId); |
| 2701 | if (captures === undefined || !captures.has(nativeItemId)) { |
| 2702 | return [false, current] as const; |
| 2703 | } |
| 2704 | const remaining = new Map(captures); |
| 2705 | remaining.delete(nativeItemId); |
| 2706 | const updated = new Map(current); |
| 2707 | if (remaining.size === 0) updated.delete(nativeTurnId); |
| 2708 | else updated.set(nativeTurnId, remaining); |
| 2709 | return [true, updated] as const; |
| 2710 | }); |
| 2711 | |
| 2712 | const trackRunningDynamicTool = (nativeTurnId: string, item: CodexDynamicToolItem) => |
| 2713 | Ref.update(runningDynamicToolsByTurn, (current) => { |
| 2714 | const updated = new Map(current); |
| 2715 | const items = new Map(updated.get(nativeTurnId) ?? []); |
| 2716 | items.set(item.id, item); |
| 2717 | updated.set(nativeTurnId, items); |
| 2718 | return updated; |
| 2719 | }); |
| 2720 | |
| 2721 | const clearRunningDynamicTool = (nativeTurnId: string, nativeItemId: string) => |
| 2722 | Ref.update(runningDynamicToolsByTurn, (current) => { |
| 2723 | const items = current.get(nativeTurnId); |
| 2724 | if (items === undefined || !items.has(nativeItemId)) { |
| 2725 | return current; |
| 2726 | } |
| 2727 | const remaining = new Map(items); |
| 2728 | remaining.delete(nativeItemId); |
| 2729 | const updated = new Map(current); |
| 2730 | if (remaining.size === 0) { |
| 2731 | updated.delete(nativeTurnId); |
| 2732 | } else { |
| 2733 | updated.set(nativeTurnId, remaining); |
| 2734 | } |
| 2735 | return updated; |
| 2736 | }); |
| 2737 | |
| 2738 | const turnHasRetainedBackgroundWork = |
| 2739 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2740 | Effect.fnUntraced(function* (nativeTurnId: string) { |
| 2741 | const commands = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId); |
| 2742 | if (commands !== undefined && commands.size > 0) { |
| 2743 | return true; |
| 2744 | } |
| 2745 | if ((yield* Ref.get(pendingMcpAppCaptures)).has(nativeTurnId)) { |
| 2746 | return true; |
| 2747 | } |
| 2748 | const images = imageTurns.get(nativeTurnId); |
| 2749 | if (images !== undefined && (images.running.size > 0 || images.saved.size > 0)) { |
| 2750 | return true; |
| 2751 | } |
| 2752 | const tools = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId); |
| 2753 | if (tools === undefined) { |
| 2754 | return false; |
| 2755 | } |
| 2756 | for (const item of tools.values()) { |
| 2757 | if (isPersistentCodexDynamicTool(item)) { |
| 2758 | return true; |
| 2759 | } |
| 2760 | } |
| 2761 | return false; |
| 2762 | }); |
| 2763 | |
| 2764 | const releaseSettledTurnIfIdle = |
| 2765 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2766 | Effect.fnUntraced(function* (nativeTurnId: string) { |
| 2767 | if (yield* turnHasRetainedBackgroundWork(nativeTurnId)) { |
| 2768 | return; |
| 2769 | } |
| 2770 | yield* Ref.update(settledTurns, (current) => { |
| 2771 | if (!current.has(nativeTurnId)) { |
| 2772 | return current; |
| 2773 | } |
| 2774 | const updated = new Map(current); |
| 2775 | updated.delete(nativeTurnId); |
| 2776 | return updated; |
| 2777 | }); |
| 2778 | yield* Ref.update(offeredContinuationItemsByTurn, (current) => { |
| 2779 | if (!current.has(nativeTurnId)) { |
| 2780 | return current; |
| 2781 | } |
| 2782 | const updated = new Map(current); |
| 2783 | updated.delete(nativeTurnId); |
| 2784 | return updated; |
| 2785 | }); |
| 2786 | yield* Ref.update(completedFinalAnswerTextsByTurn, (current) => { |
| 2787 | if (!current.has(nativeTurnId)) { |
| 2788 | return current; |
| 2789 | } |
| 2790 | const updated = new Map(current); |
| 2791 | updated.delete(nativeTurnId); |
| 2792 | return updated; |
| 2793 | }); |
| 2794 | imageTurns.delete(nativeTurnId); |
| 2795 | yield* Ref.update(finalAnswerItemIdsByTurn, (current) => { |
| 2796 | if (!current.has(nativeTurnId)) { |
| 2797 | return current; |
| 2798 | } |
| 2799 | const updated = new Map(current); |
| 2800 | updated.delete(nativeTurnId); |
| 2801 | return updated; |
| 2802 | }); |
| 2803 | }); |
| 2804 | |
| 2805 | /** |
| 2806 | * When a turn is interrupted or failed, Codex often leaves commandExecution |
| 2807 | * items mid-flight (no item/completed). Emit terminal turn items before |
| 2808 | * turn.terminal so the projection never keeps a forever-running command card. |
| 2809 | */ |
| 2810 | const terminalizeRunningCommandItems = Effect.fn( |
| 2811 | "CodexAdapterV2.terminalizeRunningCommandItems", |
| 2812 | )(function* ( |
| 2813 | context: ActiveCodexTurnContext, |
| 2814 | nativeTurnId: string, |
| 2815 | status: "interrupted" | "failed", |
| 2816 | completedAt: DateTime.Utc, |
| 2817 | ) { |
| 2818 | const items = (yield* Ref.get(runningCommandItemsByTurn)).get(nativeTurnId); |
| 2819 | if (items === undefined || items.size === 0) { |
| 2820 | return; |
| 2821 | } |
| 2822 | for (const tracked of items.values()) { |
| 2823 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 2824 | driver: CODEX_PROVIDER, |
| 2825 | nativeItemId: tracked.id, |
| 2826 | }); |
| 2827 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 2828 | driver: CODEX_PROVIDER, |
| 2829 | nativeItemId: tracked.id, |
| 2830 | }); |
| 2831 | const { ordinal, startedAt } = yield* resolveItemPosition(context, tracked.id); |
| 2832 | const node: OrchestrationV2ExecutionNode = { |
| 2833 | id: nodeId, |
| 2834 | threadId: context.projectionThreadId, |
| 2835 | runId: context.projectionRunId, |
| 2836 | parentNodeId: context.itemParentNodeId, |
| 2837 | rootNodeId: context.rootNodeId, |
| 2838 | kind: "tool_call", |
| 2839 | status, |
| 2840 | countsForRun: false, |
| 2841 | providerThreadId: context.providerThread.id, |
| 2842 | providerTurnId: context.providerTurnId, |
| 2843 | nativeItemRef: codexNativeItemRef(tracked.id), |
| 2844 | runtimeRequestId: null, |
| 2845 | checkpointScopeId: null, |
| 2846 | startedAt, |
| 2847 | completedAt, |
| 2848 | }; |
| 2849 | const turnItem: OrchestrationV2TurnItem = { |
| 2850 | id: turnItemId, |
| 2851 | threadId: context.projectionThreadId, |
| 2852 | runId: context.projectionRunId, |
| 2853 | nodeId, |
| 2854 | providerThreadId: context.providerThread.id, |
| 2855 | providerTurnId: context.providerTurnId, |
| 2856 | nativeItemRef: codexNativeItemRef(tracked.id), |
| 2857 | parentItemId: null, |
| 2858 | ordinal, |
| 2859 | status, |
| 2860 | title: null, |
| 2861 | startedAt, |
| 2862 | completedAt, |
| 2863 | updatedAt: completedAt, |
| 2864 | type: "command_execution", |
| 2865 | input: tracked.command, |
| 2866 | ...(tracked.aggregatedOutput === undefined |
| 2867 | ? {} |
| 2868 | : { output: tracked.aggregatedOutput }), |
| 2869 | }; |
| 2870 | yield* emitProviderEvent({ |
| 2871 | type: "node.updated", |
| 2872 | driver: CODEX_PROVIDER, |
| 2873 | node, |
| 2874 | }); |
| 2875 | yield* emitProviderEvent({ |
| 2876 | type: "turn_item.updated", |
| 2877 | driver: CODEX_PROVIDER, |
| 2878 | turnItem, |
| 2879 | }); |
| 2880 | } |
| 2881 | }); |
| 2882 | |
| 2883 | const terminateBackgroundTerminal = Effect.fn("CodexAdapterV2.terminateBackgroundTerminal")( |
| 2884 | function* (nativeThreadId: string, processId: string) { |
| 2885 | const response = yield* client.raw |
| 2886 | .request("thread/backgroundTerminals/terminate", { |
| 2887 | threadId: nativeThreadId, |
| 2888 | processId, |
| 2889 | }) |
| 2890 | .pipe( |
| 2891 | Effect.catchTags({ |
| 2892 | CodexAppServerProcessExitedError: () => Effect.succeed({ terminated: true }), |
| 2893 | CodexAppServerInputStreamEndedError: () => Effect.succeed({ terminated: true }), |
| 2894 | // Unloading kills terminals, so "thread not found" means nothing remains to stop. |
| 2895 | CodexAppServerRequestError: (error) => |
| 2896 | isCodexThreadNotFoundError(error) |
| 2897 | ? Effect.succeed({ terminated: true }) |
| 2898 | : Effect.fail(error), |
| 2899 | }), |
| 2900 | ); |
| 2901 | const result = yield* decodeCodexBackgroundTerminalTerminateResponse(response); |
| 2902 | if (result.terminated) return; |
| 2903 | let cursor: string | null = null; |
| 2904 | while (true) { |
| 2905 | const response: unknown = yield* client.raw.request( |
| 2906 | "thread/backgroundTerminals/list", |
| 2907 | { |
| 2908 | threadId: nativeThreadId, |
| 2909 | ...(cursor === null ? {} : { cursor }), |
| 2910 | }, |
| 2911 | ); |
| 2912 | const page: CodexBackgroundTerminalsListPage = |
| 2913 | yield* decodeCodexBackgroundTerminalsListResponse(response); |
| 2914 | if (page.data.some((terminal) => terminal.processId === processId)) { |
| 2915 | return yield* toProtocolError( |
| 2916 | `Codex background terminal ${processId} remained active after termination.`, |
| 2917 | ); |
| 2918 | } |
| 2919 | if (page.nextCursor === null) return; |
| 2920 | cursor = page.nextCursor; |
| 2921 | } |
| 2922 | }, |
| 2923 | Effect.timeout("10 seconds"), |
| 2924 | ); |
| 2925 | |
| 2926 | /** |
| 2927 | * Yielded exec cells can start MCP / dynamic tools that never receive |
| 2928 | * item/completed when functions.wait terminates the cell. Persistent tools |
| 2929 | * can outlive the root turn and must stay running. |
| 2930 | */ |
| 2931 | const terminalizeRunningDynamicTools = Effect.fn( |
| 2932 | "CodexAdapterV2.terminalizeRunningDynamicTools", |
| 2933 | )(function* ( |
| 2934 | context: ActiveCodexTurnContext, |
| 2935 | nativeTurnId: string, |
| 2936 | status: "cancelled" | "interrupted" | "failed", |
| 2937 | completedAt: DateTime.Utc, |
| 2938 | includePersistent: boolean, |
| 2939 | ) { |
| 2940 | const items = (yield* Ref.get(runningDynamicToolsByTurn)).get(nativeTurnId); |
| 2941 | if (items === undefined || items.size === 0) { |
| 2942 | return; |
| 2943 | } |
| 2944 | for (const tracked of items.values()) { |
| 2945 | if (!includePersistent && isPersistentCodexDynamicTool(tracked)) { |
| 2946 | continue; |
| 2947 | } |
| 2948 | const artifacts = yield* buildDynamicToolArtifacts(context, tracked); |
| 2949 | yield* emitProviderEvent({ |
| 2950 | type: "node.updated", |
| 2951 | driver: CODEX_PROVIDER, |
| 2952 | node: { |
| 2953 | ...artifacts.node, |
| 2954 | status, |
| 2955 | completedAt, |
| 2956 | }, |
| 2957 | }); |
| 2958 | yield* emitProviderEvent({ |
| 2959 | type: "turn_item.updated", |
| 2960 | driver: CODEX_PROVIDER, |
| 2961 | turnItem: { |
| 2962 | ...artifacts.turnItem, |
| 2963 | status, |
| 2964 | completedAt, |
| 2965 | updatedAt: completedAt, |
| 2966 | }, |
| 2967 | }); |
| 2968 | } |
| 2969 | yield* Ref.update(runningDynamicToolsByTurn, (current) => { |
| 2970 | if (!current.has(nativeTurnId)) { |
| 2971 | return current; |
| 2972 | } |
| 2973 | const remaining = new Map(current.get(nativeTurnId) ?? []); |
| 2974 | for (const tracked of remaining.values()) { |
| 2975 | if (includePersistent || !isPersistentCodexDynamicTool(tracked)) { |
| 2976 | remaining.delete(tracked.id); |
| 2977 | } |
| 2978 | } |
| 2979 | const updated = new Map(current); |
| 2980 | if (remaining.size === 0) { |
| 2981 | updated.delete(nativeTurnId); |
| 2982 | } else { |
| 2983 | updated.set(nativeTurnId, remaining); |
| 2984 | } |
| 2985 | return updated; |
| 2986 | }); |
| 2987 | }); |
| 2988 | |
| 2989 | const resolveItemPosition = |
| 2990 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 2991 | Effect.fnUntraced(function* ( |
| 2992 | context: ActiveCodexTurnContext, |
| 2993 | nativeItemId: string, |
| 2994 | startedAt?: DateTime.Utc, |
| 2995 | ) { |
| 2996 | // Read the clock first so the lookup and the insert run without yielding. |
| 2997 | const now = startedAt ?? (yield* DateTime.now); |
| 2998 | const existing = context.itemPositions.get(nativeItemId); |
| 2999 | if (existing !== undefined) { |
| 3000 | return existing; |
| 3001 | } |
| 3002 | const position = { |
| 3003 | ordinal: context.providerTurnOrdinal * 100 + context.itemPositions.size + 1, |
| 3004 | startedAt: now, |
| 3005 | }; |
| 3006 | context.itemPositions.set(nativeItemId, position); |
| 3007 | return position; |
| 3008 | }); |
| 3009 | |
| 3010 | const resolveItemOrdinal = (context: ActiveCodexTurnContext, nativeItemId: string) => |
| 3011 | resolveItemPosition(context, nativeItemId).pipe( |
| 3012 | Effect.map((position) => position.ordinal), |
| 3013 | ); |
| 3014 | |
| 3015 | const nextProviderTurnOrdinal = ( |
| 3016 | providerThreadId: OrchestrationV2ProviderThread["id"], |
| 3017 | minimum: number, |
| 3018 | ) => |
| 3019 | Ref.modify(nextProviderTurnOrdinals, (current) => { |
| 3020 | const previous = current.get(String(providerThreadId)); |
| 3021 | const next = previous === undefined ? minimum : Math.max(previous + 1, minimum); |
| 3022 | const updated = new Map(current); |
| 3023 | updated.set(String(providerThreadId), next); |
| 3024 | return [next, updated]; |
| 3025 | }); |
| 3026 | |
| 3027 | const emitSubagentTaskUpdate = |
| 3028 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3029 | Effect.fnUntraced(function* (input: { |
| 3030 | readonly subagent: CodexSubagentThreadContext; |
| 3031 | readonly status: OrchestrationV2Subagent["status"]; |
| 3032 | readonly result?: string | null; |
| 3033 | readonly completedAt?: DateTime.Utc | null; |
| 3034 | readonly startedAt?: DateTime.Utc; |
| 3035 | readonly reopen?: boolean; |
| 3036 | readonly progress?: string; |
| 3037 | }) { |
| 3038 | const now = yield* DateTime.now; |
| 3039 | const prior = input.reopen |
| 3040 | ? (({ progress: _staleProgress, ...rest }) => rest)(input.subagent.task) |
| 3041 | : input.subagent.task; |
| 3042 | const settled = !isOrchestrationV2WorkActive(prior.status); |
| 3043 | // Late snapshots must not reopen completed children; only new turns may. |
| 3044 | if (settled && isOrchestrationV2WorkActive(input.status) && !input.reopen) return; |
| 3045 | const status = settled && !input.reopen ? prior.status : input.status; |
| 3046 | const completedAt = isOrchestrationV2WorkActive(status) |
| 3047 | ? null |
| 3048 | : (prior.completedAt ?? input.completedAt ?? now); |
| 3049 | const task = { |
| 3050 | ...prior, |
| 3051 | status, |
| 3052 | ...(input.reopen |
| 3053 | ? { |
| 3054 | runId: input.subagent.parentContext.projectionRunId, |
| 3055 | parentNodeId: input.subagent.parentContext.itemParentNodeId, |
| 3056 | } |
| 3057 | : {}), |
| 3058 | startedAt: input.startedAt ?? prior.startedAt, |
| 3059 | ...(input.progress === undefined ? {} : { progress: input.progress }), |
| 3060 | result: input.result === undefined ? input.subagent.task.result : input.result, |
| 3061 | completedAt, |
| 3062 | updatedAt: now, |
| 3063 | } satisfies OrchestrationV2Subagent; |
| 3064 | input.subagent.task = task; |
| 3065 | if (input.startedAt !== undefined) input.subagent.startedAt = input.startedAt; |
| 3066 | |
| 3067 | yield* emitProviderEvent({ |
| 3068 | type: "subagent.updated", |
| 3069 | driver: CODEX_PROVIDER, |
| 3070 | subagent: task, |
| 3071 | }); |
| 3072 | yield* emitProviderEvent({ |
| 3073 | type: "turn_item.updated", |
| 3074 | driver: CODEX_PROVIDER, |
| 3075 | turnItem: { |
| 3076 | id: input.subagent.turnItemId, |
| 3077 | threadId: task.threadId, |
| 3078 | runId: task.runId, |
| 3079 | nodeId: task.id, |
| 3080 | providerThreadId: task.providerThreadId, |
| 3081 | providerTurnId: input.subagent.parentContext.providerTurnId, |
| 3082 | nativeItemRef: task.nativeTaskRef, |
| 3083 | parentItemId: null, |
| 3084 | ordinal: input.subagent.turnItemOrdinal, |
| 3085 | status: task.status, |
| 3086 | title: task.title, |
| 3087 | startedAt: task.startedAt, |
| 3088 | completedAt: task.completedAt, |
| 3089 | updatedAt: task.updatedAt, |
| 3090 | type: "subagent", |
| 3091 | subagentId: task.id, |
| 3092 | origin: task.origin, |
| 3093 | driver: task.driver, |
| 3094 | providerInstanceId: task.providerInstanceId, |
| 3095 | childThreadId: task.childThreadId, |
| 3096 | prompt: task.prompt, |
| 3097 | ...(task.progress === undefined ? {} : { progress: task.progress }), |
| 3098 | result: task.result, |
| 3099 | }, |
| 3100 | }); |
| 3101 | }); |
| 3102 | |
| 3103 | // A native child's running item is the line its parent's subagent row shows. |
| 3104 | const reportSubagentProgress = |
| 3105 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3106 | Effect.fnUntraced(function* (context: ActiveCodexTurnContext, progress: string | null) { |
| 3107 | const subagent = context.subagent; |
| 3108 | const line = progress?.trim(); |
| 3109 | if (subagent === null || !line) return; |
| 3110 | if (!isOrchestrationV2WorkActive(subagent.task.status)) return; |
| 3111 | if (subagent.task.progress === line) return; |
| 3112 | yield* emitSubagentTaskUpdate({ |
| 3113 | subagent, |
| 3114 | status: subagent.task.status, |
| 3115 | progress: line, |
| 3116 | }); |
| 3117 | }); |
| 3118 | |
| 3119 | const emitSubagentProviderTurnStarted = |
| 3120 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3121 | Effect.fnUntraced(function* ( |
| 3122 | subagent: CodexSubagentThreadContext, |
| 3123 | turn: PendingCodexSubagentTurnStarted, |
| 3124 | ) { |
| 3125 | if (subagent.nativeTurnIds.has(turn.nativeTurnId)) return; |
| 3126 | subagent.nativeTurnIds.add(turn.nativeTurnId); |
| 3127 | const parentNativeThreadId = yield* getNativeThreadId( |
| 3128 | subagent.parentContext.providerThread, |
| 3129 | ); |
| 3130 | const currentParent = yield* findActiveTurnByNativeThreadId(parentNativeThreadId); |
| 3131 | if (currentParent !== undefined) subagent.parentContext = currentParent; |
| 3132 | const terminalizedNativeTurns = yield* Ref.get(terminalizedNonCompletedNativeTurns); |
| 3133 | let ancestor: ActiveCodexTurnContext | undefined = subagent.parentContext; |
| 3134 | while (ancestor !== undefined) { |
| 3135 | if (terminalizedNativeTurns.has(ancestor.nativeTurnId)) { |
| 3136 | const nativeThreadId = yield* getNativeThreadId(subagent.providerThread); |
| 3137 | // Fork requests off the notification reader so it can read their responses. |
| 3138 | yield* client |
| 3139 | .request("turn/interrupt", { |
| 3140 | threadId: nativeThreadId, |
| 3141 | turnId: turn.nativeTurnId, |
| 3142 | }) |
| 3143 | .pipe( |
| 3144 | Effect.catch((cause) => |
| 3145 | Effect.logWarning("orchestration-v2.codex-late-subagent-interrupt-failed", { |
| 3146 | nativeThreadId, |
| 3147 | nativeTurnId: turn.nativeTurnId, |
| 3148 | cause, |
| 3149 | }), |
| 3150 | ), |
| 3151 | Effect.timeoutOrElse({ |
| 3152 | duration: "10 seconds", |
| 3153 | orElse: () => |
| 3154 | Effect.logWarning( |
| 3155 | "orchestration-v2.codex-late-subagent-interrupt-timeout", |
| 3156 | { |
| 3157 | nativeThreadId, |
| 3158 | nativeTurnId: turn.nativeTurnId, |
| 3159 | }, |
| 3160 | ), |
| 3161 | }), |
| 3162 | Effect.forkIn(scope), |
| 3163 | ); |
| 3164 | return; |
| 3165 | } |
| 3166 | ancestor = ancestor.subagent?.parentContext; |
| 3167 | } |
| 3168 | const providerTurnId = idAllocator.derive.providerTurn({ |
| 3169 | driver: CODEX_PROVIDER, |
| 3170 | nativeTurnId: turn.nativeTurnId, |
| 3171 | }); |
| 3172 | const providerTurnOrdinal = yield* nextProviderTurnOrdinal( |
| 3173 | subagent.providerThread.id, |
| 3174 | 1, |
| 3175 | ); |
| 3176 | const providerNodeId = |
| 3177 | providerTurnOrdinal === 1 |
| 3178 | ? subagent.childRootNodeId |
| 3179 | : idAllocator.derive.nodeFromProviderItem({ |
| 3180 | driver: CODEX_PROVIDER, |
| 3181 | nativeItemId: `${turn.nativeTurnId}:thread-root`, |
| 3182 | }); |
| 3183 | const activeContext: ActiveCodexTurnContext = { |
| 3184 | input: subagent.parentContext.input, |
| 3185 | projectionAppThread: subagent.childThread, |
| 3186 | projectionThreadId: subagent.childThreadId, |
| 3187 | projectionRunId: null, |
| 3188 | nativeTurnId: turn.nativeTurnId, |
| 3189 | providerThread: subagent.providerThread, |
| 3190 | providerTurnId, |
| 3191 | providerTurnOrdinal, |
| 3192 | providerNodeId, |
| 3193 | providerNodeStartedAt: turn.startedAt, |
| 3194 | itemParentNodeId: providerNodeId, |
| 3195 | rootNodeId: providerNodeId, |
| 3196 | subagent, |
| 3197 | startedAt: turn.startedAt, |
| 3198 | itemPositions: new Map(), |
| 3199 | fileChangeKindsByItem: new Map(), |
| 3200 | messagePhases: new Map(), |
| 3201 | runningCompactionItemIds: new Set(), |
| 3202 | runningWebSearchItems: new Map(), |
| 3203 | }; |
| 3204 | beginTurnTokenUsage(activeContext); |
| 3205 | endSessionApprovalsOnModeChange(activeContext); |
| 3206 | yield* Ref.update(activeTurns, (current) => { |
| 3207 | const updated = new Map(current); |
| 3208 | updated.set(turn.nativeTurnId, activeContext); |
| 3209 | return updated; |
| 3210 | }); |
| 3211 | yield* emitSubagentTaskUpdate({ |
| 3212 | subagent, |
| 3213 | status: "running", |
| 3214 | startedAt: turn.startedAt, |
| 3215 | ...(providerTurnOrdinal > 1 ? { reopen: true, result: null } : {}), |
| 3216 | }); |
| 3217 | const now = yield* DateTime.now; |
| 3218 | yield* emitProviderEvent({ |
| 3219 | type: "provider_thread.updated", |
| 3220 | driver: CODEX_PROVIDER, |
| 3221 | providerThread: { |
| 3222 | ...subagent.providerThread, |
| 3223 | status: "active", |
| 3224 | updatedAt: now, |
| 3225 | }, |
| 3226 | }); |
| 3227 | yield* emitProviderEvent({ |
| 3228 | type: "provider_turn.updated", |
| 3229 | driver: CODEX_PROVIDER, |
| 3230 | threadId: subagent.childThreadId, |
| 3231 | providerTurn: { |
| 3232 | id: providerTurnId, |
| 3233 | providerThreadId: subagent.providerThread.id, |
| 3234 | nodeId: providerNodeId, |
| 3235 | runAttemptId: null, |
| 3236 | nativeTurnRef: { |
| 3237 | driver: CODEX_PROVIDER, |
| 3238 | nativeId: turn.nativeTurnId, |
| 3239 | strength: "strong", |
| 3240 | }, |
| 3241 | ordinal: activeContext.providerTurnOrdinal, |
| 3242 | status: "running", |
| 3243 | startedAt: turn.startedAt, |
| 3244 | completedAt: null, |
| 3245 | }, |
| 3246 | }); |
| 3247 | yield* emitProviderEvent({ |
| 3248 | type: "node.updated", |
| 3249 | driver: CODEX_PROVIDER, |
| 3250 | node: { |
| 3251 | id: providerNodeId, |
| 3252 | threadId: subagent.childThreadId, |
| 3253 | runId: null, |
| 3254 | parentNodeId: null, |
| 3255 | rootNodeId: providerNodeId, |
| 3256 | kind: "root_turn", |
| 3257 | status: "running", |
| 3258 | countsForRun: false, |
| 3259 | providerThreadId: subagent.providerThread.id, |
| 3260 | providerTurnId, |
| 3261 | nativeItemRef: subagent.task.nativeTaskRef, |
| 3262 | runtimeRequestId: null, |
| 3263 | checkpointScopeId: null, |
| 3264 | startedAt: turn.startedAt, |
| 3265 | completedAt: null, |
| 3266 | }, |
| 3267 | }); |
| 3268 | }); |
| 3269 | |
| 3270 | const rememberSubagentTurnStarted = |
| 3271 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3272 | Effect.fnUntraced(function* (input: { |
| 3273 | readonly nativeThreadId: string; |
| 3274 | readonly nativeTurnId: string; |
| 3275 | readonly startedAt: DateTime.Utc; |
| 3276 | }) { |
| 3277 | const subagent = (yield* Ref.get(subagentThreads)).get(input.nativeThreadId); |
| 3278 | if (subagent !== undefined) { |
| 3279 | yield* emitSubagentProviderTurnStarted(subagent, input); |
| 3280 | return; |
| 3281 | } |
| 3282 | yield* Ref.update(pendingSubagentTurns, (current) => { |
| 3283 | const updated = new Map(current); |
| 3284 | updated.set(input.nativeThreadId, [ |
| 3285 | ...(updated.get(input.nativeThreadId) ?? []), |
| 3286 | { nativeTurnId: input.nativeTurnId, startedAt: input.startedAt }, |
| 3287 | ]); |
| 3288 | return updated; |
| 3289 | }); |
| 3290 | }); |
| 3291 | |
| 3292 | const updateSubagentSelection = Effect.fnUntraced(function* ( |
| 3293 | nativeThreadId: string, |
| 3294 | value: string | null, |
| 3295 | effort?: string | null, |
| 3296 | tier?: string | null, |
| 3297 | ) { |
| 3298 | const model = value?.trim(); |
| 3299 | if (!model) return; |
| 3300 | const previous = subagentSelections.get(nativeThreadId); |
| 3301 | const previousOptions = previous?.options; |
| 3302 | const options = |
| 3303 | effort === undefined && tier === undefined |
| 3304 | ? previousOptions |
| 3305 | : [ |
| 3306 | ...(previousOptions ?? []).filter(({ id }) => |
| 3307 | id === "reasoningEffort" |
| 3308 | ? effort === undefined |
| 3309 | : id === "serviceTier" && tier === undefined, |
| 3310 | ), |
| 3311 | ...[ |
| 3312 | { id: "reasoningEffort", value: effort }, |
| 3313 | { id: "serviceTier", value: tier }, |
| 3314 | ].flatMap(({ id, value }) => |
| 3315 | value?.trim() ? [{ id, value: value.trim() }] : [], |
| 3316 | ), |
| 3317 | ]; |
| 3318 | const selection = { |
| 3319 | model, |
| 3320 | ...(options === undefined ? {} : { options }), |
| 3321 | }; |
| 3322 | subagentSelections.set(nativeThreadId, selection); |
| 3323 | const subagent = (yield* Ref.get(subagentThreads)).get(nativeThreadId); |
| 3324 | if (subagent === undefined) return; |
| 3325 | const modelSelection = { instanceId: subagent.task.providerInstanceId, ...selection }; |
| 3326 | if ( |
| 3327 | subagent.task.modelSelection && |
| 3328 | modelSelectionsEqual(subagent.task.modelSelection, modelSelection) |
| 3329 | ) |
| 3330 | return; |
| 3331 | subagent.task = { |
| 3332 | ...subagent.task, |
| 3333 | model, |
| 3334 | modelSelection, |
| 3335 | updatedAt: yield* DateTime.now, |
| 3336 | }; |
| 3337 | yield* emitProviderEvent({ |
| 3338 | type: "subagent.updated", |
| 3339 | driver: CODEX_PROVIDER, |
| 3340 | subagent: subagent.task, |
| 3341 | }); |
| 3342 | }); |
| 3343 | |
| 3344 | const registerSubagentThread = |
| 3345 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3346 | Effect.fnUntraced(function* (input: { |
| 3347 | readonly context: ActiveCodexTurnContext; |
| 3348 | readonly nativeThreadId: string; |
| 3349 | readonly nativeItemId: string; |
| 3350 | readonly nativeToolCallId: string; |
| 3351 | readonly prompt: string; |
| 3352 | readonly title: string | null; |
| 3353 | readonly model: string | null; |
| 3354 | readonly reasoningEffort?: string | null | undefined; |
| 3355 | readonly ordinal: number; |
| 3356 | readonly emitInitialPrompt: boolean; |
| 3357 | }) { |
| 3358 | const registeredSubagents = yield* Ref.get(subagentThreads); |
| 3359 | if (input.model && !subagentSelections.has(input.nativeThreadId)) { |
| 3360 | yield* updateSubagentSelection( |
| 3361 | input.nativeThreadId, |
| 3362 | input.model, |
| 3363 | input.reasoningEffort, |
| 3364 | ); |
| 3365 | } |
| 3366 | if (registeredSubagents.has(input.nativeThreadId)) { |
| 3367 | return; |
| 3368 | } |
| 3369 | |
| 3370 | const now = yield* DateTime.now; |
| 3371 | const subagentNodeId = idAllocator.derive.nodeFromProviderItem({ |
| 3372 | driver: CODEX_PROVIDER, |
| 3373 | nativeItemId: input.nativeItemId, |
| 3374 | }); |
| 3375 | const childRootNodeId = idAllocator.derive.nodeFromProviderItem({ |
| 3376 | driver: CODEX_PROVIDER, |
| 3377 | nativeItemId: `${input.nativeItemId}:thread-root`, |
| 3378 | }); |
| 3379 | const childThreadId = idAllocator.derive.subagentThread({ |
| 3380 | driver: CODEX_PROVIDER, |
| 3381 | nativeThreadId: input.nativeThreadId, |
| 3382 | }); |
| 3383 | const turnItemOrdinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); |
| 3384 | const providerThread = { |
| 3385 | id: idAllocator.derive.providerThread({ |
| 3386 | driver: CODEX_PROVIDER, |
| 3387 | nativeThreadId: input.nativeThreadId, |
| 3388 | }), |
| 3389 | driver: CODEX_PROVIDER, |
| 3390 | providerInstanceId: input.context.input.modelSelection.instanceId, |
| 3391 | providerSessionId: input.context.providerThread.providerSessionId, |
| 3392 | appThreadId: childThreadId, |
| 3393 | ownerNodeId: null, |
| 3394 | nativeThreadRef: { |
| 3395 | driver: CODEX_PROVIDER, |
| 3396 | nativeId: input.nativeThreadId, |
| 3397 | strength: "strong" as const, |
| 3398 | }, |
| 3399 | nativeConversationHeadRef: null, |
| 3400 | status: "idle" as const, |
| 3401 | firstRunOrdinal: null, |
| 3402 | lastRunOrdinal: null, |
| 3403 | handoffIds: [], |
| 3404 | forkedFrom: { |
| 3405 | providerThreadId: input.context.providerThread.id, |
| 3406 | providerTurnId: input.context.providerTurnId, |
| 3407 | }, |
| 3408 | createdAt: now, |
| 3409 | updatedAt: now, |
| 3410 | } satisfies OrchestrationV2ProviderThread; |
| 3411 | const reportedSelection = subagentSelections.get(input.nativeThreadId); |
| 3412 | const task = { |
| 3413 | id: subagentNodeId, |
| 3414 | threadId: input.context.projectionThreadId, |
| 3415 | runId: input.context.projectionRunId, |
| 3416 | parentNodeId: input.context.itemParentNodeId, |
| 3417 | origin: "provider_native", |
| 3418 | createdBy: "agent", |
| 3419 | driver: CODEX_PROVIDER, |
| 3420 | providerInstanceId: input.context.input.modelSelection.instanceId, |
| 3421 | providerThreadId: providerThread.id, |
| 3422 | childThreadId, |
| 3423 | nativeTaskRef: codexNativeItemRef(input.nativeItemId), |
| 3424 | prompt: input.prompt, |
| 3425 | title: input.title, |
| 3426 | model: reportedSelection?.model ?? input.model, |
| 3427 | modelSelection: reportedSelection |
| 3428 | ? { |
| 3429 | instanceId: input.context.input.modelSelection.instanceId, |
| 3430 | ...reportedSelection, |
| 3431 | } |
| 3432 | : undefined, |
| 3433 | status: "running", |
| 3434 | result: null, |
| 3435 | startedAt: now, |
| 3436 | completedAt: null, |
| 3437 | updatedAt: now, |
| 3438 | } satisfies OrchestrationV2Subagent; |
| 3439 | const childThread = makeSubagentChildThread({ |
| 3440 | parentThread: input.context.projectionAppThread, |
| 3441 | childThreadId, |
| 3442 | parentNodeId: subagentNodeId, |
| 3443 | activeProviderThreadId: providerThread.id, |
| 3444 | providerInstanceId: input.context.input.modelSelection.instanceId, |
| 3445 | // A child's effort can differ from the parent's. Until Codex reports it, show none. |
| 3446 | modelSelection: task.modelSelection ?? { |
| 3447 | ...input.context.input.modelSelection, |
| 3448 | model: task.model ?? input.context.input.modelSelection.model, |
| 3449 | options: (input.context.input.modelSelection.options ?? []).filter( |
| 3450 | ({ id }) => id !== "reasoningEffort", |
| 3451 | ), |
| 3452 | }, |
| 3453 | title: subagentThreadTitle({ |
| 3454 | parentTitle: input.context.projectionAppThread.title, |
| 3455 | prompt: task.prompt, |
| 3456 | title: task.title, |
| 3457 | ordinal: input.ordinal, |
| 3458 | }), |
| 3459 | now, |
| 3460 | createdBy: "agent", |
| 3461 | creationSource: "provider", |
| 3462 | }); |
| 3463 | const subagent = { |
| 3464 | parentContext: input.context, |
| 3465 | providerThread, |
| 3466 | childThread, |
| 3467 | subagentNodeId, |
| 3468 | childRootNodeId, |
| 3469 | childThreadId, |
| 3470 | nativeTurnIds: new Set<string>(), |
| 3471 | startedAt: now, |
| 3472 | turnItemId: idAllocator.derive.turnItemFromProviderItem({ |
| 3473 | driver: CODEX_PROVIDER, |
| 3474 | nativeItemId: input.nativeItemId, |
| 3475 | }), |
| 3476 | turnItemOrdinal, |
| 3477 | task, |
| 3478 | } satisfies CodexSubagentThreadContext; |
| 3479 | |
| 3480 | yield* Ref.update(subagentThreads, (current) => { |
| 3481 | const updated = new Map(current); |
| 3482 | updated.set(input.nativeThreadId, subagent); |
| 3483 | return updated; |
| 3484 | }); |
| 3485 | yield* emitProviderEvent({ |
| 3486 | type: "app_thread.created", |
| 3487 | driver: CODEX_PROVIDER, |
| 3488 | appThread: childThread, |
| 3489 | }); |
| 3490 | yield* emitProviderEvent({ |
| 3491 | type: "node.updated", |
| 3492 | driver: CODEX_PROVIDER, |
| 3493 | node: { |
| 3494 | id: subagentNodeId, |
| 3495 | threadId: input.context.projectionThreadId, |
| 3496 | runId: input.context.projectionRunId, |
| 3497 | parentNodeId: input.context.itemParentNodeId, |
| 3498 | rootNodeId: input.context.rootNodeId, |
| 3499 | kind: "subagent", |
| 3500 | status: "running", |
| 3501 | countsForRun: false, |
| 3502 | providerThreadId: providerThread.id, |
| 3503 | providerTurnId: input.context.providerTurnId, |
| 3504 | nativeItemRef: codexNativeItemRef(input.nativeToolCallId), |
| 3505 | runtimeRequestId: null, |
| 3506 | checkpointScopeId: null, |
| 3507 | startedAt: now, |
| 3508 | completedAt: null, |
| 3509 | }, |
| 3510 | }); |
| 3511 | yield* emitProviderEvent({ |
| 3512 | type: "node.updated", |
| 3513 | driver: CODEX_PROVIDER, |
| 3514 | node: { |
| 3515 | id: childRootNodeId, |
| 3516 | threadId: childThreadId, |
| 3517 | runId: null, |
| 3518 | parentNodeId: null, |
| 3519 | rootNodeId: childRootNodeId, |
| 3520 | kind: "root_turn", |
| 3521 | status: "running", |
| 3522 | countsForRun: false, |
| 3523 | providerThreadId: providerThread.id, |
| 3524 | providerTurnId: null, |
| 3525 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 3526 | runtimeRequestId: null, |
| 3527 | checkpointScopeId: null, |
| 3528 | startedAt: now, |
| 3529 | completedAt: null, |
| 3530 | }, |
| 3531 | }); |
| 3532 | yield* emitProviderEvent({ |
| 3533 | type: "provider_thread.updated", |
| 3534 | driver: CODEX_PROVIDER, |
| 3535 | providerThread, |
| 3536 | }); |
| 3537 | if (input.emitInitialPrompt && input.prompt.length > 0) { |
| 3538 | const promptNativeItemId = `${input.nativeItemId}:prompt`; |
| 3539 | const promptArtifacts = makeSubagentConversationArtifacts({ |
| 3540 | senderThreadId: input.context.projectionThreadId, |
| 3541 | messageId: idAllocator.derive.messageFromProviderItem({ |
| 3542 | driver: CODEX_PROVIDER, |
| 3543 | nativeItemId: promptNativeItemId, |
| 3544 | }), |
| 3545 | turnItemId: idAllocator.derive.turnItemFromProviderItem({ |
| 3546 | driver: CODEX_PROVIDER, |
| 3547 | nativeItemId: promptNativeItemId, |
| 3548 | }), |
| 3549 | threadId: childThreadId, |
| 3550 | rootNodeId: childRootNodeId, |
| 3551 | providerThreadId: providerThread.id, |
| 3552 | providerTurnId: null, |
| 3553 | nativeItemRef: codexNativeItemRef(promptNativeItemId), |
| 3554 | role: "user", |
| 3555 | text: input.prompt, |
| 3556 | ordinal: 100, |
| 3557 | now, |
| 3558 | }); |
| 3559 | yield* emitProviderEvent({ |
| 3560 | type: "message.updated", |
| 3561 | driver: CODEX_PROVIDER, |
| 3562 | message: promptArtifacts.message, |
| 3563 | }); |
| 3564 | yield* emitProviderEvent({ |
| 3565 | type: "turn_item.updated", |
| 3566 | driver: CODEX_PROVIDER, |
| 3567 | turnItem: promptArtifacts.turnItem, |
| 3568 | }); |
| 3569 | } |
| 3570 | yield* emitSubagentTaskUpdate({ |
| 3571 | subagent, |
| 3572 | status: "running", |
| 3573 | }); |
| 3574 | |
| 3575 | const pendingTurns = yield* Ref.modify(pendingSubagentTurns, (current) => { |
| 3576 | const pending = current.get(input.nativeThreadId) ?? []; |
| 3577 | const updated = new Map(current); |
| 3578 | updated.delete(input.nativeThreadId); |
| 3579 | return [pending, updated]; |
| 3580 | }); |
| 3581 | for (const pendingTurn of pendingTurns) { |
| 3582 | yield* emitSubagentProviderTurnStarted(subagent, pendingTurn); |
| 3583 | } |
| 3584 | if (task.model === null) { |
| 3585 | yield* client.raw |
| 3586 | .request("thread/read", { threadId: input.nativeThreadId, includeTurns: false }) |
| 3587 | .pipe( |
| 3588 | Effect.flatMap(decodeCodexChildThread), |
| 3589 | Effect.map((response): typeof CodexChildSelection.Type | null => |
| 3590 | response.thread.id === input.nativeThreadId && response.thread.model?.trim() |
| 3591 | ? { |
| 3592 | thread: response.thread, |
| 3593 | model: response.thread.model, |
| 3594 | reasoningEffort: response.thread.reasoningEffort, |
| 3595 | } |
| 3596 | : null, |
| 3597 | ), |
| 3598 | Effect.orElseSucceed(() => null), |
| 3599 | Effect.filterOrElse( |
| 3600 | (response) => !(response === null), |
| 3601 | (_response) => |
| 3602 | client.raw |
| 3603 | .request("thread/resume", { |
| 3604 | threadId: input.nativeThreadId, |
| 3605 | excludeTurns: true, |
| 3606 | }) |
| 3607 | .pipe(Effect.flatMap(decodeCodexChildModel)), |
| 3608 | ), |
| 3609 | Effect.timeout("5 seconds"), |
| 3610 | Effect.flatMap((response) => |
| 3611 | response.thread.id === input.nativeThreadId && |
| 3612 | !subagentSelections.has(input.nativeThreadId) |
| 3613 | ? updateSubagentSelection( |
| 3614 | input.nativeThreadId, |
| 3615 | response.model, |
| 3616 | response.reasoningEffort, |
| 3617 | response.serviceTier, |
| 3618 | ) |
| 3619 | : Effect.void, |
| 3620 | ), |
| 3621 | Effect.ignore, |
| 3622 | Effect.forkIn(scope), |
| 3623 | ); |
| 3624 | } |
| 3625 | }); |
| 3626 | |
| 3627 | const registerSubagentThreads = |
| 3628 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3629 | Effect.fnUntraced(function* (input: { |
| 3630 | readonly context: ActiveCodexTurnContext; |
| 3631 | readonly item: CodexCollabAgentToolCallItem; |
| 3632 | }) { |
| 3633 | if (input.item.tool !== "spawnAgent" || input.item.receiverThreadIds.length === 0) { |
| 3634 | return; |
| 3635 | } |
| 3636 | |
| 3637 | for (const [index, nativeThreadId] of input.item.receiverThreadIds.entries()) { |
| 3638 | const model = |
| 3639 | typeof input.item.model === "string" && input.item.model.length > 0 |
| 3640 | ? input.item.model |
| 3641 | : null; |
| 3642 | yield* registerSubagentThread({ |
| 3643 | context: input.context, |
| 3644 | nativeThreadId, |
| 3645 | nativeItemId: `${input.item.id}:${nativeThreadId}`, |
| 3646 | nativeToolCallId: input.item.id, |
| 3647 | prompt: input.item.prompt ?? "", |
| 3648 | title: null, |
| 3649 | model, |
| 3650 | reasoningEffort: input.item.reasoningEffort, |
| 3651 | ordinal: index + 1, |
| 3652 | emitInitialPrompt: true, |
| 3653 | }); |
| 3654 | } |
| 3655 | }); |
| 3656 | |
| 3657 | const registerSubagentActivity = |
| 3658 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3659 | Effect.fnUntraced(function* (input: { |
| 3660 | readonly context?: ActiveCodexTurnContext; |
| 3661 | readonly item: CodexSubAgentActivityItem; |
| 3662 | }) { |
| 3663 | if (input.item.kind === "started") { |
| 3664 | const context = input.context; |
| 3665 | if (context === undefined) return; |
| 3666 | const registeredSubagents = yield* Ref.get(subagentThreads); |
| 3667 | const ordinal = |
| 3668 | Array.from(registeredSubagents.values()).filter( |
| 3669 | (subagent) => subagent.parentContext.rootNodeId === context.rootNodeId, |
| 3670 | ).length + 1; |
| 3671 | yield* registerSubagentThread({ |
| 3672 | context, |
| 3673 | nativeThreadId: input.item.agentThreadId, |
| 3674 | nativeItemId: `${input.item.id}:${input.item.agentThreadId}`, |
| 3675 | nativeToolCallId: input.item.id, |
| 3676 | prompt: "", |
| 3677 | title: input.item.agentPath, |
| 3678 | model: null, |
| 3679 | ordinal, |
| 3680 | emitInitialPrompt: false, |
| 3681 | }); |
| 3682 | return; |
| 3683 | } |
| 3684 | |
| 3685 | const subagent = (yield* Ref.get(subagentThreads)).get(input.item.agentThreadId); |
| 3686 | if (subagent === undefined) { |
| 3687 | return; |
| 3688 | } |
| 3689 | |
| 3690 | if (input.item.kind === "interrupted" || input.item.kind === "completed") { |
| 3691 | yield* emitSubagentTaskUpdate({ |
| 3692 | subagent, |
| 3693 | status: input.item.kind, |
| 3694 | }); |
| 3695 | } |
| 3696 | }); |
| 3697 | |
| 3698 | const updateSubagentStates = |
| 3699 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3700 | Effect.fnUntraced(function* (input: { readonly item: CodexCollabAgentToolCallItem }) { |
| 3701 | const subagents = yield* Ref.get(subagentThreads); |
| 3702 | for (const [nativeThreadId, state] of Object.entries(input.item.agentsStates)) { |
| 3703 | const subagent = subagents.get(nativeThreadId); |
| 3704 | if (subagent === undefined) { |
| 3705 | continue; |
| 3706 | } |
| 3707 | const statuses = { |
| 3708 | pendingInit: "pending", |
| 3709 | running: "running", |
| 3710 | interrupted: "interrupted", |
| 3711 | completed: "completed", |
| 3712 | errored: "failed", |
| 3713 | shutdown: "cancelled", |
| 3714 | notFound: "failed", |
| 3715 | } as const satisfies Record< |
| 3716 | CodexSchema.ServerNotification__CollabAgentStatus, |
| 3717 | OrchestrationV2Subagent["status"] |
| 3718 | >; |
| 3719 | const status = statuses[state.status]; |
| 3720 | yield* emitSubagentTaskUpdate({ |
| 3721 | subagent, |
| 3722 | status, |
| 3723 | ...(state.message === null ? {} : { result: state.message }), |
| 3724 | }); |
| 3725 | } |
| 3726 | }); |
| 3727 | |
| 3728 | const resolvePlanId = |
| 3729 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3730 | Effect.fnUntraced(function* (context: ActiveCodexTurnContext, planKey: string) { |
| 3731 | const existing = (yield* Ref.get(planIds)).get(planKey); |
| 3732 | if (existing !== undefined) { |
| 3733 | return existing; |
| 3734 | } |
| 3735 | const planId = yield* idAllocator.allocate.plan({ |
| 3736 | threadId: context.projectionThreadId, |
| 3737 | ...(context.projectionRunId === null ? {} : { runId: context.projectionRunId }), |
| 3738 | driver: CODEX_PROVIDER, |
| 3739 | }); |
| 3740 | yield* Ref.update(planIds, (current) => { |
| 3741 | const updated = new Map(current); |
| 3742 | updated.set(planKey, planId); |
| 3743 | return updated; |
| 3744 | }); |
| 3745 | return planId; |
| 3746 | }); |
| 3747 | |
| 3748 | const resolveCodexAttachment = Effect.fn("CodexAdapterV2.resolveCodexAttachment")( |
| 3749 | function* (attachment: ChatAttachment) { |
| 3750 | const attachmentPath = resolveAttachmentPath({ |
| 3751 | attachmentsDir: serverConfig.attachmentsDir, |
| 3752 | attachment, |
| 3753 | }); |
| 3754 | if (attachmentPath === null) { |
| 3755 | return yield* toProtocolError(`Invalid attachment id '${attachment.id}'`); |
| 3756 | } |
| 3757 | const bytes = yield* fileSystem.readFile(attachmentPath).pipe( |
| 3758 | Effect.mapError( |
| 3759 | (cause) => |
| 3760 | new ProviderAdapter.ProviderAdapterProtocolError({ |
| 3761 | driver: CODEX_PROVIDER, |
| 3762 | detail: `Failed to read attachment '${attachment.id}'.`, |
| 3763 | reason: "attachment_unreadable", |
| 3764 | payload: cause, |
| 3765 | }), |
| 3766 | ), |
| 3767 | ); |
| 3768 | return { |
| 3769 | type: "image" as const, |
| 3770 | url: `data:${attachment.mimeType};base64,${Buffer.from(bytes).toString("base64")}`, |
| 3771 | } satisfies CodexSchema.V2TurnStartParams__UserInput; |
| 3772 | }, |
| 3773 | ); |
| 3774 | |
| 3775 | const toCodexInput = Effect.fn("CodexAdapterV2.toCodexInput")(function* ( |
| 3776 | turnInput: Pick< |
| 3777 | | ProviderAdapter.ProviderAdapterV2TurnInput |
| 3778 | | ProviderAdapter.ProviderAdapterV2SteerInput, |
| 3779 | "message" |
| 3780 | >, |
| 3781 | ) { |
| 3782 | const inputItems: Array<CodexSchema.V2TurnStartParams__UserInput> = []; |
| 3783 | const text = yield* providerMessageTextWithAttachmentPaths({ |
| 3784 | text: codexSkillMentionText(turnInput.message.text), |
| 3785 | attachments: turnInput.message.attachments, |
| 3786 | resolveExtractedTextPath: (path) => |
| 3787 | DocumentText.resolveExtractedTextPath(path).pipe( |
| 3788 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 3789 | ), |
| 3790 | resolveAttachmentPath: (attachment) => |
| 3791 | resolveAttachmentPath({ attachmentsDir: serverConfig.attachmentsDir, attachment }), |
| 3792 | }); |
| 3793 | if (text.length > 0) { |
| 3794 | inputItems.push({ |
| 3795 | type: "text", |
| 3796 | text, |
| 3797 | }); |
| 3798 | } |
| 3799 | const attachmentItems = yield* Effect.forEach( |
| 3800 | turnInput.message.attachments.filter(isProviderNativeImageAttachment), |
| 3801 | resolveCodexAttachment, |
| 3802 | { concurrency: 1 }, |
| 3803 | ); |
| 3804 | inputItems.push(...attachmentItems); |
| 3805 | if (inputItems.length === 0) { |
| 3806 | return yield* toProtocolError("Turn requires non-empty text or attachments."); |
| 3807 | } |
| 3808 | return inputItems; |
| 3809 | }); |
| 3810 | |
| 3811 | // Reasoning and assistant-text coalescers build these artifacts on every streamed update. |
| 3812 | const buildAgentMessageArtifacts = Effect.fnUntraced(function* ( |
| 3813 | context: ActiveCodexTurnContext, |
| 3814 | item: { readonly id: string; readonly text: string }, |
| 3815 | completed: boolean, |
| 3816 | ) { |
| 3817 | const updatedAt = yield* DateTime.now; |
| 3818 | const completedAt = completed ? updatedAt : null; |
| 3819 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 3820 | driver: CODEX_PROVIDER, |
| 3821 | nativeItemId: item.id, |
| 3822 | }); |
| 3823 | const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id); |
| 3824 | const messageId = idAllocator.derive.messageFromProviderItem({ |
| 3825 | driver: CODEX_PROVIDER, |
| 3826 | nativeItemId: item.id, |
| 3827 | }); |
| 3828 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 3829 | driver: CODEX_PROVIDER, |
| 3830 | nativeItemId: item.id, |
| 3831 | }); |
| 3832 | const node: OrchestrationV2ExecutionNode = { |
| 3833 | id: nodeId, |
| 3834 | threadId: context.projectionThreadId, |
| 3835 | runId: context.projectionRunId, |
| 3836 | parentNodeId: context.itemParentNodeId, |
| 3837 | rootNodeId: context.rootNodeId, |
| 3838 | kind: "assistant_message", |
| 3839 | status: completed ? "completed" : "running", |
| 3840 | countsForRun: false, |
| 3841 | providerThreadId: context.providerThread.id, |
| 3842 | providerTurnId: context.providerTurnId, |
| 3843 | nativeItemRef: codexNativeItemRef(item.id), |
| 3844 | runtimeRequestId: null, |
| 3845 | checkpointScopeId: null, |
| 3846 | startedAt, |
| 3847 | completedAt, |
| 3848 | }; |
| 3849 | const message: OrchestrationV2ConversationMessage = { |
| 3850 | createdBy: "agent", |
| 3851 | creationSource: "provider", |
| 3852 | id: messageId, |
| 3853 | threadId: context.projectionThreadId, |
| 3854 | runId: context.projectionRunId, |
| 3855 | nodeId, |
| 3856 | role: "assistant", |
| 3857 | text: item.text, |
| 3858 | attachments: [], |
| 3859 | streaming: !completed, |
| 3860 | createdAt: startedAt, |
| 3861 | updatedAt, |
| 3862 | }; |
| 3863 | const turnItem: OrchestrationV2TurnItem = { |
| 3864 | id: turnItemId, |
| 3865 | threadId: context.projectionThreadId, |
| 3866 | runId: context.projectionRunId, |
| 3867 | nodeId, |
| 3868 | providerThreadId: context.providerThread.id, |
| 3869 | providerTurnId: context.providerTurnId, |
| 3870 | nativeItemRef: codexNativeItemRef(item.id), |
| 3871 | parentItemId: null, |
| 3872 | ordinal, |
| 3873 | status: completed ? "completed" : "running", |
| 3874 | title: null, |
| 3875 | startedAt, |
| 3876 | completedAt, |
| 3877 | updatedAt, |
| 3878 | type: "assistant_message", |
| 3879 | ...(context.messagePhases.has(item.id) |
| 3880 | ? { phase: context.messagePhases.get(item.id) } |
| 3881 | : {}), |
| 3882 | messageId, |
| 3883 | text: item.text, |
| 3884 | streaming: !completed, |
| 3885 | }; |
| 3886 | return { node, message, turnItem }; |
| 3887 | }); |
| 3888 | |
| 3889 | // Coalesce token bursts to avoid a database write per token. |
| 3890 | const reasoningParts = new Map< |
| 3891 | string, |
| 3892 | { turnId: string; nativeItemId: string; stream: "summary" | "content"; index: number } |
| 3893 | >(); |
| 3894 | const reasoningDeltas = yield* makeProviderTextDeltaCoalescer({ |
| 3895 | flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS, |
| 3896 | emit: |
| 3897 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3898 | Effect.fnUntraced(function* (update) { |
| 3899 | const part = reasoningParts.get(update.itemId); |
| 3900 | if (part === undefined) return; |
| 3901 | const context = yield* awaitActiveTurn(update.turnId); |
| 3902 | if (context === undefined) return; |
| 3903 | const artifacts = yield* buildAgentMessageArtifacts( |
| 3904 | context, |
| 3905 | { id: update.itemId, text: update.text }, |
| 3906 | update.completed, |
| 3907 | ); |
| 3908 | const interrupted = (yield* Ref.get(terminalizedNonCompletedNativeTurns)).has( |
| 3909 | update.turnId, |
| 3910 | ); |
| 3911 | const { messageId: _messageId, ...item } = artifacts.turnItem; |
| 3912 | const nativeItemRef = codexNativeItemRef(part.nativeItemId); |
| 3913 | yield* emitProviderEvent({ |
| 3914 | type: "node.updated", |
| 3915 | driver: CODEX_PROVIDER, |
| 3916 | node: { |
| 3917 | ...artifacts.node, |
| 3918 | kind: "reasoning", |
| 3919 | nativeItemRef, |
| 3920 | ...(interrupted ? { status: "interrupted" as const } : {}), |
| 3921 | }, |
| 3922 | }); |
| 3923 | yield* emitProviderEvent({ |
| 3924 | type: "turn_item.updated", |
| 3925 | driver: CODEX_PROVIDER, |
| 3926 | turnItem: { |
| 3927 | ...item, |
| 3928 | type: "reasoning", |
| 3929 | nativeItemRef, |
| 3930 | ...(interrupted ? { status: "interrupted" as const } : {}), |
| 3931 | }, |
| 3932 | }); |
| 3933 | }), |
| 3934 | }); |
| 3935 | const reasoningPartKey = ( |
| 3936 | turnId: string, |
| 3937 | nativeItemId: string, |
| 3938 | stream: "summary" | "content", |
| 3939 | index: number, |
| 3940 | ) => { |
| 3941 | const key = JSON.stringify([turnId, nativeItemId, stream, index]); |
| 3942 | reasoningParts.set(key, { turnId, nativeItemId, stream, index }); |
| 3943 | return key; |
| 3944 | }; |
| 3945 | const appendReasoning = Effect.fn("CodexAdapterV2.appendReasoning")(function* ( |
| 3946 | payload: { turnId: string; itemId: string; delta: string }, |
| 3947 | stream: "summary" | "content", |
| 3948 | index: number, |
| 3949 | ) { |
| 3950 | const context = yield* awaitActiveTurn(payload.turnId); |
| 3951 | if (context === undefined || payload.delta.length === 0) return; |
| 3952 | yield* completeProviderRetry(context, yield* DateTime.now); |
| 3953 | const itemId = reasoningPartKey(payload.turnId, payload.itemId, stream, index); |
| 3954 | // Reserve positions before delayed flushes so later tools stay after them. |
| 3955 | yield* resolveItemOrdinal(context, itemId); |
| 3956 | yield* reasoningDeltas.append({ turnId: payload.turnId, itemId, delta: payload.delta }); |
| 3957 | }); |
| 3958 | const completeReasoning = Effect.fn("CodexAdapterV2.completeReasoning")(function* ( |
| 3959 | turnId: string, |
| 3960 | item: { id: string; summary?: ReadonlyArray<string>; content?: ReadonlyArray<string> }, |
| 3961 | ) { |
| 3962 | for (const stream of ["summary", "content"] as const) { |
| 3963 | for (const [index] of (item[stream] ?? []).entries()) { |
| 3964 | reasoningPartKey(turnId, item.id, stream, index); |
| 3965 | } |
| 3966 | } |
| 3967 | for (const [key, part] of reasoningParts) { |
| 3968 | if (part.turnId !== turnId || part.nativeItemId !== item.id) continue; |
| 3969 | const finalText = item[part.stream]?.[part.index]; |
| 3970 | yield* reasoningDeltas.complete({ |
| 3971 | turnId, |
| 3972 | itemId: key, |
| 3973 | ...(finalText ? { finalText } : {}), |
| 3974 | emitEmpty: false, |
| 3975 | }); |
| 3976 | reasoningParts.delete(key); |
| 3977 | } |
| 3978 | }); |
| 3979 | |
| 3980 | const agentMessageDeltas = yield* makeProviderTextDeltaCoalescer({ |
| 3981 | flushIntervalMs: CODEX_ASSISTANT_DELTA_FLUSH_INTERVAL_MS, |
| 3982 | emit: |
| 3983 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 3984 | Effect.fnUntraced(function* (update) { |
| 3985 | const context = yield* awaitActiveTurn(update.turnId); |
| 3986 | if (context === undefined) { |
| 3987 | return; |
| 3988 | } |
| 3989 | const finalAnswerItem = (yield* Ref.get(finalAnswerItemIdsByTurn)) |
| 3990 | .get(update.turnId) |
| 3991 | ?.has(update.itemId); |
| 3992 | if (finalAnswerItem) { |
| 3993 | const finalAnswerItemIds = (yield* Ref.get(finalAnswerItemIdsByTurn)).get( |
| 3994 | update.turnId, |
| 3995 | ); |
| 3996 | const completedTexts = |
| 3997 | (yield* Ref.get(completedFinalAnswerTextsByTurn)).get(update.turnId) ?? |
| 3998 | new Set<string>(); |
| 3999 | const firstFinalAnswerItemId = finalAnswerItemIds?.values().next().value; |
| 4000 | const duplicateCompletion = |
| 4001 | update.completed && |
| 4002 | completedTexts.size > 0 && |
| 4003 | (update.text.length === 0 || completedTexts.has(update.text)); |
| 4004 | const deferredStreamingUpdate = |
| 4005 | !update.completed && |
| 4006 | (completedTexts.size > 0 || firstFinalAnswerItemId !== update.itemId); |
| 4007 | if (deferredStreamingUpdate || duplicateCompletion) { |
| 4008 | return; |
| 4009 | } |
| 4010 | } |
| 4011 | const artifacts = yield* buildAgentMessageArtifacts( |
| 4012 | context, |
| 4013 | { id: update.itemId, text: update.text }, |
| 4014 | update.completed, |
| 4015 | ); |
| 4016 | yield* emitProviderEvent({ |
| 4017 | type: "node.updated", |
| 4018 | driver: CODEX_PROVIDER, |
| 4019 | node: artifacts.node, |
| 4020 | }); |
| 4021 | if (update.completed) { |
| 4022 | yield* emitProviderEvent({ |
| 4023 | type: "message.updated", |
| 4024 | driver: CODEX_PROVIDER, |
| 4025 | message: artifacts.message, |
| 4026 | }); |
| 4027 | } |
| 4028 | yield* emitProviderEvent({ |
| 4029 | type: "turn_item.updated", |
| 4030 | driver: CODEX_PROVIDER, |
| 4031 | turnItem: artifacts.turnItem, |
| 4032 | }); |
| 4033 | if (finalAnswerItem && update.completed) { |
| 4034 | imageTurn(update.turnId).answer = { id: update.itemId, text: update.text }; |
| 4035 | yield* Ref.update(completedFinalAnswerTextsByTurn, (current) => { |
| 4036 | const updated = new Map(current); |
| 4037 | const texts = new Set(updated.get(update.turnId) ?? []); |
| 4038 | texts.add(update.text); |
| 4039 | updated.set(update.turnId, texts); |
| 4040 | return updated; |
| 4041 | }); |
| 4042 | } |
| 4043 | }), |
| 4044 | }); |
| 4045 | |
| 4046 | const emitSubagentUserMessage = |
| 4047 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 4048 | Effect.fnUntraced(function* ( |
| 4049 | context: ActiveCodexTurnContext, |
| 4050 | item: Extract< |
| 4051 | | CodexSchema.V2ItemStartedNotification__ThreadItem |
| 4052 | | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 4053 | { type: "userMessage" } |
| 4054 | >, |
| 4055 | nativeStartedAt?: DateTime.Utc, |
| 4056 | ) { |
| 4057 | if (context.subagent === null || context.providerTurnOrdinal === 1) { |
| 4058 | return false; |
| 4059 | } |
| 4060 | const text = codexUserMessageText(item.content); |
| 4061 | if (text.length === 0) { |
| 4062 | return false; |
| 4063 | } |
| 4064 | const { ordinal, startedAt } = yield* resolveItemPosition( |
| 4065 | context, |
| 4066 | item.id, |
| 4067 | nativeStartedAt, |
| 4068 | ); |
| 4069 | const artifacts = makeSubagentConversationArtifacts({ |
| 4070 | senderThreadId: context.subagent.parentContext.projectionThreadId, |
| 4071 | messageId: idAllocator.derive.messageFromProviderItem({ |
| 4072 | driver: CODEX_PROVIDER, |
| 4073 | nativeItemId: item.id, |
| 4074 | }), |
| 4075 | turnItemId: idAllocator.derive.turnItemFromProviderItem({ |
| 4076 | driver: CODEX_PROVIDER, |
| 4077 | nativeItemId: item.id, |
| 4078 | }), |
| 4079 | threadId: context.projectionThreadId, |
| 4080 | rootNodeId: context.rootNodeId, |
| 4081 | providerThreadId: context.providerThread.id, |
| 4082 | providerTurnId: context.providerTurnId, |
| 4083 | nativeItemRef: codexNativeItemRef(item.id), |
| 4084 | role: "user", |
| 4085 | text, |
| 4086 | ordinal, |
| 4087 | now: startedAt, |
| 4088 | }); |
| 4089 | yield* emitProviderEvent({ |
| 4090 | type: "message.updated", |
| 4091 | driver: CODEX_PROVIDER, |
| 4092 | message: artifacts.message, |
| 4093 | }); |
| 4094 | yield* emitProviderEvent({ |
| 4095 | type: "turn_item.updated", |
| 4096 | driver: CODEX_PROVIDER, |
| 4097 | turnItem: artifacts.turnItem, |
| 4098 | }); |
| 4099 | return true; |
| 4100 | }); |
| 4101 | |
| 4102 | const buildCommandExecutionArtifacts = Effect.fn( |
| 4103 | "CodexAdapterV2.buildCommandExecutionArtifacts", |
| 4104 | )(function* ( |
| 4105 | context: ActiveCodexTurnContext, |
| 4106 | item: Extract< |
| 4107 | | CodexSchema.V2ItemStartedNotification__ThreadItem |
| 4108 | | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 4109 | { type: "commandExecution" } |
| 4110 | >, |
| 4111 | ) { |
| 4112 | const updatedAt = yield* DateTime.now; |
| 4113 | const status = codexItemStatus(item.status); |
| 4114 | const completedAt = status.completed ? updatedAt : null; |
| 4115 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4116 | driver: CODEX_PROVIDER, |
| 4117 | nativeItemId: item.id, |
| 4118 | }); |
| 4119 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4120 | driver: CODEX_PROVIDER, |
| 4121 | nativeItemId: item.id, |
| 4122 | }); |
| 4123 | const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id); |
| 4124 | const node: OrchestrationV2ExecutionNode = { |
| 4125 | id: nodeId, |
| 4126 | threadId: context.projectionThreadId, |
| 4127 | runId: context.projectionRunId, |
| 4128 | parentNodeId: context.itemParentNodeId, |
| 4129 | rootNodeId: context.rootNodeId, |
| 4130 | kind: "tool_call", |
| 4131 | status: status.node, |
| 4132 | countsForRun: false, |
| 4133 | providerThreadId: context.providerThread.id, |
| 4134 | providerTurnId: context.providerTurnId, |
| 4135 | nativeItemRef: codexNativeItemRef(item.id), |
| 4136 | runtimeRequestId: null, |
| 4137 | checkpointScopeId: null, |
| 4138 | startedAt, |
| 4139 | completedAt, |
| 4140 | }; |
| 4141 | const turnItem: OrchestrationV2TurnItem = { |
| 4142 | id: turnItemId, |
| 4143 | threadId: context.projectionThreadId, |
| 4144 | runId: context.projectionRunId, |
| 4145 | nodeId, |
| 4146 | providerThreadId: context.providerThread.id, |
| 4147 | providerTurnId: context.providerTurnId, |
| 4148 | nativeItemRef: codexNativeItemRef(item.id), |
| 4149 | parentItemId: null, |
| 4150 | ordinal, |
| 4151 | status: status.turnItem, |
| 4152 | title: null, |
| 4153 | startedAt, |
| 4154 | completedAt, |
| 4155 | updatedAt, |
| 4156 | type: "command_execution", |
| 4157 | input: item.command, |
| 4158 | ...(item.aggregatedOutput === null || item.aggregatedOutput === undefined |
| 4159 | ? {} |
| 4160 | : { output: item.aggregatedOutput }), |
| 4161 | ...(item.exitCode === null || item.exitCode === undefined |
| 4162 | ? {} |
| 4163 | : { exitCode: item.exitCode }), |
| 4164 | // Matches the continuation offered when it completes after the turn. |
| 4165 | ...(context.subagent === null && continuationRequests !== undefined |
| 4166 | ? { completionWake: "always" as const } |
| 4167 | : {}), |
| 4168 | }; |
| 4169 | return { node, turnItem }; |
| 4170 | }); |
| 4171 | |
| 4172 | const buildFileChangeArtifacts = Effect.fn("CodexAdapterV2.buildFileChangeArtifacts")( |
| 4173 | function* ( |
| 4174 | context: ActiveCodexTurnContext, |
| 4175 | item: Extract< |
| 4176 | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 4177 | { type: "fileChange" } |
| 4178 | >, |
| 4179 | ) { |
| 4180 | const firstChange = item.changes[0]; |
| 4181 | if (firstChange === undefined) { |
| 4182 | return null; |
| 4183 | } |
| 4184 | |
| 4185 | const updatedAt = yield* DateTime.now; |
| 4186 | const status = codexItemStatus(item.status); |
| 4187 | const completedAt = status.completed ? updatedAt : null; |
| 4188 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4189 | driver: CODEX_PROVIDER, |
| 4190 | nativeItemId: item.id, |
| 4191 | }); |
| 4192 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4193 | driver: CODEX_PROVIDER, |
| 4194 | nativeItemId: item.id, |
| 4195 | }); |
| 4196 | const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id); |
| 4197 | const node: OrchestrationV2ExecutionNode = { |
| 4198 | id: nodeId, |
| 4199 | threadId: context.projectionThreadId, |
| 4200 | runId: context.projectionRunId, |
| 4201 | parentNodeId: context.itemParentNodeId, |
| 4202 | rootNodeId: context.rootNodeId, |
| 4203 | kind: "tool_call", |
| 4204 | status: status.node, |
| 4205 | countsForRun: false, |
| 4206 | providerThreadId: context.providerThread.id, |
| 4207 | providerTurnId: context.providerTurnId, |
| 4208 | nativeItemRef: codexNativeItemRef(item.id), |
| 4209 | runtimeRequestId: null, |
| 4210 | checkpointScopeId: null, |
| 4211 | startedAt, |
| 4212 | completedAt, |
| 4213 | }; |
| 4214 | const turnItem: OrchestrationV2TurnItem = { |
| 4215 | id: turnItemId, |
| 4216 | threadId: context.projectionThreadId, |
| 4217 | runId: context.projectionRunId, |
| 4218 | nodeId, |
| 4219 | providerThreadId: context.providerThread.id, |
| 4220 | providerTurnId: context.providerTurnId, |
| 4221 | nativeItemRef: codexNativeItemRef(item.id), |
| 4222 | parentItemId: null, |
| 4223 | ordinal, |
| 4224 | status: status.turnItem, |
| 4225 | title: null, |
| 4226 | startedAt, |
| 4227 | completedAt, |
| 4228 | updatedAt, |
| 4229 | type: "file_change", |
| 4230 | fileName: firstChange.path, |
| 4231 | diffStr: firstChange.diff, |
| 4232 | changes: item.changes.map((change) => { |
| 4233 | const movePath = change.kind.type === "update" ? change.kind.move_path : undefined; |
| 4234 | return movePath |
| 4235 | ? { operation: change.kind.type, path: movePath, oldPath: change.path } |
| 4236 | : { operation: change.kind.type, path: change.path }; |
| 4237 | }), |
| 4238 | }; |
| 4239 | return { node, turnItem }; |
| 4240 | }, |
| 4241 | ); |
| 4242 | |
| 4243 | const buildWebSearchArtifacts = Effect.fn("CodexAdapterV2.buildWebSearchArtifacts")( |
| 4244 | function* (input: { |
| 4245 | readonly context: ActiveCodexTurnContext; |
| 4246 | readonly item: CodexWebSearchItem; |
| 4247 | readonly status: "running" | "completed" | "cancelled" | "failed" | "interrupted"; |
| 4248 | readonly updatedAt?: DateTime.Utc; |
| 4249 | }) { |
| 4250 | const updatedAt = input.updatedAt ?? (yield* DateTime.now); |
| 4251 | const completedAt = input.status === "running" ? null : updatedAt; |
| 4252 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4253 | driver: CODEX_PROVIDER, |
| 4254 | nativeItemId: input.item.id, |
| 4255 | }); |
| 4256 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4257 | driver: CODEX_PROVIDER, |
| 4258 | nativeItemId: input.item.id, |
| 4259 | }); |
| 4260 | const { ordinal, startedAt } = yield* resolveItemPosition(input.context, input.item.id); |
| 4261 | const patterns = webSearchPatterns(input.item); |
| 4262 | const { status } = input; |
| 4263 | const node: OrchestrationV2ExecutionNode = { |
| 4264 | id: nodeId, |
| 4265 | threadId: input.context.projectionThreadId, |
| 4266 | runId: input.context.projectionRunId, |
| 4267 | parentNodeId: input.context.itemParentNodeId, |
| 4268 | rootNodeId: input.context.rootNodeId, |
| 4269 | kind: "tool_call", |
| 4270 | status, |
| 4271 | countsForRun: false, |
| 4272 | providerThreadId: input.context.providerThread.id, |
| 4273 | providerTurnId: input.context.providerTurnId, |
| 4274 | nativeItemRef: codexNativeItemRef(input.item.id), |
| 4275 | runtimeRequestId: null, |
| 4276 | checkpointScopeId: null, |
| 4277 | startedAt, |
| 4278 | completedAt, |
| 4279 | }; |
| 4280 | const turnItem: OrchestrationV2TurnItem = { |
| 4281 | id: turnItemId, |
| 4282 | threadId: input.context.projectionThreadId, |
| 4283 | runId: input.context.projectionRunId, |
| 4284 | nodeId, |
| 4285 | providerThreadId: input.context.providerThread.id, |
| 4286 | providerTurnId: input.context.providerTurnId, |
| 4287 | nativeItemRef: codexNativeItemRef(input.item.id), |
| 4288 | parentItemId: null, |
| 4289 | ordinal, |
| 4290 | status, |
| 4291 | title: null, |
| 4292 | startedAt, |
| 4293 | completedAt, |
| 4294 | updatedAt, |
| 4295 | type: "web_search", |
| 4296 | ...(patterns.length === 0 ? {} : { patterns: [...patterns] }), |
| 4297 | }; |
| 4298 | return { node, turnItem }; |
| 4299 | }, |
| 4300 | ); |
| 4301 | |
| 4302 | const buildDynamicToolArtifacts = Effect.fn("CodexAdapterV2.buildDynamicToolArtifacts")( |
| 4303 | function* (context: ActiveCodexTurnContext, item: CodexDynamicToolItem) { |
| 4304 | const updatedAt = yield* DateTime.now; |
| 4305 | const status = codexItemStatus(item.status); |
| 4306 | const completedAt = status.completed ? updatedAt : null; |
| 4307 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4308 | driver: CODEX_PROVIDER, |
| 4309 | nativeItemId: item.id, |
| 4310 | }); |
| 4311 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4312 | driver: CODEX_PROVIDER, |
| 4313 | nativeItemId: item.id, |
| 4314 | }); |
| 4315 | const { ordinal, startedAt } = yield* resolveItemPosition(context, item.id); |
| 4316 | const projection = yield* projectCodexDynamicToolItem(item).pipe( |
| 4317 | Effect.provideService(Digest.Digest, digest), |
| 4318 | ); |
| 4319 | const node: OrchestrationV2ExecutionNode = { |
| 4320 | id: nodeId, |
| 4321 | threadId: context.projectionThreadId, |
| 4322 | runId: context.projectionRunId, |
| 4323 | parentNodeId: context.itemParentNodeId, |
| 4324 | rootNodeId: context.rootNodeId, |
| 4325 | kind: "tool_call", |
| 4326 | status: status.node, |
| 4327 | countsForRun: false, |
| 4328 | providerThreadId: context.providerThread.id, |
| 4329 | providerTurnId: context.providerTurnId, |
| 4330 | nativeItemRef: codexNativeItemRef(item.id), |
| 4331 | runtimeRequestId: null, |
| 4332 | checkpointScopeId: null, |
| 4333 | startedAt, |
| 4334 | completedAt, |
| 4335 | }; |
| 4336 | const turnItem: OrchestrationV2TurnItem = { |
| 4337 | id: turnItemId, |
| 4338 | threadId: context.projectionThreadId, |
| 4339 | runId: context.projectionRunId, |
| 4340 | nodeId, |
| 4341 | providerThreadId: context.providerThread.id, |
| 4342 | providerTurnId: context.providerTurnId, |
| 4343 | nativeItemRef: codexNativeItemRef(item.id), |
| 4344 | parentItemId: null, |
| 4345 | ordinal, |
| 4346 | title: projection.title ?? null, |
| 4347 | startedAt, |
| 4348 | completedAt, |
| 4349 | updatedAt, |
| 4350 | type: "dynamic_tool", |
| 4351 | ...projection, |
| 4352 | }; |
| 4353 | return { node, turnItem }; |
| 4354 | }, |
| 4355 | ); |
| 4356 | |
| 4357 | const emitImageGenerationItem = Effect.fn("CodexAdapterV2.emitImageGenerationItem")( |
| 4358 | function* ( |
| 4359 | context: ActiveCodexTurnContext, |
| 4360 | item: Extract< |
| 4361 | CodexSchema.V2ItemCompletedNotification__ThreadItem, |
| 4362 | { type: "imageGeneration" } |
| 4363 | >, |
| 4364 | completed: boolean, |
| 4365 | ) { |
| 4366 | const cancelled = completed && item.status === "cancelled"; |
| 4367 | const failed = item.status === "failed" || item.failure != null; |
| 4368 | const artifacts = yield* buildDynamicToolArtifacts(context, { |
| 4369 | type: "dynamicToolCall", |
| 4370 | id: item.id, |
| 4371 | namespace: "image_gen", |
| 4372 | tool: "imagegen", |
| 4373 | status: completed ? (failed ? "failed" : "completed") : "inProgress", |
| 4374 | arguments: { |
| 4375 | ...(item.revisedPrompt == null ? {} : { prompt: item.revisedPrompt }), |
| 4376 | ...(item.transparentBackground == null |
| 4377 | ? {} |
| 4378 | : { transparent_background: item.transparentBackground }), |
| 4379 | }, |
| 4380 | }); |
| 4381 | yield* emitProviderEvent({ |
| 4382 | type: "node.updated", |
| 4383 | driver: CODEX_PROVIDER, |
| 4384 | node: { ...artifacts.node, ...(cancelled ? { status: "cancelled" } : {}) }, |
| 4385 | }); |
| 4386 | yield* emitProviderEvent({ |
| 4387 | type: "turn_item.updated", |
| 4388 | driver: CODEX_PROVIDER, |
| 4389 | turnItem: { |
| 4390 | ...artifacts.turnItem, |
| 4391 | title: "Generate image", |
| 4392 | ...(cancelled ? { status: "cancelled" } : {}), |
| 4393 | ...(completed |
| 4394 | ? { |
| 4395 | output: { |
| 4396 | status: item.status, |
| 4397 | ...(item.savedPath == null ? {} : { savedPath: item.savedPath }), |
| 4398 | ...(item.failure == null ? {} : { failure: item.failure }), |
| 4399 | }, |
| 4400 | } |
| 4401 | : {}), |
| 4402 | }, |
| 4403 | }); |
| 4404 | }, |
| 4405 | ); |
| 4406 | |
| 4407 | /** |
| 4408 | * The item stays running until then, which keeps the run's event |
| 4409 | * ingestion open past turn/completed; it runs off the notification |
| 4410 | * reader so a slow server cannot stall other events. |
| 4411 | */ |
| 4412 | const captureMcpApp = Effect.fn("CodexAdapterV2.captureMcpApp")(function* ( |
| 4413 | context: ActiveCodexTurnContext, |
| 4414 | nativeTurnId: string, |
| 4415 | item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>, |
| 4416 | resourceUri: string, |
| 4417 | ) { |
| 4418 | // Registered before it can run, so a turn ending right away sees it. |
| 4419 | const started = yield* Deferred.make<void>(); |
| 4420 | const fiber = yield* Deferred.await(started).pipe( |
| 4421 | Effect.andThen(captureMcpAppItem(context, nativeTurnId, item, resourceUri)), |
| 4422 | Effect.forkIn(scope, { startImmediately: true }), |
| 4423 | ); |
| 4424 | yield* Ref.update(pendingMcpAppCaptures, (current) => { |
| 4425 | const updated = new Map(current); |
| 4426 | updated.set( |
| 4427 | nativeTurnId, |
| 4428 | new Map(current.get(nativeTurnId) ?? []).set(item.id, { item, fiber }), |
| 4429 | ); |
| 4430 | return updated; |
| 4431 | }); |
| 4432 | yield* Deferred.succeed(started, undefined); |
| 4433 | }); |
| 4434 | |
| 4435 | const captureMcpAppItem = ( |
| 4436 | context: ActiveCodexTurnContext, |
| 4437 | nativeTurnId: string, |
| 4438 | item: Extract<CodexDynamicToolItem, { readonly type: "mcpToolCall" }>, |
| 4439 | resourceUri: string, |
| 4440 | ) => |
| 4441 | // Only reads and storage are cancellable; remove partial writes. Once stored, attach the app or delete it if the item settled. |
| 4442 | Effect.uninterruptibleMask((restore) => |
| 4443 | Effect.gen(function* () { |
| 4444 | const reference = |
| 4445 | item.result != null && item.error == null |
| 4446 | ? yield* restore( |
| 4447 | getNativeThreadId(context.providerThread).pipe( |
| 4448 | Effect.flatMap((threadId) => |
| 4449 | client.request("mcpServer/resource/read", { |
| 4450 | threadId, |
| 4451 | server: item.server, |
| 4452 | uri: resourceUri, |
| 4453 | }), |
| 4454 | ), |
| 4455 | Effect.timeout(MCP_APP_CAPTURE_TIMEOUT), |
| 4456 | Effect.flatMap((response) => |
| 4457 | snapshotMcpApp({ |
| 4458 | attachmentsDir: serverConfig.attachmentsDir, |
| 4459 | threadId: context.projectionThreadId, |
| 4460 | server: item.server, |
| 4461 | tool: item.tool, |
| 4462 | resourceUri, |
| 4463 | contents: response.contents, |
| 4464 | }), |
| 4465 | ), |
| 4466 | Effect.provideService(FileSystem.FileSystem, fileSystem), |
| 4467 | // Convert failures and defects to plain tool rows; only interruption ends the capture fiber. |
| 4468 | Effect.catchCauseIf( |
| 4469 | (cause) => !Cause.hasInterruptsOnly(cause), |
| 4470 | (cause) => |
| 4471 | Effect.logWarning( |
| 4472 | "Failed to capture an MCP app; showing a plain tool row.", |
| 4473 | { server: item.server, tool: item.tool, resourceUri, cause }, |
| 4474 | ).pipe(Effect.as(undefined)), |
| 4475 | ), |
| 4476 | Effect.orDie, |
| 4477 | ), |
| 4478 | ) |
| 4479 | : undefined; |
| 4480 | const artifacts = yield* buildDynamicToolArtifacts(context, item); |
| 4481 | // Clear before emitting; ingestion rechecks pending work after each event. |
| 4482 | if (!(yield* takePendingMcpAppCapture(nativeTurnId, item.id))) { |
| 4483 | if (reference !== undefined) { |
| 4484 | const filePath = resolveAttachmentPathById({ |
| 4485 | attachmentsDir: serverConfig.attachmentsDir, |
| 4486 | attachmentId: reference.attachmentId, |
| 4487 | }); |
| 4488 | if (filePath !== null) { |
| 4489 | yield* fileSystem.remove(filePath, { force: true }).pipe(Effect.ignore); |
| 4490 | } |
| 4491 | } |
| 4492 | return; |
| 4493 | } |
| 4494 | const turnItem = |
| 4495 | reference === undefined || artifacts.turnItem.type !== "dynamic_tool" |
| 4496 | ? artifacts.turnItem |
| 4497 | : { |
| 4498 | ...artifacts.turnItem, |
| 4499 | output: { |
| 4500 | [MCP_APP_OUTPUT_KEY]: reference, |
| 4501 | result: |
| 4502 | item.status === "failed" |
| 4503 | ? { ...item.result, isError: true } |
| 4504 | : item.result, |
| 4505 | }, |
| 4506 | }; |
| 4507 | yield* emitProviderEvent({ |
| 4508 | type: "node.updated", |
| 4509 | driver: CODEX_PROVIDER, |
| 4510 | node: artifacts.node, |
| 4511 | }); |
| 4512 | yield* emitProviderEvent({ |
| 4513 | type: "turn_item.updated", |
| 4514 | driver: CODEX_PROVIDER, |
| 4515 | turnItem, |
| 4516 | }); |
| 4517 | if ((yield* Ref.get(settledTurns)).has(nativeTurnId)) { |
| 4518 | yield* releaseSettledTurnIfIdle(nativeTurnId); |
| 4519 | } |
| 4520 | }), |
| 4521 | ); |
| 4522 | |
| 4523 | const terminalizeMcpAppCaptures = Effect.fn("CodexAdapterV2.terminalizeMcpAppCaptures")( |
| 4524 | function* (context: ActiveCodexTurnContext, nativeTurnId: string) { |
| 4525 | const captures = (yield* Ref.get(pendingMcpAppCaptures)).get(nativeTurnId); |
| 4526 | if (captures === undefined) return; |
| 4527 | for (const { item, fiber } of captures.values()) { |
| 4528 | if (!(yield* takePendingMcpAppCapture(nativeTurnId, item.id))) continue; |
| 4529 | yield* Fiber.interrupt(fiber); |
| 4530 | const artifacts = yield* buildDynamicToolArtifacts(context, item); |
| 4531 | yield* emitProviderEvent({ |
| 4532 | type: "node.updated", |
| 4533 | driver: CODEX_PROVIDER, |
| 4534 | node: artifacts.node, |
| 4535 | }); |
| 4536 | yield* emitProviderEvent({ |
| 4537 | type: "turn_item.updated", |
| 4538 | driver: CODEX_PROVIDER, |
| 4539 | turnItem: artifacts.turnItem, |
| 4540 | }); |
| 4541 | } |
| 4542 | }, |
| 4543 | ); |
| 4544 | |
| 4545 | // The plan coalescer builds these artifacts on every streamed update. |
| 4546 | const buildProposedPlanArtifacts = Effect.fnUntraced(function* (input: { |
| 4547 | readonly context: ActiveCodexTurnContext; |
| 4548 | readonly nativeItemId: string; |
| 4549 | readonly status: OrchestrationV2PlanArtifact["status"]; |
| 4550 | readonly markdown: string; |
| 4551 | readonly completed?: boolean; |
| 4552 | }) { |
| 4553 | const updatedAt = yield* DateTime.now; |
| 4554 | const completedAt = input.completed === true ? updatedAt : null; |
| 4555 | const planId = yield* resolvePlanId(input.context, input.nativeItemId); |
| 4556 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4557 | driver: CODEX_PROVIDER, |
| 4558 | nativeItemId: input.nativeItemId, |
| 4559 | }); |
| 4560 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4561 | driver: CODEX_PROVIDER, |
| 4562 | nativeItemId: input.nativeItemId, |
| 4563 | }); |
| 4564 | const { ordinal, startedAt } = yield* resolveItemPosition( |
| 4565 | input.context, |
| 4566 | input.nativeItemId, |
| 4567 | ); |
| 4568 | const plan: OrchestrationV2PlanArtifact = { |
| 4569 | id: planId, |
| 4570 | threadId: input.context.projectionThreadId, |
| 4571 | runId: input.context.projectionRunId, |
| 4572 | nodeId, |
| 4573 | kind: "proposed_plan", |
| 4574 | status: input.status, |
| 4575 | markdown: input.markdown, |
| 4576 | }; |
| 4577 | const node: OrchestrationV2ExecutionNode = { |
| 4578 | id: nodeId, |
| 4579 | threadId: input.context.projectionThreadId, |
| 4580 | runId: input.context.projectionRunId, |
| 4581 | parentNodeId: input.context.itemParentNodeId, |
| 4582 | rootNodeId: input.context.rootNodeId, |
| 4583 | kind: "plan", |
| 4584 | status: input.completed === true ? "completed" : "running", |
| 4585 | countsForRun: false, |
| 4586 | providerThreadId: input.context.providerThread.id, |
| 4587 | providerTurnId: input.context.providerTurnId, |
| 4588 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4589 | runtimeRequestId: null, |
| 4590 | checkpointScopeId: null, |
| 4591 | startedAt, |
| 4592 | completedAt, |
| 4593 | }; |
| 4594 | const turnItem: OrchestrationV2TurnItem = { |
| 4595 | id: turnItemId, |
| 4596 | threadId: input.context.projectionThreadId, |
| 4597 | runId: input.context.projectionRunId, |
| 4598 | nodeId, |
| 4599 | providerThreadId: input.context.providerThread.id, |
| 4600 | providerTurnId: input.context.providerTurnId, |
| 4601 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4602 | parentItemId: null, |
| 4603 | ordinal, |
| 4604 | status: input.completed === true ? "completed" : "running", |
| 4605 | title: null, |
| 4606 | startedAt, |
| 4607 | completedAt, |
| 4608 | updatedAt, |
| 4609 | type: "proposed_plan", |
| 4610 | planId, |
| 4611 | markdown: input.markdown, |
| 4612 | streaming: input.completed !== true, |
| 4613 | }; |
| 4614 | return { node, plan, turnItem }; |
| 4615 | }); |
| 4616 | |
| 4617 | const planDeltas = yield* makeProviderTextDeltaCoalescer({ |
| 4618 | flushIntervalMs: CODEX_PLAN_DELTA_FLUSH_INTERVAL_MS, |
| 4619 | emit: |
| 4620 | /* Provider events include streaming deltas; avoid a span for each update. */ |
| 4621 | Effect.fnUntraced(function* (update) { |
| 4622 | const resolved = yield* resolveItemEventContext(update.turnId); |
| 4623 | if (resolved === undefined) return; |
| 4624 | const interrupted = (yield* Ref.get(terminalizedNonCompletedNativeTurns)).has( |
| 4625 | update.turnId, |
| 4626 | ); |
| 4627 | const artifacts = yield* buildProposedPlanArtifacts({ |
| 4628 | context: resolved.context, |
| 4629 | nativeItemId: update.itemId, |
| 4630 | // A finished proposal stays active until Implement consumes it. |
| 4631 | status: "active", |
| 4632 | markdown: update.text, |
| 4633 | completed: update.completed && !interrupted, |
| 4634 | }); |
| 4635 | yield* emitProviderEvent({ |
| 4636 | type: "node.updated", |
| 4637 | driver: CODEX_PROVIDER, |
| 4638 | node: artifacts.node, |
| 4639 | }); |
| 4640 | yield* emitProviderEvent({ |
| 4641 | type: "plan.updated", |
| 4642 | driver: CODEX_PROVIDER, |
| 4643 | plan: artifacts.plan, |
| 4644 | }); |
| 4645 | yield* emitProviderEvent({ |
| 4646 | type: "turn_item.updated", |
| 4647 | driver: CODEX_PROVIDER, |
| 4648 | turnItem: artifacts.turnItem, |
| 4649 | }); |
| 4650 | }, Effect.orDie), |
| 4651 | }); |
| 4652 | |
| 4653 | const buildTodoListArtifacts = Effect.fn("CodexAdapterV2.buildTodoListArtifacts")( |
| 4654 | function* (input: { |
| 4655 | readonly context: ActiveCodexTurnContext; |
| 4656 | readonly nativeItemId: string; |
| 4657 | readonly status: OrchestrationV2PlanArtifact["status"]; |
| 4658 | readonly steps: ReadonlyArray<OrchestrationV2PlanStep>; |
| 4659 | readonly explanation?: string; |
| 4660 | readonly completed?: boolean; |
| 4661 | }) { |
| 4662 | const updatedAt = yield* DateTime.now; |
| 4663 | const completedAt = input.completed === true ? updatedAt : null; |
| 4664 | const planId = yield* resolvePlanId(input.context, input.nativeItemId); |
| 4665 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4666 | driver: CODEX_PROVIDER, |
| 4667 | nativeItemId: input.nativeItemId, |
| 4668 | }); |
| 4669 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4670 | driver: CODEX_PROVIDER, |
| 4671 | nativeItemId: input.nativeItemId, |
| 4672 | }); |
| 4673 | const { ordinal, startedAt } = yield* resolveItemPosition( |
| 4674 | input.context, |
| 4675 | input.nativeItemId, |
| 4676 | ); |
| 4677 | const plan: OrchestrationV2PlanArtifact = { |
| 4678 | id: planId, |
| 4679 | threadId: input.context.projectionThreadId, |
| 4680 | runId: input.context.projectionRunId, |
| 4681 | nodeId, |
| 4682 | kind: "todo_list", |
| 4683 | status: input.status, |
| 4684 | steps: [...input.steps], |
| 4685 | ...(input.explanation === undefined ? {} : { explanation: input.explanation }), |
| 4686 | }; |
| 4687 | const node: OrchestrationV2ExecutionNode = { |
| 4688 | id: nodeId, |
| 4689 | threadId: input.context.projectionThreadId, |
| 4690 | runId: input.context.projectionRunId, |
| 4691 | parentNodeId: input.context.itemParentNodeId, |
| 4692 | rootNodeId: input.context.rootNodeId, |
| 4693 | kind: "todo_list", |
| 4694 | status: input.completed === true ? "completed" : "running", |
| 4695 | countsForRun: false, |
| 4696 | providerThreadId: input.context.providerThread.id, |
| 4697 | providerTurnId: input.context.providerTurnId, |
| 4698 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4699 | runtimeRequestId: null, |
| 4700 | checkpointScopeId: null, |
| 4701 | startedAt, |
| 4702 | completedAt, |
| 4703 | }; |
| 4704 | const turnItem: OrchestrationV2TurnItem = { |
| 4705 | id: turnItemId, |
| 4706 | threadId: input.context.projectionThreadId, |
| 4707 | runId: input.context.projectionRunId, |
| 4708 | nodeId, |
| 4709 | providerThreadId: input.context.providerThread.id, |
| 4710 | providerTurnId: input.context.providerTurnId, |
| 4711 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4712 | parentItemId: null, |
| 4713 | ordinal, |
| 4714 | status: input.completed === true ? "completed" : "running", |
| 4715 | title: null, |
| 4716 | startedAt, |
| 4717 | completedAt, |
| 4718 | updatedAt, |
| 4719 | type: "todo_list", |
| 4720 | planId, |
| 4721 | steps: [...input.steps], |
| 4722 | ...(input.explanation === undefined ? {} : { explanation: input.explanation }), |
| 4723 | }; |
| 4724 | return { node, plan, turnItem }; |
| 4725 | }, |
| 4726 | ); |
| 4727 | |
| 4728 | const buildApprovalRequestArtifacts = Effect.fn( |
| 4729 | "CodexAdapterV2.buildApprovalRequestArtifacts", |
| 4730 | )(function* (input: { |
| 4731 | readonly context: ActiveCodexTurnContext; |
| 4732 | readonly nativeItemId: string; |
| 4733 | readonly nativeRequestId: string; |
| 4734 | readonly requestKind: ProviderRequestKind; |
| 4735 | readonly prompt?: string | null; |
| 4736 | readonly appName?: string; |
| 4737 | readonly options?: ReadonlyArray<ProviderApprovalOption>; |
| 4738 | }) { |
| 4739 | const createdAt = yield* DateTime.now; |
| 4740 | const { owner, subagent } = approvalOwnerCodexTurn(input.context); |
| 4741 | const parentNodeId = |
| 4742 | subagent?.subagentNodeId ?? |
| 4743 | idAllocator.derive.nodeFromProviderItem({ |
| 4744 | driver: CODEX_PROVIDER, |
| 4745 | nativeItemId: input.nativeItemId, |
| 4746 | }); |
| 4747 | const ordinal = yield* resolveItemOrdinal( |
| 4748 | owner, |
| 4749 | `${input.nativeItemId}:approval:${input.nativeRequestId}`, |
| 4750 | ); |
| 4751 | const requestId = yield* idAllocator.allocate.runtimeRequest({ |
| 4752 | driver: CODEX_PROVIDER, |
| 4753 | providerTurnId: owner.providerTurnId, |
| 4754 | nativeRequestId: input.nativeRequestId, |
| 4755 | }); |
| 4756 | const nodeId = idAllocator.derive.approvalNode({ requestId }); |
| 4757 | const providerSessionId = owner.input.providerThread.providerSessionId; |
| 4758 | if (providerSessionId === null) { |
| 4759 | return yield* toProtocolError( |
| 4760 | `Provider thread ${owner.providerThread.id} is missing a provider session id.`, |
| 4761 | ); |
| 4762 | } |
| 4763 | const node: OrchestrationV2ExecutionNode = { |
| 4764 | id: nodeId, |
| 4765 | threadId: owner.projectionThreadId, |
| 4766 | runId: owner.projectionRunId, |
| 4767 | parentNodeId, |
| 4768 | rootNodeId: owner.rootNodeId, |
| 4769 | kind: "approval_request", |
| 4770 | status: "waiting", |
| 4771 | countsForRun: false, |
| 4772 | providerThreadId: owner.providerThread.id, |
| 4773 | providerTurnId: owner.providerTurnId, |
| 4774 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4775 | runtimeRequestId: requestId, |
| 4776 | checkpointScopeId: null, |
| 4777 | startedAt: createdAt, |
| 4778 | completedAt: null, |
| 4779 | }; |
| 4780 | const request: OrchestrationV2RuntimeRequest = { |
| 4781 | id: requestId, |
| 4782 | nodeId, |
| 4783 | providerTurnId: owner.providerTurnId, |
| 4784 | nativeRequestRef: { |
| 4785 | driver: CODEX_PROVIDER, |
| 4786 | nativeId: input.nativeRequestId, |
| 4787 | strength: "strong", |
| 4788 | }, |
| 4789 | kind: input.requestKind, |
| 4790 | status: "pending", |
| 4791 | responseCapability: { |
| 4792 | type: "live", |
| 4793 | providerSessionId, |
| 4794 | }, |
| 4795 | createdAt, |
| 4796 | resolvedAt: null, |
| 4797 | }; |
| 4798 | const turnItem: OrchestrationV2TurnItem = { |
| 4799 | id: idAllocator.derive.approvalTurnItem({ requestId }), |
| 4800 | threadId: owner.projectionThreadId, |
| 4801 | runId: owner.projectionRunId, |
| 4802 | nodeId, |
| 4803 | providerThreadId: owner.providerThread.id, |
| 4804 | providerTurnId: owner.providerTurnId, |
| 4805 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4806 | parentItemId: null, |
| 4807 | ordinal, |
| 4808 | status: "waiting", |
| 4809 | title: null, |
| 4810 | startedAt: createdAt, |
| 4811 | completedAt: null, |
| 4812 | updatedAt: createdAt, |
| 4813 | type: "approval_request", |
| 4814 | requestId, |
| 4815 | requestKind: input.requestKind, |
| 4816 | ...(input.prompt === null || input.prompt === undefined |
| 4817 | ? {} |
| 4818 | : { prompt: input.prompt }), |
| 4819 | ...(input.appName === undefined ? {} : { appName: input.appName }), |
| 4820 | ...(input.options === undefined ? {} : { options: input.options }), |
| 4821 | }; |
| 4822 | return { node, request, turnItem }; |
| 4823 | }); |
| 4824 | |
| 4825 | const buildUserInputRequestArtifacts = Effect.fn( |
| 4826 | "CodexAdapterV2.buildUserInputRequestArtifacts", |
| 4827 | )(function* (input: { |
| 4828 | readonly context: ActiveCodexTurnContext; |
| 4829 | readonly nativeItemId: string; |
| 4830 | readonly nativeRequestId: string; |
| 4831 | readonly questions: ReadonlyArray<CodexSchema.ToolRequestUserInputParams__ToolRequestUserInputQuestion>; |
| 4832 | readonly responseMode?: "message"; |
| 4833 | }) { |
| 4834 | const createdAt = yield* DateTime.now; |
| 4835 | const requestId = yield* idAllocator.allocate.runtimeRequest({ |
| 4836 | driver: CODEX_PROVIDER, |
| 4837 | providerTurnId: input.context.providerTurnId, |
| 4838 | nativeRequestId: input.nativeRequestId, |
| 4839 | }); |
| 4840 | const providerSessionId = input.context.input.providerThread.providerSessionId; |
| 4841 | if (providerSessionId === null) { |
| 4842 | return yield* toProtocolError( |
| 4843 | `Provider thread ${input.context.providerThread.id} is missing a provider session id.`, |
| 4844 | ); |
| 4845 | } |
| 4846 | const nativeQuestionIds = new Map( |
| 4847 | input.questions.map((question, index) => [ |
| 4848 | nonEmptyText(question.id, `question-${index + 1}`), |
| 4849 | question.id, |
| 4850 | ]), |
| 4851 | ); |
| 4852 | const questions = input.questions.map((question, index) => ({ |
| 4853 | id: nonEmptyText(question.id, `question-${index + 1}`), |
| 4854 | header: nonEmptyText(question.header, "Question"), |
| 4855 | question: nonEmptyText(question.question, "Choose an answer."), |
| 4856 | options: |
| 4857 | question.options?.map((option, optionIndex) => ({ |
| 4858 | label: nonEmptyText(option.label, `Option ${optionIndex + 1}`), |
| 4859 | description: nonEmptyText(option.description, option.label), |
| 4860 | })) ?? [], |
| 4861 | })); |
| 4862 | const nodeId = idAllocator.derive.nodeFromProviderItem({ |
| 4863 | driver: CODEX_PROVIDER, |
| 4864 | nativeItemId: input.nativeItemId, |
| 4865 | }); |
| 4866 | const turnItemId = idAllocator.derive.turnItemFromProviderItem({ |
| 4867 | driver: CODEX_PROVIDER, |
| 4868 | nativeItemId: input.nativeItemId, |
| 4869 | }); |
| 4870 | const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); |
| 4871 | const node: OrchestrationV2ExecutionNode = { |
| 4872 | id: nodeId, |
| 4873 | threadId: input.context.projectionThreadId, |
| 4874 | runId: input.context.projectionRunId, |
| 4875 | parentNodeId: input.context.itemParentNodeId, |
| 4876 | rootNodeId: input.context.rootNodeId, |
| 4877 | kind: "user_input_request", |
| 4878 | status: "waiting", |
| 4879 | countsForRun: false, |
| 4880 | providerThreadId: input.context.providerThread.id, |
| 4881 | providerTurnId: input.context.providerTurnId, |
| 4882 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4883 | runtimeRequestId: requestId, |
| 4884 | checkpointScopeId: null, |
| 4885 | startedAt: createdAt, |
| 4886 | completedAt: null, |
| 4887 | }; |
| 4888 | const request: OrchestrationV2RuntimeRequest = { |
| 4889 | id: requestId, |
| 4890 | nodeId, |
| 4891 | providerTurnId: input.context.providerTurnId, |
| 4892 | nativeRequestRef: { |
| 4893 | driver: CODEX_PROVIDER, |
| 4894 | nativeId: input.nativeRequestId, |
| 4895 | strength: "strong", |
| 4896 | }, |
| 4897 | kind: "user_input", |
| 4898 | status: "pending", |
| 4899 | responseCapability: |
| 4900 | input.responseMode === "message" |
| 4901 | ? { type: "message" } |
| 4902 | : { type: "live", providerSessionId }, |
| 4903 | createdAt, |
| 4904 | resolvedAt: null, |
| 4905 | }; |
| 4906 | const turnItem: OrchestrationV2TurnItem = { |
| 4907 | id: turnItemId, |
| 4908 | threadId: input.context.projectionThreadId, |
| 4909 | runId: input.context.projectionRunId, |
| 4910 | nodeId, |
| 4911 | providerThreadId: input.context.providerThread.id, |
| 4912 | providerTurnId: input.context.providerTurnId, |
| 4913 | nativeItemRef: codexNativeItemRef(input.nativeItemId), |
| 4914 | parentItemId: null, |
| 4915 | ordinal, |
| 4916 | status: "waiting", |
| 4917 | title: null, |
| 4918 | startedAt: createdAt, |
| 4919 | completedAt: null, |
| 4920 | updatedAt: createdAt, |
| 4921 | type: "user_input_request", |
| 4922 | requestId, |
| 4923 | questions, |
| 4924 | ...(input.responseMode === undefined ? {} : { responseMode: input.responseMode }), |
| 4925 | }; |
| 4926 | return { node, request, turnItem, nativeQuestionIds }; |
| 4927 | }); |
| 4928 | |
| 4929 | yield* client.handleServerNotification("item/agentMessage/delta", (payload) => |
| 4930 | Effect.gen(function* () { |
| 4931 | const context = (yield* Ref.get(activeTurns)).get(payload.turnId); |
| 4932 | if (context !== undefined) { |
| 4933 | yield* completeProviderRetry(context, yield* DateTime.now); |
| 4934 | } |
| 4935 | yield* agentMessageDeltas.append({ |
| 4936 | turnId: payload.turnId, |
| 4937 | itemId: payload.itemId, |
| 4938 | delta: payload.delta, |
| 4939 | }); |
| 4940 | }), |
| 4941 | ); |
| 4942 | |
| 4943 | yield* client.handleServerNotification("item/commandExecution/outputDelta", (payload) => |
| 4944 | Effect.gen(function* () { |
| 4945 | // Background commands emit deltas after settlement; item/started already registered their turn. |
| 4946 | const context = |
| 4947 | (yield* Ref.get(activeTurns)).get(payload.turnId) ?? |
| 4948 | (yield* Ref.get(settledTurns)).get(payload.turnId); |
| 4949 | if (context === undefined) return; |
| 4950 | yield* emitProviderEvent({ |
| 4951 | type: "command_output.delta", |
| 4952 | driver: CODEX_PROVIDER, |
| 4953 | threadId: context.projectionThreadId, |
| 4954 | itemId: idAllocator.derive.turnItemFromProviderItem({ |
| 4955 | driver: CODEX_PROVIDER, |
| 4956 | nativeItemId: payload.itemId, |
| 4957 | }), |
| 4958 | chunk: payload.delta, |
| 4959 | }); |
| 4960 | }), |
| 4961 | ); |
| 4962 | |
| 4963 | yield* client.handleServerNotification("item/reasoning/summaryTextDelta", (payload) => |
| 4964 | appendReasoning(payload, "summary", payload.summaryIndex), |
| 4965 | ); |
| 4966 | yield* client.handleServerNotification("item/reasoning/textDelta", (payload) => |
| 4967 | appendReasoning(payload, "content", payload.contentIndex), |
| 4968 | ); |
| 4969 | |
| 4970 | yield* client.handleServerNotification("item/plan/delta", (payload) => |
| 4971 | Effect.gen(function* () { |
| 4972 | const context = yield* awaitActiveTurn(payload.turnId); |
| 4973 | if (context === undefined) { |
| 4974 | return; |
| 4975 | } |
| 4976 | yield* completeProviderRetry(context, yield* DateTime.now); |
| 4977 | yield* planDeltas.append({ |
| 4978 | turnId: payload.turnId, |
| 4979 | itemId: payload.itemId, |
| 4980 | delta: payload.delta, |
| 4981 | }); |
| 4982 | }).pipe(Effect.orDie), |
| 4983 | ); |
| 4984 | |
| 4985 | yield* client.handleServerNotification("turn/plan/updated", (payload) => |
| 4986 | Effect.gen(function* () { |
| 4987 | const context = yield* awaitActiveTurn(payload.turnId); |
| 4988 | if (context === undefined) { |
| 4989 | return; |
| 4990 | } |
| 4991 | yield* completeProviderRetry(context, yield* DateTime.now); |
| 4992 | const steps = payload.plan.map((step, index) => ({ |
| 4993 | id: `step-${index + 1}`, |
| 4994 | text: nonEmptyText(step.step, `Step ${index + 1}`), |
| 4995 | status: codexPlanStepStatus(step.status), |
| 4996 | })); |
| 4997 | const explanation = trimText(payload.explanation); |
| 4998 | const artifacts = yield* buildTodoListArtifacts({ |
| 4999 | context, |
| 5000 | nativeItemId: `turn-plan:${payload.turnId}`, |
Showing first 5,000 of 9,269 lines.
View raw