The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { ClaudeSettings } from "@t3tools/contracts"; |
| 2 | import { |
| 3 | forkSession, |
| 4 | query, |
| 5 | type CanUseTool, |
| 6 | type PermissionResult, |
| 7 | type SDKAssistantMessage, |
| 8 | type SDKMessage, |
| 9 | type SDKUserMessage, |
| 10 | } from "@anthropic-ai/claude-agent-sdk"; |
| 11 | import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; |
| 12 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 13 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 14 | import { SpawnExecutableResolution } from "@t3tools/shared/shell"; |
| 15 | import { |
| 16 | ProviderReplayEntry, |
| 17 | type ModelSelection, |
| 18 | type ProviderApprovalDecision, |
| 19 | type ProviderReplayTranscript, |
| 20 | } from "@t3tools/contracts"; |
| 21 | import * as Cause from "effect/Cause"; |
| 22 | import * as SecureRandom from "effect/crypto/SecureRandom"; |
| 23 | import * as Duration from "effect/Duration"; |
| 24 | import * as Effect from "effect/Effect"; |
| 25 | import * as Exit from "effect/Exit"; |
| 26 | import * as FileSystem from "effect/FileSystem"; |
| 27 | import * as Layer from "effect/Layer"; |
| 28 | import * as Path from "effect/Path"; |
| 29 | import * as Schema from "effect/Schema"; |
| 30 | import * as Stream from "effect/Stream"; |
| 31 | |
| 32 | import * as ServerConfig from "../../config.ts"; |
| 33 | import { |
| 34 | isWindowsClaudeLauncherShimPath, |
| 35 | resolveClaudeSdkExecutablePath, |
| 36 | } from "../../provider/Drivers/ClaudeExecutable.ts"; |
| 37 | import * as ClaudeAdapterV2 from "./ClaudeAdapterV2.ts"; |
| 38 | import { claudeTaskOutputRoot } from "./ClaudeTaskOutputTail.ts"; |
| 39 | import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; |
| 40 | import * as ProviderInstallationGate from "../../provider/ProviderInstallationGate.ts"; |
| 41 | import { ProviderAdapterDriverCreateError } from "@t3tools/provider-core/server/adapterDriver"; |
| 42 | import * as ProviderAdapterRegistry from "../ProviderAdapterRegistry.ts"; |
| 43 | import { randomUuidV4 } from "@t3tools/provider-core/server/randomUuid"; |
| 44 | import { |
| 45 | makeReplayServerConfig, |
| 46 | type OrchestratorV2ProviderReplayHarness, |
| 47 | } from "../testkit/ProviderReplayHarness.ts"; |
| 48 | import type { ProviderReplayGate } from "@t3tools/provider-testing/replayGate"; |
| 49 | |
| 50 | export const CLAUDE_AGENT_SDK_REPLAY_PROTOCOL = "claude-agent-sdk.query" as const; |
| 51 | export const claudeBackgroundWakeResultLabel = (wakeNumber: number) => |
| 52 | `result:background-wake:${wakeNumber}`; |
| 53 | |
| 54 | const DEFAULT_CLAUDE_SETTINGS = Schema.decodeSync(ClaudeSettings)({}); |
| 55 | |
| 56 | const ClaudeAgentSdkReplayTranscript = Schema.Struct({ |
| 57 | provider: Schema.Literal(ClaudeAdapterV2.CLAUDE_PROVIDER), |
| 58 | protocol: Schema.Literal(CLAUDE_AGENT_SDK_REPLAY_PROTOCOL), |
| 59 | version: Schema.String, |
| 60 | scenario: Schema.String, |
| 61 | metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)), |
| 62 | entries: Schema.Array(ProviderReplayEntry), |
| 63 | }); |
| 64 | type ClaudeAgentSdkReplayTranscript = typeof ClaudeAgentSdkReplayTranscript.Type; |
| 65 | |
| 66 | export class ClaudeReplayTranscriptDecodeError extends Schema.TaggedError<ClaudeReplayTranscriptDecodeError>()( |
| 67 | "ClaudeReplayTranscriptDecodeError", |
| 68 | { |
| 69 | driver: Schema.optional(Schema.String), |
| 70 | protocol: Schema.optional(Schema.String), |
| 71 | scenario: Schema.optional(Schema.String), |
| 72 | cause: Schema.Defect(), |
| 73 | }, |
| 74 | ) { |
| 75 | override get message(): string { |
| 76 | return `Failed to decode Claude Agent SDK replay transcript for scenario ${this.scenario ?? "<unknown>"}.`; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | export class ClaudeReplayExhaustedError extends Schema.TaggedError<ClaudeReplayExhaustedError>()( |
| 81 | "ClaudeReplayExhaustedError", |
| 82 | { |
| 83 | scenario: Schema.String, |
| 84 | cursor: Schema.Number, |
| 85 | actual: Schema.Unknown, |
| 86 | }, |
| 87 | ) { |
| 88 | override get message(): string { |
| 89 | return `Claude Agent SDK replay transcript exhausted before outbound frame ${this.cursor} in scenario ${this.scenario}.`; |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | export class ClaudeReplayUnexpectedOutboundError extends Schema.TaggedError<ClaudeReplayUnexpectedOutboundError>()( |
| 94 | "ClaudeReplayUnexpectedOutboundError", |
| 95 | { |
| 96 | scenario: Schema.String, |
| 97 | cursor: Schema.Number, |
| 98 | expectedType: Schema.String, |
| 99 | actual: Schema.Unknown, |
| 100 | }, |
| 101 | ) { |
| 102 | override get message(): string { |
| 103 | return `Unexpected outbound Claude Agent SDK frame at replay cursor ${this.cursor} in scenario ${this.scenario}.`; |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | export class ClaudeReplayFrameMismatchError extends Schema.TaggedError<ClaudeReplayFrameMismatchError>()( |
| 108 | "ClaudeReplayFrameMismatchError", |
| 109 | { |
| 110 | scenario: Schema.String, |
| 111 | cursor: Schema.Number, |
| 112 | label: Schema.optional(Schema.String), |
| 113 | expected: Schema.Unknown, |
| 114 | actual: Schema.Unknown, |
| 115 | }, |
| 116 | ) { |
| 117 | override get message(): string { |
| 118 | return `Outbound Claude Agent SDK frame did not match replay cursor ${this.cursor} in scenario ${this.scenario}.`; |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | export class ClaudeReplayRuntimeExitError extends Schema.TaggedError<ClaudeReplayRuntimeExitError>()( |
| 123 | "ClaudeReplayRuntimeExitError", |
| 124 | { |
| 125 | scenario: Schema.String, |
| 126 | cursor: Schema.Number, |
| 127 | status: Schema.Literals(["error", "cancelled"]), |
| 128 | error: Schema.optional(Schema.Unknown), |
| 129 | }, |
| 130 | ) { |
| 131 | override get message(): string { |
| 132 | return `Claude Agent SDK replay exited with status ${this.status} at cursor ${this.cursor} in scenario ${this.scenario}.`; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | export class ClaudeReplayIncompleteError extends Schema.TaggedError<ClaudeReplayIncompleteError>()( |
| 137 | "ClaudeReplayIncompleteError", |
| 138 | { |
| 139 | scenario: Schema.String, |
| 140 | cursor: Schema.Number, |
| 141 | remaining: Schema.Number, |
| 142 | }, |
| 143 | ) { |
| 144 | override get message(): string { |
| 145 | return `Claude Agent SDK replay ended with ${this.remaining} unconsumed entries in scenario ${this.scenario}.`; |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | export class ClaudeReplayDriverError extends Schema.TaggedError<ClaudeReplayDriverError>()( |
| 150 | "ClaudeReplayDriverError", |
| 151 | { |
| 152 | scenario: Schema.String, |
| 153 | cause: Schema.Defect(), |
| 154 | }, |
| 155 | ) { |
| 156 | override get message(): string { |
| 157 | return `Claude Agent SDK replay driver failed in scenario ${this.scenario}.`; |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | export const ClaudeAgentSdkReplayError = Schema.Union([ |
| 162 | ClaudeReplayTranscriptDecodeError, |
| 163 | ClaudeReplayExhaustedError, |
| 164 | ClaudeReplayUnexpectedOutboundError, |
| 165 | ClaudeReplayFrameMismatchError, |
| 166 | ClaudeReplayRuntimeExitError, |
| 167 | ClaudeReplayIncompleteError, |
| 168 | ClaudeReplayDriverError, |
| 169 | ]); |
| 170 | export type ClaudeAgentSdkReplayError = typeof ClaudeAgentSdkReplayError.Type; |
| 171 | export const ClaudeOrchestratorReplayHarnessError = Schema.Union([ |
| 172 | ClaudeAgentSdkReplayError, |
| 173 | ProviderAdapterDriverCreateError, |
| 174 | ]); |
| 175 | export type ClaudeOrchestratorReplayHarnessError = typeof ClaudeOrchestratorReplayHarnessError.Type; |
| 176 | |
| 177 | interface ClaudeQueryOpenFrame { |
| 178 | readonly type: "query.open"; |
| 179 | readonly options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions; |
| 180 | } |
| 181 | |
| 182 | interface ClaudePromptOfferFrame { |
| 183 | readonly type: "prompt.offer"; |
| 184 | readonly message: SDKUserMessage; |
| 185 | } |
| 186 | |
| 187 | interface ClaudeQuerySetModelFrame { |
| 188 | readonly type: "query.set_model"; |
| 189 | readonly model: string; |
| 190 | } |
| 191 | |
| 192 | interface ClaudeQuerySetPermissionModeFrame { |
| 193 | readonly type: "query.set_permission_mode"; |
| 194 | readonly mode: string; |
| 195 | } |
| 196 | |
| 197 | interface ClaudeQueryInterruptFrame { |
| 198 | readonly type: "query.interrupt"; |
| 199 | } |
| 200 | |
| 201 | interface ClaudePermissionRequestFrame { |
| 202 | readonly type: "permission.request"; |
| 203 | readonly toolName: string; |
| 204 | readonly input: Record<string, unknown>; |
| 205 | readonly options: { |
| 206 | readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"]; |
| 207 | readonly blockedPath?: string; |
| 208 | readonly decisionReason?: string; |
| 209 | readonly title?: string; |
| 210 | readonly displayName?: string; |
| 211 | readonly description?: string; |
| 212 | readonly toolUseID: string; |
| 213 | readonly agentID?: string; |
| 214 | }; |
| 215 | } |
| 216 | |
| 217 | interface ClaudePermissionResponseFrame { |
| 218 | readonly type: "permission.response"; |
| 219 | readonly result: PermissionResult; |
| 220 | } |
| 221 | |
| 222 | interface ClaudeSessionForkFrame { |
| 223 | readonly type: "session.fork"; |
| 224 | readonly sessionId: string; |
| 225 | readonly options: { |
| 226 | readonly dir?: string; |
| 227 | readonly upToMessageId?: string; |
| 228 | readonly title?: string; |
| 229 | }; |
| 230 | } |
| 231 | |
| 232 | interface ClaudeSessionForkedFrame { |
| 233 | readonly type: "session.forked"; |
| 234 | readonly sessionId: string; |
| 235 | } |
| 236 | |
| 237 | interface ClaudeSubagentLookupFrame { |
| 238 | readonly type: "subagent.lookup"; |
| 239 | readonly sessionId: string; |
| 240 | readonly agentId: string; |
| 241 | } |
| 242 | |
| 243 | interface ClaudeSubagentFoundFrame { |
| 244 | readonly type: "subagent.found"; |
| 245 | readonly toolUseId: string | null; |
| 246 | } |
| 247 | |
| 248 | type ClaudeOutboundFrame = |
| 249 | | { readonly type: "query.stop_task"; readonly taskId: string } |
| 250 | | { readonly type: "query.background_tasks"; readonly toolUseId: string } |
| 251 | | ClaudeQueryOpenFrame |
| 252 | | ClaudePromptOfferFrame |
| 253 | | ClaudeQuerySetModelFrame |
| 254 | | { |
| 255 | readonly type: "query.apply_flag_settings"; |
| 256 | readonly settings: Parameters< |
| 257 | ClaudeAdapterV2.ClaudeAgentSdkQuerySession["applyFlagSettings"] |
| 258 | >[0]; |
| 259 | } |
| 260 | | ClaudeQuerySetPermissionModeFrame |
| 261 | | ClaudeQueryInterruptFrame |
| 262 | | ClaudePermissionResponseFrame |
| 263 | | ClaudeSessionForkFrame |
| 264 | | ClaudeSubagentLookupFrame; |
| 265 | |
| 266 | interface ClaudeQueryRunner { |
| 267 | readonly open: ( |
| 268 | input: ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput, |
| 269 | ) => ClaudeAdapterV2.ClaudeAgentSdkQuerySession; |
| 270 | readonly forkSession: ( |
| 271 | input: ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput, |
| 272 | ) => ClaudeSessionForkedFrame; |
| 273 | readonly subagentLaunchToolUseId: ( |
| 274 | input: ClaudeAdapterV2.ClaudeAgentSdkSubagentLookupInput, |
| 275 | ) => string | null; |
| 276 | readonly assertComplete: () => void; |
| 277 | } |
| 278 | |
| 279 | function stableStringify(value: unknown): string { |
| 280 | if (Array.isArray(value)) { |
| 281 | return `[${value.map(stableStringify).join(",")}]`; |
| 282 | } |
| 283 | if (typeof value === "object" && value !== null) { |
| 284 | const record = value as Record<string, unknown>; |
| 285 | return `{${Object.keys(record) |
| 286 | .toSorted() |
| 287 | .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`) |
| 288 | .join(",")}}`; |
| 289 | } |
| 290 | return JSON.stringify(value); |
| 291 | } |
| 292 | |
| 293 | function normalizeContextHandoffText(value: string): string { |
| 294 | if (!value.startsWith("Context handoff (")) { |
| 295 | return value; |
| 296 | } |
| 297 | const userMessageMarker = "\n\nUser message:\n"; |
| 298 | const userMessageIndex = value.indexOf(userMessageMarker); |
| 299 | const headerEndIndex = value.indexOf(":\n"); |
| 300 | if (headerEndIndex === -1 || userMessageIndex === -1 || headerEndIndex >= userMessageIndex) { |
| 301 | return value; |
| 302 | } |
| 303 | return `${value.slice(0, headerEndIndex + 2)}<dynamic-summary>${value.slice(userMessageIndex)}`; |
| 304 | } |
| 305 | |
| 306 | function normalizeReplayFrame(value: unknown): unknown { |
| 307 | if (typeof value === "string") { |
| 308 | return normalizeContextHandoffText(value); |
| 309 | } |
| 310 | if (Array.isArray(value)) { |
| 311 | return value.map(normalizeReplayFrame); |
| 312 | } |
| 313 | if (typeof value !== "object" || value === null) { |
| 314 | return value; |
| 315 | } |
| 316 | return Object.fromEntries( |
| 317 | Object.entries(value).map(([key, entry]) => [key, normalizeReplayFrame(entry)]), |
| 318 | ); |
| 319 | } |
| 320 | |
| 321 | function sameFrame(left: unknown, right: unknown): boolean { |
| 322 | return ( |
| 323 | stableStringify(normalizeReplayFrame(left)) === stableStringify(normalizeReplayFrame(right)) |
| 324 | ); |
| 325 | } |
| 326 | |
| 327 | function isClaudeSdkReplayMessage(frame: unknown): frame is SDKMessage { |
| 328 | if (typeof frame !== "object" || frame === null) { |
| 329 | return false; |
| 330 | } |
| 331 | const type = Reflect.get(frame, "type"); |
| 332 | return ( |
| 333 | type === "assistant" || |
| 334 | type === "user" || |
| 335 | type === "result" || |
| 336 | type === "system" || |
| 337 | type === "stream_event" || |
| 338 | type === "rate_limit_event" || |
| 339 | // The SDK types omit command_lifecycle for prompt uuids. |
| 340 | type === "command_lifecycle" |
| 341 | ); |
| 342 | } |
| 343 | |
| 344 | function sdkMessageFromReplayFrame(frame: unknown): SDKMessage { |
| 345 | if (!isClaudeSdkReplayMessage(frame)) { |
| 346 | throw new Error("Replay frame is not a Claude Agent SDK message."); |
| 347 | } |
| 348 | return frame; |
| 349 | } |
| 350 | |
| 351 | function isClaudePermissionRequestFrame(frame: unknown): frame is ClaudePermissionRequestFrame { |
| 352 | const options = |
| 353 | typeof frame === "object" && frame !== null ? Reflect.get(frame, "options") : undefined; |
| 354 | return ( |
| 355 | typeof frame === "object" && |
| 356 | frame !== null && |
| 357 | Reflect.get(frame, "type") === "permission.request" && |
| 358 | typeof Reflect.get(frame, "toolName") === "string" && |
| 359 | typeof Reflect.get(frame, "input") === "object" && |
| 360 | Reflect.get(frame, "input") !== null && |
| 361 | typeof options === "object" && |
| 362 | options !== null && |
| 363 | typeof Reflect.get(options, "toolUseID") === "string" |
| 364 | ); |
| 365 | } |
| 366 | |
| 367 | function makeClaudePermissionResponseFrame( |
| 368 | result: PermissionResult, |
| 369 | ): ClaudePermissionResponseFrame { |
| 370 | return { |
| 371 | type: "permission.response", |
| 372 | result, |
| 373 | }; |
| 374 | } |
| 375 | |
| 376 | function permissionRequestOptionsFromFrame( |
| 377 | frame: ClaudePermissionRequestFrame, |
| 378 | signal: AbortSignal, |
| 379 | ): Parameters<CanUseTool>[2] { |
| 380 | const options = frame.options; |
| 381 | return { |
| 382 | signal, |
| 383 | ...(options.suggestions === undefined ? {} : { suggestions: options.suggestions }), |
| 384 | ...(options.blockedPath === undefined ? {} : { blockedPath: options.blockedPath }), |
| 385 | ...(options.decisionReason === undefined ? {} : { decisionReason: options.decisionReason }), |
| 386 | ...(options.title === undefined ? {} : { title: options.title }), |
| 387 | ...(options.displayName === undefined ? {} : { displayName: options.displayName }), |
| 388 | ...(options.description === undefined ? {} : { description: options.description }), |
| 389 | toolUseID: options.toolUseID, |
| 390 | ...(options.agentID === undefined ? {} : { agentID: options.agentID }), |
| 391 | requestId: options.toolUseID, |
| 392 | }; |
| 393 | } |
| 394 | |
| 395 | function unresolvedCursorSignal(): void {} |
| 396 | |
| 397 | function makeCursorSignal(): { |
| 398 | readonly promise: Promise<void>; |
| 399 | readonly resolve: () => void; |
| 400 | } { |
| 401 | let resolve: () => void = unresolvedCursorSignal; |
| 402 | const promise = new Promise<void>((onResolve) => { |
| 403 | resolve = onResolve; |
| 404 | }); |
| 405 | return { promise, resolve }; |
| 406 | } |
| 407 | |
| 408 | function waitForCursorAdvance(promise: Promise<void>, signal: AbortSignal): Promise<void> { |
| 409 | if (signal.aborted) { |
| 410 | return Promise.resolve(); |
| 411 | } |
| 412 | return new Promise<void>((resolve) => { |
| 413 | let waiting = true; |
| 414 | const finish = () => { |
| 415 | if (!waiting) { |
| 416 | return; |
| 417 | } |
| 418 | waiting = false; |
| 419 | signal.removeEventListener("abort", finish); |
| 420 | resolve(); |
| 421 | }; |
| 422 | signal.addEventListener("abort", finish, { once: true }); |
| 423 | void promise.then(finish); |
| 424 | if (signal.aborted) { |
| 425 | finish(); |
| 426 | } |
| 427 | }); |
| 428 | } |
| 429 | |
| 430 | async function waitForReplayDelay(afterMs: number, signal: AbortSignal): Promise<void> { |
| 431 | const exit = await Effect.runPromiseExit(Effect.sleep(Duration.millis(afterMs)), { signal }); |
| 432 | if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) { |
| 433 | throw Cause.squash(exit.cause); |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | function stableClaudeQueryOptions( |
| 438 | options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions, |
| 439 | ): ClaudeAdapterV2.ClaudeAgentSdkQueryOptions { |
| 440 | const stable = { |
| 441 | model: options.model, |
| 442 | tools: options.tools, |
| 443 | permissionMode: options.permissionMode, |
| 444 | ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }), |
| 445 | ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }), |
| 446 | ...(options.settings === undefined ? {} : { settings: options.settings }), |
| 447 | ...(options.allowDangerouslySkipPermissions === true |
| 448 | ? { allowDangerouslySkipPermissions: true } |
| 449 | : {}), |
| 450 | ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }), |
| 451 | ...(options.forkSession === true ? { forkSession: true } : {}), |
| 452 | }; |
| 453 | return options.resume === undefined |
| 454 | ? { ...stable, sessionId: options.sessionId } |
| 455 | : { ...stable, resume: options.resume }; |
| 456 | } |
| 457 | |
| 458 | function makeClaudeQueryOpenFrame( |
| 459 | input: Pick<ClaudeAdapterV2.ClaudeAgentSdkQueryOpenInput, "options">, |
| 460 | ): ClaudeQueryOpenFrame { |
| 461 | return { |
| 462 | type: "query.open", |
| 463 | options: stableClaudeQueryOptions(input.options), |
| 464 | }; |
| 465 | } |
| 466 | |
| 467 | function makeClaudePromptOfferFrame(message: SDKUserMessage): ClaudePromptOfferFrame { |
| 468 | return { |
| 469 | type: "prompt.offer", |
| 470 | message, |
| 471 | }; |
| 472 | } |
| 473 | |
| 474 | function makeClaudeSessionForkFrame( |
| 475 | input: ClaudeAdapterV2.ClaudeAgentSdkSessionForkInput, |
| 476 | scenario: string, |
| 477 | ): ClaudeSessionForkFrame { |
| 478 | return { |
| 479 | type: "session.fork", |
| 480 | sessionId: input.sessionId, |
| 481 | options: { |
| 482 | ...(input.options.dir === undefined ? {} : { dir: sanitizedReplayCwd(scenario) }), |
| 483 | ...(input.options.upToMessageId === undefined |
| 484 | ? {} |
| 485 | : { upToMessageId: input.options.upToMessageId }), |
| 486 | ...(input.options.title === undefined ? {} : { title: input.options.title }), |
| 487 | }, |
| 488 | }; |
| 489 | } |
| 490 | |
| 491 | function makeReplayQueryRunner( |
| 492 | transcript: ClaudeAgentSdkReplayTranscript, |
| 493 | replayOptions: { readonly replayGate?: ProviderReplayGate } = {}, |
| 494 | ): ClaudeQueryRunner { |
| 495 | let cursor = 0; |
| 496 | let failure: ClaudeAgentSdkReplayError | null = null; |
| 497 | let cursorAdvanced = makeCursorSignal(); |
| 498 | const iteratorAbortControllers = new Set<AbortController>(); |
| 499 | |
| 500 | const abortReplayIterators = () => { |
| 501 | for (const abortController of iteratorAbortControllers) { |
| 502 | abortController.abort(); |
| 503 | } |
| 504 | }; |
| 505 | |
| 506 | const fail = (error: ClaudeAgentSdkReplayError): never => { |
| 507 | failure = error; |
| 508 | abortReplayIterators(); |
| 509 | replayOptions.replayGate?.releaseAll(); |
| 510 | cursorAdvanced.resolve(); |
| 511 | throw error; |
| 512 | }; |
| 513 | |
| 514 | const throwIfFailed = () => { |
| 515 | if (failure !== null) { |
| 516 | throw failure; |
| 517 | } |
| 518 | }; |
| 519 | |
| 520 | const advance = () => { |
| 521 | cursor += 1; |
| 522 | const signal = cursorAdvanced; |
| 523 | cursorAdvanced = makeCursorSignal(); |
| 524 | signal.resolve(); |
| 525 | }; |
| 526 | |
| 527 | async function* replayMessages( |
| 528 | options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions, |
| 529 | signal: AbortSignal, |
| 530 | ): AsyncGenerator<SDKMessage, void> { |
| 531 | while (true) { |
| 532 | throwIfFailed(); |
| 533 | |
| 534 | const entry = transcript.entries[cursor]; |
| 535 | if (entry === undefined) { |
| 536 | return; |
| 537 | } |
| 538 | |
| 539 | if (entry.type === "emit_inbound") { |
| 540 | if (replayOptions.replayGate !== undefined) { |
| 541 | await replayOptions.replayGate.beforeEmit(entry.label, signal); |
| 542 | throwIfFailed(); |
| 543 | if (signal.aborted) { |
| 544 | return; |
| 545 | } |
| 546 | } |
| 547 | if (entry.afterMs !== undefined && entry.afterMs > 0) { |
| 548 | await waitForReplayDelay(entry.afterMs, signal); |
| 549 | throwIfFailed(); |
| 550 | if (signal.aborted) { |
| 551 | return; |
| 552 | } |
| 553 | } |
| 554 | if (isClaudePermissionRequestFrame(entry.frame)) { |
| 555 | const request = entry.frame; |
| 556 | const invokeCanUseTool = options.canUseTool; |
| 557 | if (invokeCanUseTool === undefined) { |
| 558 | const error = new ClaudeReplayUnexpectedOutboundError({ |
| 559 | scenario: transcript.scenario, |
| 560 | cursor, |
| 561 | expectedType: "permission.request", |
| 562 | actual: request, |
| 563 | }); |
| 564 | return fail(error); |
| 565 | } |
| 566 | advance(); |
| 567 | let result: PermissionResult | null; |
| 568 | try { |
| 569 | result = await invokeCanUseTool( |
| 570 | request.toolName, |
| 571 | request.input, |
| 572 | permissionRequestOptionsFromFrame(request, signal), |
| 573 | ); |
| 574 | } catch (cause) { |
| 575 | throwIfFailed(); |
| 576 | if (signal.aborted) { |
| 577 | return; |
| 578 | } |
| 579 | throw cause; |
| 580 | } |
| 581 | throwIfFailed(); |
| 582 | if (signal.aborted) { |
| 583 | return; |
| 584 | } |
| 585 | if (result === null) { |
| 586 | const error = new ClaudeReplayUnexpectedOutboundError({ |
| 587 | scenario: transcript.scenario, |
| 588 | cursor, |
| 589 | expectedType: "permission.response", |
| 590 | actual: null, |
| 591 | }); |
| 592 | return fail(error); |
| 593 | } |
| 594 | assertNextOutboundFrame(makeClaudePermissionResponseFrame(result)); |
| 595 | continue; |
| 596 | } |
| 597 | advance(); |
| 598 | yield sdkMessageFromReplayFrame(withReplayedPromptUuids(entry.frame)); |
| 599 | continue; |
| 600 | } |
| 601 | |
| 602 | if (entry.type === "runtime_exit") { |
| 603 | advance(); |
| 604 | if (entry.status === "success") { |
| 605 | return; |
| 606 | } |
| 607 | fail( |
| 608 | new ClaudeReplayRuntimeExitError({ |
| 609 | scenario: transcript.scenario, |
| 610 | cursor: cursor - 1, |
| 611 | status: entry.status, |
| 612 | ...(entry.error === undefined ? {} : { error: entry.error }), |
| 613 | }), |
| 614 | ); |
| 615 | } |
| 616 | |
| 617 | if (entry.type === "expect_outbound") { |
| 618 | await waitForCursorAdvance(cursorAdvanced.promise, signal); |
| 619 | throwIfFailed(); |
| 620 | if (signal.aborted) { |
| 621 | return; |
| 622 | } |
| 623 | continue; |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | const replayMessagesWithGateCleanup = ( |
| 629 | options: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions, |
| 630 | ): AsyncIterable<SDKMessage> => ({ |
| 631 | [Symbol.asyncIterator]: () => { |
| 632 | const abortController = new AbortController(); |
| 633 | iteratorAbortControllers.add(abortController); |
| 634 | const iterator = replayMessages(options, abortController.signal); |
| 635 | return { |
| 636 | next: async () => { |
| 637 | try { |
| 638 | const result = await iterator.next(); |
| 639 | if (result.done) { |
| 640 | iteratorAbortControllers.delete(abortController); |
| 641 | } |
| 642 | return result; |
| 643 | } catch (cause) { |
| 644 | iteratorAbortControllers.delete(abortController); |
| 645 | throw cause; |
| 646 | } |
| 647 | }, |
| 648 | return: async () => { |
| 649 | abortController.abort(); |
| 650 | replayOptions.replayGate?.releaseAll(); |
| 651 | try { |
| 652 | return await iterator.return(); |
| 653 | } finally { |
| 654 | iteratorAbortControllers.delete(abortController); |
| 655 | } |
| 656 | }, |
| 657 | }; |
| 658 | }, |
| 659 | }); |
| 660 | |
| 661 | // Prompt uuids differ on replay; rewrite inbound echoes and acknowledgements to match. |
| 662 | const promptUuidReplacements = new Map<string, string>(); |
| 663 | const replayedPromptUuid = (value: string): string => promptUuidReplacements.get(value) ?? value; |
| 664 | const withReplayedPromptUuids = (frame: unknown): unknown => { |
| 665 | if (promptUuidReplacements.size === 0 || typeof frame !== "object" || frame === null) { |
| 666 | return frame; |
| 667 | } |
| 668 | const uuid: unknown = Reflect.get(frame, "user_message_uuid"); |
| 669 | const uuids: unknown = Reflect.get(frame, "user_message_uuids"); |
| 670 | const commandUuid: unknown = Reflect.get(frame, "command_uuid"); |
| 671 | if (typeof uuid !== "string" && !Array.isArray(uuids) && typeof commandUuid !== "string") { |
| 672 | return frame; |
| 673 | } |
| 674 | return { |
| 675 | ...frame, |
| 676 | ...(typeof commandUuid === "string" ? { command_uuid: replayedPromptUuid(commandUuid) } : {}), |
| 677 | ...(typeof uuid === "string" ? { user_message_uuid: replayedPromptUuid(uuid) } : {}), |
| 678 | ...(Array.isArray(uuids) |
| 679 | ? { |
| 680 | user_message_uuids: uuids.map((entry) => |
| 681 | typeof entry === "string" ? replayedPromptUuid(entry) : entry, |
| 682 | ), |
| 683 | } |
| 684 | : {}), |
| 685 | }; |
| 686 | }; |
| 687 | const promptOfferUuid = (frame: unknown): string | undefined => { |
| 688 | if ( |
| 689 | typeof frame !== "object" || |
| 690 | frame === null || |
| 691 | Reflect.get(frame, "type") !== "prompt.offer" |
| 692 | ) { |
| 693 | return undefined; |
| 694 | } |
| 695 | const message: unknown = Reflect.get(frame, "message"); |
| 696 | const uuid: unknown = |
| 697 | typeof message === "object" && message !== null ? Reflect.get(message, "uuid") : undefined; |
| 698 | return typeof uuid === "string" ? uuid : undefined; |
| 699 | }; |
| 700 | const withoutPromptOfferUuid = (frame: unknown): unknown => { |
| 701 | if (promptOfferUuid(frame) === undefined || typeof frame !== "object" || frame === null) { |
| 702 | return frame; |
| 703 | } |
| 704 | const message = Reflect.get(frame, "message") as Record<string, unknown>; |
| 705 | const { uuid: _uuid, ...rest } = message; |
| 706 | return { ...frame, message: rest }; |
| 707 | }; |
| 708 | |
| 709 | const assertNextOutboundFrame = (actual: ClaudeOutboundFrame) => { |
| 710 | if (failure !== null) { |
| 711 | throw failure; |
| 712 | } |
| 713 | const entry = transcript.entries[cursor]; |
| 714 | if (entry === undefined) { |
| 715 | return fail( |
| 716 | new ClaudeReplayExhaustedError({ |
| 717 | scenario: transcript.scenario, |
| 718 | cursor, |
| 719 | actual, |
| 720 | }), |
| 721 | ); |
| 722 | } |
| 723 | if (entry.type !== "expect_outbound") { |
| 724 | return fail( |
| 725 | new ClaudeReplayUnexpectedOutboundError({ |
| 726 | scenario: transcript.scenario, |
| 727 | cursor, |
| 728 | expectedType: entry.type, |
| 729 | actual, |
| 730 | }), |
| 731 | ); |
| 732 | } |
| 733 | |
| 734 | const expected = entry.frame; |
| 735 | const expectedUuid = promptOfferUuid(expected); |
| 736 | const actualUuid = promptOfferUuid(actual); |
| 737 | if ( |
| 738 | !sameFrame(withoutPromptOfferUuid(expected), withoutPromptOfferUuid(actual)) || |
| 739 | (expectedUuid !== undefined && actualUuid === undefined) |
| 740 | ) { |
| 741 | fail( |
| 742 | new ClaudeReplayFrameMismatchError({ |
| 743 | scenario: transcript.scenario, |
| 744 | cursor, |
| 745 | ...(entry.label === undefined ? {} : { label: entry.label }), |
| 746 | expected, |
| 747 | actual, |
| 748 | }), |
| 749 | ); |
| 750 | } |
| 751 | if (expectedUuid !== undefined && actualUuid !== undefined) { |
| 752 | promptUuidReplacements.set(expectedUuid, actualUuid); |
| 753 | } |
| 754 | |
| 755 | advance(); |
| 756 | }; |
| 757 | |
| 758 | const assertNextReplyFrame = <Frame extends ClaudeSessionForkedFrame | ClaudeSubagentFoundFrame>( |
| 759 | type: Frame["type"], |
| 760 | isValid: (frame: object) => boolean, |
| 761 | ): Frame => { |
| 762 | const entry = transcript.entries[cursor]; |
| 763 | if (entry === undefined) { |
| 764 | return fail( |
| 765 | new ClaudeReplayExhaustedError({ |
| 766 | scenario: transcript.scenario, |
| 767 | cursor, |
| 768 | actual: { type }, |
| 769 | }), |
| 770 | ); |
| 771 | } |
| 772 | if (entry.type !== "emit_inbound") { |
| 773 | return fail( |
| 774 | new ClaudeReplayUnexpectedOutboundError({ |
| 775 | scenario: transcript.scenario, |
| 776 | cursor, |
| 777 | expectedType: entry.type, |
| 778 | actual: { type }, |
| 779 | }), |
| 780 | ); |
| 781 | } |
| 782 | if ( |
| 783 | typeof entry.frame !== "object" || |
| 784 | entry.frame === null || |
| 785 | Reflect.get(entry.frame, "type") !== type || |
| 786 | !isValid(entry.frame) |
| 787 | ) { |
| 788 | return fail( |
| 789 | new ClaudeReplayFrameMismatchError({ |
| 790 | scenario: transcript.scenario, |
| 791 | cursor, |
| 792 | expected: { type }, |
| 793 | actual: entry.frame, |
| 794 | }), |
| 795 | ); |
| 796 | } |
| 797 | |
| 798 | const frame = entry.frame as Frame; |
| 799 | advance(); |
| 800 | return frame; |
| 801 | }; |
| 802 | |
| 803 | const replayEffect = (tryEffect: () => void) => |
| 804 | Effect.try({ |
| 805 | try: tryEffect, |
| 806 | catch: (cause) => replayQueryRunnerError(transcript, cause), |
| 807 | }); |
| 808 | |
| 809 | return { |
| 810 | open: (input) => { |
| 811 | assertNextOutboundFrame(makeClaudeQueryOpenFrame(input)); |
| 812 | return { |
| 813 | messages: Stream.fromAsyncIterable(replayMessagesWithGateCleanup(input.options), (cause) => |
| 814 | replayQueryRunnerError(transcript, cause), |
| 815 | ), |
| 816 | offer: (message) => |
| 817 | replayEffect(() => { |
| 818 | assertNextOutboundFrame(makeClaudePromptOfferFrame(message)); |
| 819 | }), |
| 820 | setModel: (model) => |
| 821 | replayEffect(() => { |
| 822 | assertNextOutboundFrame({ |
| 823 | type: "query.set_model", |
| 824 | model, |
| 825 | }); |
| 826 | }), |
| 827 | applyFlagSettings: (settings) => |
| 828 | replayEffect(() => { |
| 829 | assertNextOutboundFrame({ |
| 830 | type: "query.apply_flag_settings", |
| 831 | settings, |
| 832 | }); |
| 833 | }), |
| 834 | setPermissionMode: (mode) => |
| 835 | replayEffect(() => { |
| 836 | assertNextOutboundFrame({ |
| 837 | type: "query.set_permission_mode", |
| 838 | mode, |
| 839 | }); |
| 840 | }), |
| 841 | // Recorded sessions already hold their title, and no replay asserts rename frames. |
| 842 | renameSession: () => Effect.void, |
| 843 | stopTask: (taskId) => |
| 844 | replayEffect(() => { |
| 845 | assertNextOutboundFrame({ type: "query.stop_task", taskId }); |
| 846 | }), |
| 847 | backgroundTasks: (toolUseId) => |
| 848 | replayEffect(() => { |
| 849 | assertNextOutboundFrame({ type: "query.background_tasks", toolUseId }); |
| 850 | }).pipe(Effect.as(true)), |
| 851 | // A result looks for servers that need a sign-in; the replay reports none. |
| 852 | mcpServerStatus: Effect.succeed([]), |
| 853 | // Recorded CLIs predate MCP Apps capabilities, so replays never reach these. |
| 854 | readMcpResource: () => Effect.die("unexpected MCP resource read in replay"), |
| 855 | mcpAuthenticate: () => Effect.die("unexpected MCP sign-in in replay"), |
| 856 | mcpSubmitOAuthCallbackUrl: () => Effect.die("unexpected MCP sign-in in replay"), |
| 857 | reconnectMcpServer: () => Effect.die("unexpected MCP reconnect in replay"), |
| 858 | callMcpTool: () => Effect.die("unexpected MCP tool call in replay"), |
| 859 | listPermissionRules: Effect.die("unexpected permission rules read in replay"), |
| 860 | interrupt: replayEffect(() => { |
| 861 | assertNextOutboundFrame({ type: "query.interrupt" }); |
| 862 | }), |
| 863 | close: Effect.void, |
| 864 | }; |
| 865 | }, |
| 866 | forkSession: (input) => { |
| 867 | assertNextOutboundFrame(makeClaudeSessionForkFrame(input, transcript.scenario)); |
| 868 | return assertNextReplyFrame<ClaudeSessionForkedFrame>( |
| 869 | "session.forked", |
| 870 | (frame) => typeof Reflect.get(frame, "sessionId") === "string", |
| 871 | ); |
| 872 | }, |
| 873 | subagentLaunchToolUseId: (input) => { |
| 874 | assertNextOutboundFrame({ |
| 875 | type: "subagent.lookup", |
| 876 | sessionId: input.sessionId, |
| 877 | agentId: input.agentId, |
| 878 | }); |
| 879 | return assertNextReplyFrame<ClaudeSubagentFoundFrame>("subagent.found", (frame) => { |
| 880 | const toolUseId = Reflect.get(frame, "toolUseId"); |
| 881 | return toolUseId === null || typeof toolUseId === "string"; |
| 882 | }).toolUseId; |
| 883 | }, |
| 884 | assertComplete: () => { |
| 885 | if (failure !== null) { |
| 886 | throw failure; |
| 887 | } |
| 888 | if (cursor !== transcript.entries.length) { |
| 889 | replayOptions.replayGate?.releaseAll(); |
| 890 | throw new ClaudeReplayIncompleteError({ |
| 891 | scenario: transcript.scenario, |
| 892 | cursor, |
| 893 | remaining: transcript.entries.length - cursor, |
| 894 | }); |
| 895 | } |
| 896 | }, |
| 897 | }; |
| 898 | } |
| 899 | |
| 900 | function metadataFromTranscript(transcript: ProviderReplayTranscript): { |
| 901 | readonly provider?: string; |
| 902 | readonly protocol?: string; |
| 903 | readonly scenario?: string; |
| 904 | } { |
| 905 | return { |
| 906 | provider: transcript.provider, |
| 907 | protocol: transcript.protocol, |
| 908 | scenario: transcript.scenario, |
| 909 | }; |
| 910 | } |
| 911 | |
| 912 | function nativeSessionIdFor(transcript: ClaudeAgentSdkReplayTranscript): string { |
| 913 | const metadataSessionId = transcript.metadata?.nativeSessionId; |
| 914 | return typeof metadataSessionId === "string" |
| 915 | ? metadataSessionId |
| 916 | : "00000000-0000-4000-8000-000000000000"; |
| 917 | } |
| 918 | |
| 919 | const isClaudeAgentSdkQueryRunnerError = Schema.is(ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError); |
| 920 | const isClaudeAgentSdkReplayError = Schema.is(ClaudeAgentSdkReplayError); |
| 921 | |
| 922 | function replayQueryRunnerError( |
| 923 | transcript: ClaudeAgentSdkReplayTranscript, |
| 924 | cause: unknown, |
| 925 | ): ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError { |
| 926 | if (isClaudeAgentSdkQueryRunnerError(cause)) { |
| 927 | return cause; |
| 928 | } |
| 929 | const replayCause = isClaudeAgentSdkReplayError(cause) |
| 930 | ? cause |
| 931 | : new ClaudeReplayDriverError({ scenario: transcript.scenario, cause }); |
| 932 | return new ClaudeAdapterV2.ClaudeAgentSdkQueryRunnerError({ |
| 933 | cause: replayCause, |
| 934 | method: `replay-scenario:${transcript.scenario}`, |
| 935 | }); |
| 936 | } |
| 937 | |
| 938 | function replayQueryRunnerService( |
| 939 | transcript: ClaudeAgentSdkReplayTranscript, |
| 940 | queryRunner: ClaudeQueryRunner, |
| 941 | ): ClaudeAdapterV2.ClaudeAgentSdkQueryRunner["Service"] { |
| 942 | const replay = <A>(run: () => A) => |
| 943 | Effect.try({ |
| 944 | try: run, |
| 945 | catch: (cause) => replayQueryRunnerError(transcript, cause), |
| 946 | }); |
| 947 | return ClaudeAdapterV2.ClaudeAgentSdkQueryRunner.of({ |
| 948 | allocateSessionId: Effect.succeed(nativeSessionIdFor(transcript)), |
| 949 | open: (input) => replay(() => queryRunner.open(input)), |
| 950 | forkSession: (input) => replay(() => queryRunner.forkSession(input)), |
| 951 | subagentLaunchToolUseId: (input) => replay(() => queryRunner.subagentLaunchToolUseId(input)), |
| 952 | subagentModel: () => Effect.succeed(null), |
| 953 | assertComplete: replay(() => queryRunner.assertComplete()), |
| 954 | }); |
| 955 | } |
| 956 | |
| 957 | function layerClaudeAgentSdkReplay( |
| 958 | transcript: ClaudeAgentSdkReplayTranscript, |
| 959 | options: { |
| 960 | readonly replayGate?: ProviderReplayGate; |
| 961 | readonly queryRunner?: ClaudeQueryRunner; |
| 962 | } = {}, |
| 963 | ): Layer.Layer<ClaudeAdapterV2.ClaudeAgentSdkQueryRunner> { |
| 964 | if (options.queryRunner !== undefined) { |
| 965 | return Layer.succeed( |
| 966 | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner, |
| 967 | replayQueryRunnerService(transcript, options.queryRunner), |
| 968 | ); |
| 969 | } |
| 970 | const queryRunner = makeReplayQueryRunner(transcript, options); |
| 971 | return Layer.effect( |
| 972 | ClaudeAdapterV2.ClaudeAgentSdkQueryRunner, |
| 973 | Effect.gen(function* () { |
| 974 | yield* Effect.addFinalizer(() => |
| 975 | Effect.sync(() => { |
| 976 | queryRunner.assertComplete(); |
| 977 | }), |
| 978 | ); |
| 979 | return replayQueryRunnerService(transcript, queryRunner); |
| 980 | }), |
| 981 | ); |
| 982 | } |
| 983 | |
| 984 | /** Replays write recorded Bash output to task_started files under a scenario-owned CLAUDE_CODE_TMPDIR. */ |
| 985 | const writeReplayTaskOutputFiles = Effect.fn("ClaudeReplay.writeTaskOutputFiles")(function* ( |
| 986 | transcript: ClaudeAgentSdkReplayTranscript, |
| 987 | ) { |
| 988 | const fileSystem = yield* FileSystem.FileSystem; |
| 989 | const path = yield* Path.Path; |
| 990 | const tmpRoot = yield* fileSystem.makeTempDirectoryScoped({ prefix: "claude-replay-tasks-" }); |
| 991 | const frames = transcript.entries.flatMap((entry) => |
| 992 | entry.type === "emit_inbound" && typeof entry.frame === "object" && entry.frame !== null |
| 993 | ? [entry.frame as Record<string, unknown>] |
| 994 | : [], |
| 995 | ); |
| 996 | const outputByToolUseId = new Map<string, string>(); |
| 997 | for (const frame of frames) { |
| 998 | const result = frame.tool_use_result as Record<string, unknown> | undefined; |
| 999 | const content = (frame.message as { readonly content?: unknown } | undefined)?.content; |
| 1000 | if (typeof result?.stdout !== "string" || !Array.isArray(content)) continue; |
| 1001 | const toolResult = content.find( |
| 1002 | (block): block is { readonly tool_use_id: string } => |
| 1003 | block?.type === "tool_result" && typeof block.tool_use_id === "string", |
| 1004 | ); |
| 1005 | if (toolResult === undefined) continue; |
| 1006 | const stderr = typeof result.stderr === "string" ? result.stderr : ""; |
| 1007 | outputByToolUseId.set(toolResult.tool_use_id, `${result.stdout}${stderr}`); |
| 1008 | } |
| 1009 | const root = claudeTaskOutputRoot( |
| 1010 | { CLAUDE_CODE_TMPDIR: tmpRoot }, |
| 1011 | path, |
| 1012 | null, |
| 1013 | yield* HostProcess.Platform, |
| 1014 | ); |
| 1015 | for (const frame of frames) { |
| 1016 | if (frame.type !== "system" || frame.subtype !== "task_started") continue; |
| 1017 | if (frame.task_type !== "local_bash" || frame.is_backgrounded !== false) continue; |
| 1018 | const output = |
| 1019 | typeof frame.tool_use_id === "string" ? outputByToolUseId.get(frame.tool_use_id) : undefined; |
| 1020 | if (root === undefined || output === undefined || typeof frame.session_id !== "string") { |
| 1021 | continue; |
| 1022 | } |
| 1023 | const tasks = path.join(root, "replay-project", frame.session_id, "tasks"); |
| 1024 | yield* fileSystem.makeDirectory(tasks, { recursive: true }); |
| 1025 | yield* fileSystem.writeFileString(path.join(tasks, `${String(frame.task_id)}.output`), output); |
| 1026 | } |
| 1027 | return tmpRoot; |
| 1028 | }); |
| 1029 | |
| 1030 | function layerClaudeProviderAdapterRegistryReplay( |
| 1031 | transcript: ClaudeAgentSdkReplayTranscript, |
| 1032 | options: { |
| 1033 | readonly replayGate?: ProviderReplayGate; |
| 1034 | readonly queryRunner?: ClaudeQueryRunner; |
| 1035 | } = {}, |
| 1036 | ) { |
| 1037 | const layerServerConfig = Layer.effect( |
| 1038 | ServerConfig.ServerConfig, |
| 1039 | makeReplayServerConfig(transcript.scenario).pipe(Effect.orDie), |
| 1040 | ).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))); |
| 1041 | return Layer.unwrap( |
| 1042 | writeReplayTaskOutputFiles(transcript).pipe( |
| 1043 | Effect.orDie, |
| 1044 | Effect.map((tmpRoot) => |
| 1045 | ProviderAdapterRegistry.layerFromAdaptersEffect( |
| 1046 | ClaudeAdapterV2.createClaudeAdapterV2( |
| 1047 | { |
| 1048 | instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, |
| 1049 | displayName: undefined, |
| 1050 | environment: [{ name: "CLAUDE_CODE_TMPDIR", value: tmpRoot, sensitive: false }], |
| 1051 | enabled: true, |
| 1052 | config: DEFAULT_CLAUDE_SETTINGS, |
| 1053 | }, |
| 1054 | {}, |
| 1055 | ).pipe(Effect.map((adapter) => [adapter])), |
| 1056 | ), |
| 1057 | ), |
| 1058 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1059 | ), |
| 1060 | ).pipe( |
| 1061 | Layer.provide( |
| 1062 | Layer.mergeAll( |
| 1063 | layerClaudeAgentSdkReplay(transcript, options), |
| 1064 | IdAllocator.layer, |
| 1065 | ProviderInstallationGate.layer, |
| 1066 | NodeServices.layer, |
| 1067 | NodeCrypto.layer, |
| 1068 | layerServerConfig, |
| 1069 | ), |
| 1070 | ), |
| 1071 | ); |
| 1072 | } |
| 1073 | |
| 1074 | function serializeReplayError(error: unknown, scenario?: string): unknown { |
| 1075 | return error instanceof Error |
| 1076 | ? { |
| 1077 | name: error.name, |
| 1078 | message: |
| 1079 | scenario === undefined |
| 1080 | ? error.message |
| 1081 | : sanitizeReplayText({ text: error.message, scenario }), |
| 1082 | } |
| 1083 | : error; |
| 1084 | } |
| 1085 | |
| 1086 | function permissionResultForRecording(input: { |
| 1087 | readonly decision: ProviderApprovalDecision; |
| 1088 | readonly toolInput: Record<string, unknown>; |
| 1089 | readonly toolUseID: string; |
| 1090 | readonly suggestions?: Parameters<CanUseTool>[2]["suggestions"]; |
| 1091 | }): PermissionResult { |
| 1092 | if (input.decision === "accept" || input.decision === "acceptForSession") { |
| 1093 | return { |
| 1094 | behavior: "allow", |
| 1095 | updatedInput: input.toolInput, |
| 1096 | toolUseID: input.toolUseID, |
| 1097 | decisionClassification: |
| 1098 | input.decision === "acceptForSession" ? "user_permanent" : "user_temporary", |
| 1099 | ...(input.decision === "acceptForSession" && input.suggestions !== undefined |
| 1100 | ? { updatedPermissions: input.suggestions } |
| 1101 | : {}), |
| 1102 | }; |
| 1103 | } |
| 1104 | return { |
| 1105 | behavior: "deny", |
| 1106 | message: |
| 1107 | input.decision === "cancel" |
| 1108 | ? "User cancelled tool execution." |
| 1109 | : "User declined tool execution.", |
| 1110 | toolUseID: input.toolUseID, |
| 1111 | decisionClassification: "user_reject", |
| 1112 | ...(input.decision === "cancel" ? { interrupt: true } : {}), |
| 1113 | }; |
| 1114 | } |
| 1115 | |
| 1116 | function permissionRequestFrame(input: { |
| 1117 | readonly toolName: string; |
| 1118 | readonly toolInput: Record<string, unknown>; |
| 1119 | readonly callbackOptions: Parameters<CanUseTool>[2]; |
| 1120 | }): ClaudePermissionRequestFrame { |
| 1121 | const { callbackOptions } = input; |
| 1122 | return { |
| 1123 | type: "permission.request", |
| 1124 | toolName: input.toolName, |
| 1125 | input: input.toolInput, |
| 1126 | options: { |
| 1127 | ...(callbackOptions.suggestions === undefined |
| 1128 | ? {} |
| 1129 | : { suggestions: callbackOptions.suggestions }), |
| 1130 | ...(callbackOptions.blockedPath === undefined |
| 1131 | ? {} |
| 1132 | : { blockedPath: callbackOptions.blockedPath }), |
| 1133 | ...(callbackOptions.decisionReason === undefined |
| 1134 | ? {} |
| 1135 | : { decisionReason: callbackOptions.decisionReason }), |
| 1136 | ...(callbackOptions.title === undefined ? {} : { title: callbackOptions.title }), |
| 1137 | ...(callbackOptions.displayName === undefined |
| 1138 | ? {} |
| 1139 | : { displayName: callbackOptions.displayName }), |
| 1140 | ...(callbackOptions.description === undefined |
| 1141 | ? {} |
| 1142 | : { description: callbackOptions.description }), |
| 1143 | toolUseID: callbackOptions.toolUseID, |
| 1144 | ...(callbackOptions.agentID === undefined ? {} : { agentID: callbackOptions.agentID }), |
| 1145 | }, |
| 1146 | }; |
| 1147 | } |
| 1148 | |
| 1149 | function sanitizedReplayCwd(scenario: string): string { |
| 1150 | return `/tmp/claude-replay-${scenario}`; |
| 1151 | } |
| 1152 | |
| 1153 | function parentDirectory(input: string): string { |
| 1154 | const trimmed = input.replace(/\/+$/u, ""); |
| 1155 | const lastSlash = trimmed.lastIndexOf("/"); |
| 1156 | if (lastSlash <= 0) { |
| 1157 | return "/"; |
| 1158 | } |
| 1159 | return trimmed.slice(0, lastSlash); |
| 1160 | } |
| 1161 | |
| 1162 | function sanitizeReplayText(input: { readonly text: string; readonly scenario: string }): string { |
| 1163 | const sanitizedCwd = sanitizedReplayCwd(input.scenario); |
| 1164 | const repoRoot = parentDirectory(parentDirectory(process.cwd())); |
| 1165 | return [repoRoot, process.cwd()] |
| 1166 | .toSorted((left, right) => right.length - left.length) |
| 1167 | .reduce((text, localPath) => text.replaceAll(localPath, sanitizedCwd), input.text); |
| 1168 | } |
| 1169 | |
| 1170 | function sanitizeSdkMessageForReplay(input: { |
| 1171 | readonly message: SDKMessage; |
| 1172 | readonly scenario: string; |
| 1173 | }): SDKMessage { |
| 1174 | const { message } = input; |
| 1175 | if (message.type === "system" && message.subtype === "init") { |
| 1176 | return { |
| 1177 | type: "system", |
| 1178 | subtype: "init", |
| 1179 | ...(message.agents === undefined ? {} : { agents: [] }), |
| 1180 | apiKeySource: message.apiKeySource, |
| 1181 | ...(message.betas === undefined ? {} : { betas: message.betas }), |
| 1182 | claude_code_version: message.claude_code_version, |
| 1183 | cwd: sanitizedReplayCwd(input.scenario), |
| 1184 | tools: [], |
| 1185 | mcp_servers: [], |
| 1186 | model: message.model, |
| 1187 | permissionMode: message.permissionMode, |
| 1188 | slash_commands: [], |
| 1189 | output_style: message.output_style, |
| 1190 | skills: [], |
| 1191 | plugins: [], |
| 1192 | ...(message.fast_mode_state === undefined |
| 1193 | ? {} |
| 1194 | : { fast_mode_state: message.fast_mode_state }), |
| 1195 | uuid: message.uuid, |
| 1196 | session_id: message.session_id, |
| 1197 | }; |
| 1198 | } |
| 1199 | // Recorded commands and skills are account configuration. |
| 1200 | if (message.type === "system" && message.subtype === "commands_changed") { |
| 1201 | return { ...message, commands: [] }; |
| 1202 | } |
| 1203 | if (message.type === "rate_limit_event") { |
| 1204 | return { |
| 1205 | ...message, |
| 1206 | rate_limit_info: { |
| 1207 | status: message.rate_limit_info.status, |
| 1208 | }, |
| 1209 | }; |
| 1210 | } |
| 1211 | if (message.type === "result" && message.subtype !== "success" && message.errors.length > 0) { |
| 1212 | return { |
| 1213 | ...message, |
| 1214 | errors: message.errors.map((error) => |
| 1215 | sanitizeReplayText({ text: error, scenario: input.scenario }), |
| 1216 | ), |
| 1217 | }; |
| 1218 | } |
| 1219 | return message; |
| 1220 | } |
| 1221 | |
| 1222 | class RecordingMessageReader implements AsyncIterator<SDKMessage> { |
| 1223 | private pending: Promise<IteratorResult<SDKMessage>> | undefined; |
| 1224 | private readonly iterator: AsyncIterator<SDKMessage>; |
| 1225 | |
| 1226 | constructor(iterator: AsyncIterator<SDKMessage>) { |
| 1227 | this.iterator = iterator; |
| 1228 | } |
| 1229 | |
| 1230 | next(): Promise<IteratorResult<SDKMessage>> { |
| 1231 | const pending = this.pending ?? this.iterator.next(); |
| 1232 | this.pending = undefined; |
| 1233 | return pending; |
| 1234 | } |
| 1235 | |
| 1236 | async peekWithin(ms: number): Promise<SDKMessage | undefined> { |
| 1237 | const pending = this.pending ?? this.iterator.next(); |
| 1238 | this.pending = pending; |
| 1239 | return Promise.race([ |
| 1240 | pending.then( |
| 1241 | (result) => (result.done === true ? undefined : result.value), |
| 1242 | () => undefined, |
| 1243 | ), |
| 1244 | Effect.runPromise(Effect.sleep(Duration.millis(ms))).then(() => undefined), |
| 1245 | ]); |
| 1246 | } |
| 1247 | } |
| 1248 | |
| 1249 | class RecordingPromptQueue implements AsyncIterable<SDKUserMessage> { |
| 1250 | private readonly pending: Array<IteratorResult<SDKUserMessage>> = []; |
| 1251 | private readonly waiters: Array<(result: IteratorResult<SDKUserMessage>) => void> = []; |
| 1252 | private closed = false; |
| 1253 | |
| 1254 | offer(message: SDKUserMessage): void { |
| 1255 | if (this.closed) { |
| 1256 | throw new Error("Cannot offer a prompt to a closed Claude recording queue."); |
| 1257 | } |
| 1258 | this.push({ done: false, value: message }); |
| 1259 | } |
| 1260 | |
| 1261 | close(): void { |
| 1262 | if (this.closed) { |
| 1263 | return; |
| 1264 | } |
| 1265 | this.closed = true; |
| 1266 | this.push({ done: true, value: undefined }); |
| 1267 | } |
| 1268 | |
| 1269 | async *[Symbol.asyncIterator](): AsyncIterator<SDKUserMessage> { |
| 1270 | while (true) { |
| 1271 | const next = await this.take(); |
| 1272 | if (next.done === true) { |
| 1273 | return; |
| 1274 | } |
| 1275 | yield next.value; |
| 1276 | } |
| 1277 | } |
| 1278 | |
| 1279 | private push(result: IteratorResult<SDKUserMessage>): void { |
| 1280 | const waiter = this.waiters.shift(); |
| 1281 | if (waiter === undefined) { |
| 1282 | this.pending.push(result); |
| 1283 | return; |
| 1284 | } |
| 1285 | waiter(result); |
| 1286 | } |
| 1287 | |
| 1288 | private take(): Promise<IteratorResult<SDKUserMessage>> { |
| 1289 | const next = this.pending.shift(); |
| 1290 | if (next !== undefined) { |
| 1291 | return Promise.resolve(next); |
| 1292 | } |
| 1293 | return new Promise((resolve) => { |
| 1294 | this.waiters.push(resolve); |
| 1295 | }); |
| 1296 | } |
| 1297 | } |
| 1298 | |
| 1299 | async function recordMessagesUntilTurnResult(input: { |
| 1300 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1301 | readonly entries: Array<ProviderReplayEntry>; |
| 1302 | readonly scenario: string; |
| 1303 | }): Promise<boolean> { |
| 1304 | while (true) { |
| 1305 | const next = await input.iterator.next(); |
| 1306 | if (next.done === true) { |
| 1307 | return false; |
| 1308 | } |
| 1309 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1310 | message: next.value, |
| 1311 | scenario: input.scenario, |
| 1312 | }); |
| 1313 | input.entries.push({ |
| 1314 | type: "emit_inbound", |
| 1315 | label: replayMessage.type, |
| 1316 | frame: replayMessage, |
| 1317 | }); |
| 1318 | if (replayMessage.type === "result") { |
| 1319 | return true; |
| 1320 | } |
| 1321 | } |
| 1322 | } |
| 1323 | |
| 1324 | async function recordMessagesUntilTurnResultAndFinalize(input: { |
| 1325 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1326 | readonly entries: Array<ProviderReplayEntry>; |
| 1327 | readonly scenario: string; |
| 1328 | readonly finalize: () => void; |
| 1329 | }): Promise<boolean> { |
| 1330 | try { |
| 1331 | return await recordMessagesUntilTurnResult(input); |
| 1332 | } finally { |
| 1333 | input.finalize(); |
| 1334 | } |
| 1335 | } |
| 1336 | |
| 1337 | async function recordMessagesUntilTurnResultWithCursor(input: { |
| 1338 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1339 | readonly entries: Array<ProviderReplayEntry>; |
| 1340 | readonly scenario: string; |
| 1341 | }): Promise<{ |
| 1342 | readonly completed: boolean; |
| 1343 | readonly assistantMessageUuid: SDKAssistantMessage["uuid"] | null; |
| 1344 | }> { |
| 1345 | let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null; |
| 1346 | while (true) { |
| 1347 | const next = await input.iterator.next(); |
| 1348 | if (next.done === true) { |
| 1349 | return { completed: false, assistantMessageUuid }; |
| 1350 | } |
| 1351 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1352 | message: next.value, |
| 1353 | scenario: input.scenario, |
| 1354 | }); |
| 1355 | input.entries.push({ |
| 1356 | type: "emit_inbound", |
| 1357 | label: replayMessage.type, |
| 1358 | frame: replayMessage, |
| 1359 | }); |
| 1360 | if (replayMessage.type === "assistant") { |
| 1361 | assistantMessageUuid = replayMessage.uuid; |
| 1362 | } |
| 1363 | if (replayMessage.type === "result") { |
| 1364 | return { completed: true, assistantMessageUuid }; |
| 1365 | } |
| 1366 | } |
| 1367 | } |
| 1368 | |
| 1369 | function requireAssistantCursor(input: { |
| 1370 | readonly scenario: string; |
| 1371 | readonly promptIndex: number; |
| 1372 | readonly cursor: SDKAssistantMessage["uuid"] | null; |
| 1373 | }): SDKAssistantMessage["uuid"] { |
| 1374 | if (input.cursor !== null) { |
| 1375 | return input.cursor; |
| 1376 | } |
| 1377 | throw new Error( |
| 1378 | `Claude replay scenario ${input.scenario} prompt ${input.promptIndex} completed without an SDKAssistantMessage.uuid cursor.`, |
| 1379 | ); |
| 1380 | } |
| 1381 | |
| 1382 | async function recordMessagesUntilTurnResults(input: { |
| 1383 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1384 | readonly entries: Array<ProviderReplayEntry>; |
| 1385 | readonly scenario: string; |
| 1386 | readonly resultCount: number; |
| 1387 | }): Promise<boolean> { |
| 1388 | let seenResults = 0; |
| 1389 | while (true) { |
| 1390 | const next = await input.iterator.next(); |
| 1391 | if (next.done === true) { |
| 1392 | return false; |
| 1393 | } |
| 1394 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1395 | message: next.value, |
| 1396 | scenario: input.scenario, |
| 1397 | }); |
| 1398 | input.entries.push({ |
| 1399 | type: "emit_inbound", |
| 1400 | label: replayMessage.type, |
| 1401 | frame: replayMessage, |
| 1402 | }); |
| 1403 | if (replayMessage.type === "result") { |
| 1404 | seenResults += 1; |
| 1405 | if (seenResults >= input.resultCount) { |
| 1406 | return true; |
| 1407 | } |
| 1408 | } |
| 1409 | } |
| 1410 | } |
| 1411 | |
| 1412 | async function recordMessagesUntilIteratorDone(input: { |
| 1413 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1414 | readonly entries: Array<ProviderReplayEntry>; |
| 1415 | readonly scenario: string; |
| 1416 | }): Promise<void> { |
| 1417 | while (true) { |
| 1418 | const next = await input.iterator.next(); |
| 1419 | if (next.done === true) { |
| 1420 | return; |
| 1421 | } |
| 1422 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1423 | message: next.value, |
| 1424 | scenario: input.scenario, |
| 1425 | }); |
| 1426 | input.entries.push({ |
| 1427 | type: "emit_inbound", |
| 1428 | label: replayMessage.type, |
| 1429 | frame: replayMessage, |
| 1430 | }); |
| 1431 | } |
| 1432 | } |
| 1433 | |
| 1434 | const CLAUDE_RECORDING_WAKE_QUIET_MS = 5_000; |
| 1435 | |
| 1436 | function isSystemInitFrame(message: SDKMessage | undefined): boolean { |
| 1437 | return message?.type === "system" && message.subtype === "init"; |
| 1438 | } |
| 1439 | |
| 1440 | function isTaskNotificationOriginResultFrame(frame: unknown): boolean { |
| 1441 | if (typeof frame !== "object" || frame === null || Reflect.get(frame, "type") !== "result") { |
| 1442 | return false; |
| 1443 | } |
| 1444 | const origin: unknown = Reflect.get(frame, "origin"); |
| 1445 | return ( |
| 1446 | typeof origin === "object" && |
| 1447 | origin !== null && |
| 1448 | Reflect.get(origin, "kind") === "task-notification" |
| 1449 | ); |
| 1450 | } |
| 1451 | |
| 1452 | function sdkMessageHasRootToolUse(message: SDKMessage): boolean { |
| 1453 | return ( |
| 1454 | message.type === "assistant" && |
| 1455 | message.parent_tool_use_id === null && |
| 1456 | message.message.content.some((part) => part.type === "tool_use") |
| 1457 | ); |
| 1458 | } |
| 1459 | |
| 1460 | async function recordMessagesUntilToolUse(input: { |
| 1461 | readonly iterator: AsyncIterator<SDKMessage>; |
| 1462 | readonly entries: Array<ProviderReplayEntry>; |
| 1463 | readonly scenario: string; |
| 1464 | readonly toolUseCount: number; |
| 1465 | }): Promise<void> { |
| 1466 | let toolUses = 0; |
| 1467 | while (true) { |
| 1468 | const next = await input.iterator.next(); |
| 1469 | if (next.done === true) { |
| 1470 | throw new Error(`Claude query ended before ${input.scenario} started a tool use.`); |
| 1471 | } |
| 1472 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1473 | message: next.value, |
| 1474 | scenario: input.scenario, |
| 1475 | }); |
| 1476 | input.entries.push({ |
| 1477 | type: "emit_inbound", |
| 1478 | label: replayMessage.type, |
| 1479 | frame: replayMessage, |
| 1480 | }); |
| 1481 | if (replayMessage.type === "result") { |
| 1482 | throw new Error(`Claude query completed before ${input.scenario} started a tool use.`); |
| 1483 | } |
| 1484 | if (sdkMessageHasRootToolUse(replayMessage)) { |
| 1485 | toolUses += 1; |
| 1486 | if (toolUses >= input.toolUseCount) { |
| 1487 | return; |
| 1488 | } |
| 1489 | } |
| 1490 | } |
| 1491 | } |
| 1492 | |
| 1493 | // The SDK may lack a platform executable. Prefer installed Claude only when directly spawnable, |
| 1494 | // including Windows shims resolved to package entries. |
| 1495 | const resolveClaudeRecordingExecutablePath = Effect.fn("resolveClaudeRecordingExecutablePath")( |
| 1496 | function* (environment: NodeJS.ProcessEnv) { |
| 1497 | const resolveExecutable = yield* SpawnExecutableResolution; |
| 1498 | const platform = yield* HostProcess.Platform; |
| 1499 | const resolved = resolveExecutable("claude", platform, environment); |
| 1500 | if (resolved === undefined) { |
| 1501 | return undefined; |
| 1502 | } |
| 1503 | const executablePath = yield* resolveClaudeSdkExecutablePath(resolved, environment); |
| 1504 | if (platform === "win32" && isWindowsClaudeLauncherShimPath(executablePath)) { |
| 1505 | return undefined; |
| 1506 | } |
| 1507 | return executablePath; |
| 1508 | }, |
| 1509 | ); |
| 1510 | |
| 1511 | async function openRecordingQuery(input: Parameters<typeof query>[0]) { |
| 1512 | const executablePath = await Effect.runPromise(resolveClaudeRecordingExecutablePath(process.env)); |
| 1513 | return query({ |
| 1514 | ...input, |
| 1515 | options: { |
| 1516 | ...input.options, |
| 1517 | ...(executablePath === undefined ? {} : { pathToClaudeCodeExecutable: executablePath }), |
| 1518 | }, |
| 1519 | }); |
| 1520 | } |
| 1521 | |
| 1522 | async function recordClaudeStreamingQuery(input: { |
| 1523 | readonly scenario: string; |
| 1524 | readonly prompts: ReadonlyArray<string>; |
| 1525 | readonly modelSelection: ModelSelection; |
| 1526 | readonly cwd: string; |
| 1527 | readonly sessionId: string; |
| 1528 | readonly entries: Array<ProviderReplayEntry>; |
| 1529 | readonly enableTools?: boolean; |
| 1530 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 1531 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 1532 | readonly allowedTools?: ReadonlyArray<string>; |
| 1533 | readonly disallowedTools?: ReadonlyArray<string>; |
| 1534 | readonly allowDangerouslySkipPermissions?: boolean; |
| 1535 | readonly enablePermissionCallback?: boolean; |
| 1536 | readonly permissionDecision?: ProviderApprovalDecision; |
| 1537 | readonly backgroundWakeCounts?: ReadonlyArray<number>; |
| 1538 | readonly offerNextPromptImmediately?: boolean; |
| 1539 | }): Promise<void> { |
| 1540 | const promptQueue = new RecordingPromptQueue(); |
| 1541 | const canUseTool: CanUseTool | undefined = |
| 1542 | input.enablePermissionCallback === true |
| 1543 | ? async (toolName, toolInput, callbackOptions) => { |
| 1544 | const requestFrame = permissionRequestFrame({ |
| 1545 | toolName, |
| 1546 | toolInput, |
| 1547 | callbackOptions, |
| 1548 | }); |
| 1549 | input.entries.push({ |
| 1550 | type: "emit_inbound", |
| 1551 | label: `permission.request:${toolName}`, |
| 1552 | frame: requestFrame, |
| 1553 | }); |
| 1554 | const result = permissionResultForRecording({ |
| 1555 | decision: input.permissionDecision ?? "accept", |
| 1556 | toolInput, |
| 1557 | toolUseID: callbackOptions.toolUseID, |
| 1558 | ...(callbackOptions.suggestions === undefined |
| 1559 | ? {} |
| 1560 | : { suggestions: callbackOptions.suggestions }), |
| 1561 | }); |
| 1562 | input.entries.push({ |
| 1563 | type: "expect_outbound", |
| 1564 | label: `permission.response:${toolName}`, |
| 1565 | frame: makeClaudePermissionResponseFrame(result), |
| 1566 | }); |
| 1567 | return result; |
| 1568 | } |
| 1569 | : undefined; |
| 1570 | const options = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 1571 | modelSelection: input.modelSelection, |
| 1572 | nativeThreadId: input.sessionId, |
| 1573 | resume: false, |
| 1574 | cwd: input.cwd, |
| 1575 | ...(input.enableTools === true |
| 1576 | ? { |
| 1577 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 1578 | permissionMode: input.permissionMode ?? "default", |
| 1579 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 1580 | ...(input.disallowedTools === undefined |
| 1581 | ? {} |
| 1582 | : { disallowedTools: input.disallowedTools }), |
| 1583 | ...(input.allowDangerouslySkipPermissions === true |
| 1584 | ? { allowDangerouslySkipPermissions: true } |
| 1585 | : {}), |
| 1586 | ...(canUseTool === undefined ? {} : { canUseTool }), |
| 1587 | } |
| 1588 | : {}), |
| 1589 | }); |
| 1590 | input.entries.push({ |
| 1591 | type: "expect_outbound", |
| 1592 | label: "query.open", |
| 1593 | frame: makeClaudeQueryOpenFrame({ options }), |
| 1594 | }); |
| 1595 | const queryRuntime = await openRecordingQuery({ |
| 1596 | prompt: promptQueue, |
| 1597 | options, |
| 1598 | }); |
| 1599 | const iterator = new RecordingMessageReader(queryRuntime[Symbol.asyncIterator]()); |
| 1600 | let wakeNumber = 0; |
| 1601 | const recordTurn = async (promptNumber: number): Promise<"prompt" | "wake"> => { |
| 1602 | const completed = await recordMessagesUntilTurnResult({ |
| 1603 | iterator, |
| 1604 | entries: input.entries, |
| 1605 | scenario: input.scenario, |
| 1606 | }); |
| 1607 | if (!completed) { |
| 1608 | throw new Error( |
| 1609 | `Claude streaming query ended before prompt ${promptNumber} and its background wakes completed.`, |
| 1610 | ); |
| 1611 | } |
| 1612 | const resultEntry = input.entries.at(-1); |
| 1613 | const resultFrame = resultEntry?.type === "emit_inbound" ? resultEntry.frame : undefined; |
| 1614 | if (!isTaskNotificationOriginResultFrame(resultFrame)) { |
| 1615 | return "prompt"; |
| 1616 | } |
| 1617 | wakeNumber += 1; |
| 1618 | input.entries[input.entries.length - 1] = { |
| 1619 | type: "emit_inbound", |
| 1620 | label: claudeBackgroundWakeResultLabel(wakeNumber), |
| 1621 | frame: resultFrame, |
| 1622 | }; |
| 1623 | return "wake"; |
| 1624 | }; |
| 1625 | try { |
| 1626 | for (const [index, prompt] of input.prompts.entries()) { |
| 1627 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ |
| 1628 | text: prompt, |
| 1629 | uuid: await Effect.runPromise( |
| 1630 | SecureRandom.SecureRandom.pipe( |
| 1631 | Effect.flatMap((random) => random.uuidV4()), |
| 1632 | Effect.filterOrFail(ClaudeAdapterV2.isClaudePromptUuid), |
| 1633 | Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)), |
| 1634 | ), |
| 1635 | ), |
| 1636 | }); |
| 1637 | input.entries.push({ |
| 1638 | type: "expect_outbound", |
| 1639 | label: `prompt.offer:${index + 1}`, |
| 1640 | frame: makeClaudePromptOfferFrame(message), |
| 1641 | }); |
| 1642 | promptQueue.offer(message); |
| 1643 | // Wake turns can precede the prompt turn; identify results by origin. |
| 1644 | let promptSettled = false; |
| 1645 | let wakes = 0; |
| 1646 | const expectedWakes = input.backgroundWakeCounts?.[index] ?? 0; |
| 1647 | while (!promptSettled || wakes < expectedWakes) { |
| 1648 | if ((await recordTurn(index + 1)) === "prompt") { |
| 1649 | promptSettled = true; |
| 1650 | } else { |
| 1651 | wakes += 1; |
| 1652 | } |
| 1653 | } |
| 1654 | if (input.backgroundWakeCounts !== undefined && input.offerNextPromptImmediately !== true) { |
| 1655 | // system:init opens each turn; leave ongoing subagent frames for the next recording. |
| 1656 | while (isSystemInitFrame(await iterator.peekWithin(CLAUDE_RECORDING_WAKE_QUIET_MS))) { |
| 1657 | await recordTurn(index + 1); |
| 1658 | } |
| 1659 | } |
| 1660 | } |
| 1661 | promptQueue.close(); |
| 1662 | queryRuntime.close(); |
| 1663 | input.entries.push({ |
| 1664 | type: "runtime_exit", |
| 1665 | status: "success", |
| 1666 | }); |
| 1667 | } catch (error) { |
| 1668 | promptQueue.close(); |
| 1669 | queryRuntime.close(); |
| 1670 | input.entries.push({ |
| 1671 | type: "runtime_exit", |
| 1672 | status: "error", |
| 1673 | error: serializeReplayError(error, input.scenario), |
| 1674 | }); |
| 1675 | throw error; |
| 1676 | } |
| 1677 | } |
| 1678 | |
| 1679 | async function recordClaudeActiveSteeringQuery(input: { |
| 1680 | readonly scenario: string; |
| 1681 | readonly prompts: ReadonlyArray<string>; |
| 1682 | readonly modelSelection: ModelSelection; |
| 1683 | readonly cwd: string; |
| 1684 | readonly sessionId: string; |
| 1685 | readonly entries: Array<ProviderReplayEntry>; |
| 1686 | readonly enableTools?: boolean; |
| 1687 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 1688 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 1689 | readonly allowedTools?: ReadonlyArray<string>; |
| 1690 | readonly disallowedTools?: ReadonlyArray<string>; |
| 1691 | readonly allowDangerouslySkipPermissions?: boolean; |
| 1692 | readonly enablePermissionCallback?: boolean; |
| 1693 | readonly permissionDecision?: ProviderApprovalDecision; |
| 1694 | }): Promise<void> { |
| 1695 | if (input.prompts.length < 2) { |
| 1696 | throw new Error("Claude active steering replay recording requires at least two prompts."); |
| 1697 | } |
| 1698 | |
| 1699 | const promptQueue = new RecordingPromptQueue(); |
| 1700 | const offerPrompt = (index: number, priority?: SDKUserMessage["priority"]) => { |
| 1701 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ |
| 1702 | text: input.prompts[index]!, |
| 1703 | ...(priority === undefined ? {} : { priority }), |
| 1704 | }); |
| 1705 | input.entries.push({ |
| 1706 | type: "expect_outbound", |
| 1707 | label: `prompt.offer:${index + 1}`, |
| 1708 | frame: makeClaudePromptOfferFrame(message), |
| 1709 | }); |
| 1710 | promptQueue.offer(message); |
| 1711 | }; |
| 1712 | const offerSteeringPrompts = () => { |
| 1713 | for (let index = 1; index < input.prompts.length; index += 1) { |
| 1714 | offerPrompt(index, "now"); |
| 1715 | } |
| 1716 | }; |
| 1717 | |
| 1718 | const canUseTool: CanUseTool | undefined = |
| 1719 | input.enablePermissionCallback === true |
| 1720 | ? async (toolName, toolInput, callbackOptions) => { |
| 1721 | const requestFrame = permissionRequestFrame({ |
| 1722 | toolName, |
| 1723 | toolInput, |
| 1724 | callbackOptions, |
| 1725 | }); |
| 1726 | input.entries.push({ |
| 1727 | type: "emit_inbound", |
| 1728 | label: `permission.request:${toolName}`, |
| 1729 | frame: requestFrame, |
| 1730 | }); |
| 1731 | const result = permissionResultForRecording({ |
| 1732 | decision: input.permissionDecision ?? "accept", |
| 1733 | toolInput, |
| 1734 | toolUseID: callbackOptions.toolUseID, |
| 1735 | ...(callbackOptions.suggestions === undefined |
| 1736 | ? {} |
| 1737 | : { suggestions: callbackOptions.suggestions }), |
| 1738 | }); |
| 1739 | input.entries.push({ |
| 1740 | type: "expect_outbound", |
| 1741 | label: `permission.response:${toolName}`, |
| 1742 | frame: makeClaudePermissionResponseFrame(result), |
| 1743 | }); |
| 1744 | return result; |
| 1745 | } |
| 1746 | : undefined; |
| 1747 | const options = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 1748 | modelSelection: input.modelSelection, |
| 1749 | nativeThreadId: input.sessionId, |
| 1750 | resume: false, |
| 1751 | cwd: input.cwd, |
| 1752 | ...(input.enableTools === true |
| 1753 | ? { |
| 1754 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 1755 | permissionMode: input.permissionMode ?? "default", |
| 1756 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 1757 | ...(input.disallowedTools === undefined |
| 1758 | ? {} |
| 1759 | : { disallowedTools: input.disallowedTools }), |
| 1760 | ...(input.allowDangerouslySkipPermissions === true |
| 1761 | ? { allowDangerouslySkipPermissions: true } |
| 1762 | : {}), |
| 1763 | ...(canUseTool === undefined ? {} : { canUseTool }), |
| 1764 | } |
| 1765 | : {}), |
| 1766 | }); |
| 1767 | input.entries.push({ |
| 1768 | type: "expect_outbound", |
| 1769 | label: "query.open", |
| 1770 | frame: makeClaudeQueryOpenFrame({ options }), |
| 1771 | }); |
| 1772 | const queryRuntime = await openRecordingQuery({ |
| 1773 | prompt: promptQueue, |
| 1774 | options, |
| 1775 | }); |
| 1776 | const iterator = queryRuntime[Symbol.asyncIterator](); |
| 1777 | try { |
| 1778 | offerPrompt(0); |
| 1779 | offerSteeringPrompts(); |
| 1780 | const completed = await recordMessagesUntilTurnResults({ |
| 1781 | iterator, |
| 1782 | entries: input.entries, |
| 1783 | scenario: input.scenario, |
| 1784 | resultCount: input.prompts.length, |
| 1785 | }); |
| 1786 | if (!completed) { |
| 1787 | throw new Error("Claude active steering query ended before the turn completed."); |
| 1788 | } |
| 1789 | promptQueue.close(); |
| 1790 | queryRuntime.close(); |
| 1791 | input.entries.push({ |
| 1792 | type: "runtime_exit", |
| 1793 | status: "success", |
| 1794 | }); |
| 1795 | } catch (error) { |
| 1796 | promptQueue.close(); |
| 1797 | queryRuntime.close(); |
| 1798 | input.entries.push({ |
| 1799 | type: "runtime_exit", |
| 1800 | status: "error", |
| 1801 | error: serializeReplayError(error, input.scenario), |
| 1802 | }); |
| 1803 | throw error; |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | async function recordClaudeRestartingQueries(input: { |
| 1808 | readonly scenario: string; |
| 1809 | readonly prompts: ReadonlyArray<string>; |
| 1810 | readonly modelSelection: ModelSelection; |
| 1811 | readonly cwd: string; |
| 1812 | readonly sessionId: string; |
| 1813 | readonly entries: Array<ProviderReplayEntry>; |
| 1814 | readonly enableTools?: boolean; |
| 1815 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 1816 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 1817 | readonly allowedTools?: ReadonlyArray<string>; |
| 1818 | readonly disallowedTools?: ReadonlyArray<string>; |
| 1819 | readonly allowDangerouslySkipPermissions?: boolean; |
| 1820 | }): Promise<void> { |
| 1821 | for (const [index, prompt] of input.prompts.entries()) { |
| 1822 | const promptQueue = new RecordingPromptQueue(); |
| 1823 | const options = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 1824 | modelSelection: input.modelSelection, |
| 1825 | nativeThreadId: input.sessionId, |
| 1826 | resume: index > 0, |
| 1827 | cwd: input.cwd, |
| 1828 | ...(input.enableTools === true |
| 1829 | ? { |
| 1830 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 1831 | permissionMode: input.permissionMode ?? "default", |
| 1832 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 1833 | ...(input.disallowedTools === undefined |
| 1834 | ? {} |
| 1835 | : { disallowedTools: input.disallowedTools }), |
| 1836 | ...(input.allowDangerouslySkipPermissions === true |
| 1837 | ? { allowDangerouslySkipPermissions: true } |
| 1838 | : {}), |
| 1839 | } |
| 1840 | : {}), |
| 1841 | }); |
| 1842 | |
| 1843 | input.entries.push({ |
| 1844 | type: "expect_outbound", |
| 1845 | label: `query.open:${index + 1}`, |
| 1846 | frame: makeClaudeQueryOpenFrame({ options }), |
| 1847 | }); |
| 1848 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt }); |
| 1849 | input.entries.push({ |
| 1850 | type: "expect_outbound", |
| 1851 | label: `prompt.offer:${index + 1}`, |
| 1852 | frame: makeClaudePromptOfferFrame(message), |
| 1853 | }); |
| 1854 | |
| 1855 | try { |
| 1856 | const queryRuntime = await openRecordingQuery({ |
| 1857 | prompt: promptQueue, |
| 1858 | options, |
| 1859 | }); |
| 1860 | promptQueue.offer(message); |
| 1861 | promptQueue.close(); |
| 1862 | const iterator = queryRuntime[Symbol.asyncIterator](); |
| 1863 | for (;;) { |
| 1864 | const next = await iterator.next(); |
| 1865 | if (next.done === true) { |
| 1866 | break; |
| 1867 | } |
| 1868 | const replayMessage = sanitizeSdkMessageForReplay({ |
| 1869 | message: next.value, |
| 1870 | scenario: input.scenario, |
| 1871 | }); |
| 1872 | input.entries.push({ |
| 1873 | type: "emit_inbound", |
| 1874 | label: replayMessage.type, |
| 1875 | frame: replayMessage, |
| 1876 | }); |
| 1877 | } |
| 1878 | input.entries.push({ |
| 1879 | type: "runtime_exit", |
| 1880 | status: "success", |
| 1881 | }); |
| 1882 | } catch (error) { |
| 1883 | promptQueue.close(); |
| 1884 | input.entries.push({ |
| 1885 | type: "runtime_exit", |
| 1886 | status: "error", |
| 1887 | error: serializeReplayError(error, input.scenario), |
| 1888 | }); |
| 1889 | throw error; |
| 1890 | } |
| 1891 | } |
| 1892 | } |
| 1893 | |
| 1894 | async function recordClaudeResumeAtCursorQuery(input: { |
| 1895 | readonly scenario: string; |
| 1896 | readonly prompts: ReadonlyArray<string>; |
| 1897 | readonly modelSelection: ModelSelection; |
| 1898 | readonly cwd: string; |
| 1899 | readonly sessionId: string; |
| 1900 | readonly entries: Array<ProviderReplayEntry>; |
| 1901 | readonly metadata: Record<string, unknown>; |
| 1902 | readonly enableTools?: boolean; |
| 1903 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 1904 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 1905 | readonly allowedTools?: ReadonlyArray<string>; |
| 1906 | readonly disallowedTools?: ReadonlyArray<string>; |
| 1907 | readonly allowDangerouslySkipPermissions?: boolean; |
| 1908 | }): Promise<void> { |
| 1909 | if (input.prompts.length !== 3) { |
| 1910 | throw new Error( |
| 1911 | `Claude resume-at-cursor replay scenario ${input.scenario} requires exactly three prompts.`, |
| 1912 | ); |
| 1913 | } |
| 1914 | |
| 1915 | const sourcePromptQueue = new RecordingPromptQueue(); |
| 1916 | const sourceOptions = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 1917 | modelSelection: input.modelSelection, |
| 1918 | nativeThreadId: input.sessionId, |
| 1919 | resume: false, |
| 1920 | cwd: input.cwd, |
| 1921 | ...(input.enableTools === true |
| 1922 | ? { |
| 1923 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 1924 | permissionMode: input.permissionMode ?? "default", |
| 1925 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 1926 | ...(input.disallowedTools === undefined |
| 1927 | ? {} |
| 1928 | : { disallowedTools: input.disallowedTools }), |
| 1929 | ...(input.allowDangerouslySkipPermissions === true |
| 1930 | ? { allowDangerouslySkipPermissions: true } |
| 1931 | : {}), |
| 1932 | } |
| 1933 | : {}), |
| 1934 | }); |
| 1935 | |
| 1936 | input.entries.push({ |
| 1937 | type: "expect_outbound", |
| 1938 | label: "query.open:source", |
| 1939 | frame: makeClaudeQueryOpenFrame({ options: sourceOptions }), |
| 1940 | }); |
| 1941 | const sourceRuntime = await openRecordingQuery({ |
| 1942 | prompt: sourcePromptQueue, |
| 1943 | options: sourceOptions, |
| 1944 | }); |
| 1945 | const sourceIterator = sourceRuntime[Symbol.asyncIterator](); |
| 1946 | |
| 1947 | try { |
| 1948 | const sourceCursors: Array<SDKAssistantMessage["uuid"]> = []; |
| 1949 | for (const [index, prompt] of input.prompts.slice(0, 2).entries()) { |
| 1950 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt }); |
| 1951 | input.entries.push({ |
| 1952 | type: "expect_outbound", |
| 1953 | label: `prompt.offer:${index + 1}`, |
| 1954 | frame: makeClaudePromptOfferFrame(message), |
| 1955 | }); |
| 1956 | sourcePromptQueue.offer(message); |
| 1957 | const result = await recordMessagesUntilTurnResultWithCursor({ |
| 1958 | iterator: sourceIterator, |
| 1959 | entries: input.entries, |
| 1960 | scenario: input.scenario, |
| 1961 | }); |
| 1962 | if (!result.completed) { |
| 1963 | throw new Error(`Claude source query ended before prompt ${index + 1} completed.`); |
| 1964 | } |
| 1965 | sourceCursors.push( |
| 1966 | requireAssistantCursor({ |
| 1967 | scenario: input.scenario, |
| 1968 | promptIndex: index + 1, |
| 1969 | cursor: result.assistantMessageUuid, |
| 1970 | }), |
| 1971 | ); |
| 1972 | } |
| 1973 | sourcePromptQueue.close(); |
| 1974 | sourceRuntime.close(); |
| 1975 | input.entries.push({ |
| 1976 | type: "runtime_exit", |
| 1977 | status: "success", |
| 1978 | }); |
| 1979 | |
| 1980 | const resumeSessionAt = sourceCursors[0]!; |
| 1981 | input.metadata.resumeSessionAt = resumeSessionAt; |
| 1982 | input.metadata.sourceAssistantMessageUuids = sourceCursors; |
| 1983 | |
| 1984 | const resumedPromptQueue = new RecordingPromptQueue(); |
| 1985 | const resumedOptions = { |
| 1986 | ...ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 1987 | modelSelection: input.modelSelection, |
| 1988 | nativeThreadId: input.sessionId, |
| 1989 | resume: true, |
| 1990 | cwd: input.cwd, |
| 1991 | ...(input.enableTools === true |
| 1992 | ? { |
| 1993 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 1994 | permissionMode: input.permissionMode ?? "default", |
| 1995 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 1996 | ...(input.disallowedTools === undefined |
| 1997 | ? {} |
| 1998 | : { disallowedTools: input.disallowedTools }), |
| 1999 | ...(input.allowDangerouslySkipPermissions === true |
| 2000 | ? { allowDangerouslySkipPermissions: true } |
| 2001 | : {}), |
| 2002 | } |
| 2003 | : {}), |
| 2004 | }), |
| 2005 | resumeSessionAt, |
| 2006 | } satisfies ClaudeAdapterV2.ClaudeAgentSdkQueryOptions; |
| 2007 | input.entries.push({ |
| 2008 | type: "expect_outbound", |
| 2009 | label: "query.open:resume_at_cursor", |
| 2010 | frame: makeClaudeQueryOpenFrame({ options: resumedOptions }), |
| 2011 | }); |
| 2012 | const resumedMessage = ClaudeAdapterV2.makeClaudeUserMessage({ text: input.prompts[2]! }); |
| 2013 | input.entries.push({ |
| 2014 | type: "expect_outbound", |
| 2015 | label: "prompt.offer:3", |
| 2016 | frame: makeClaudePromptOfferFrame(resumedMessage), |
| 2017 | }); |
| 2018 | |
| 2019 | const resumedRuntime = await openRecordingQuery({ |
| 2020 | prompt: resumedPromptQueue, |
| 2021 | options: resumedOptions, |
| 2022 | }); |
| 2023 | resumedPromptQueue.offer(resumedMessage); |
| 2024 | resumedPromptQueue.close(); |
| 2025 | const resumedIterator = resumedRuntime[Symbol.asyncIterator](); |
| 2026 | const resumed = await recordMessagesUntilTurnResultAndFinalize({ |
| 2027 | iterator: resumedIterator, |
| 2028 | entries: input.entries, |
| 2029 | scenario: input.scenario, |
| 2030 | finalize: () => { |
| 2031 | resumedPromptQueue.close(); |
| 2032 | resumedRuntime.close(); |
| 2033 | }, |
| 2034 | }); |
| 2035 | if (!resumed) { |
| 2036 | throw new Error("Claude resumed query ended before prompt 3 completed."); |
| 2037 | } |
| 2038 | input.entries.push({ |
| 2039 | type: "runtime_exit", |
| 2040 | status: "success", |
| 2041 | }); |
| 2042 | } catch (error) { |
| 2043 | sourcePromptQueue.close(); |
| 2044 | sourceRuntime.close(); |
| 2045 | input.entries.push({ |
| 2046 | type: "runtime_exit", |
| 2047 | status: "error", |
| 2048 | error: serializeReplayError(error, input.scenario), |
| 2049 | }); |
| 2050 | throw error; |
| 2051 | } |
| 2052 | } |
| 2053 | |
| 2054 | async function recordClaudeForkSessionQuery(input: { |
| 2055 | readonly scenario: string; |
| 2056 | readonly prompts: ReadonlyArray<string>; |
| 2057 | readonly modelSelection: ModelSelection; |
| 2058 | readonly cwd: string; |
| 2059 | readonly sessionId: string; |
| 2060 | readonly entries: Array<ProviderReplayEntry>; |
| 2061 | readonly metadata: Record<string, unknown>; |
| 2062 | readonly forkFromPromptIndex?: 1 | 2; |
| 2063 | readonly sourcePromptCount?: number; |
| 2064 | readonly forkPromptGroups?: ReadonlyArray<ReadonlyArray<string>>; |
| 2065 | readonly sourceContinuationPromptCount?: number; |
| 2066 | readonly enableTools?: boolean; |
| 2067 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 2068 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 2069 | readonly allowedTools?: ReadonlyArray<string>; |
| 2070 | readonly disallowedTools?: ReadonlyArray<string>; |
| 2071 | readonly allowDangerouslySkipPermissions?: boolean; |
| 2072 | }): Promise<void> { |
| 2073 | if (input.prompts.length < 2) { |
| 2074 | throw new Error( |
| 2075 | `Claude fork-session replay scenario ${input.scenario} requires at least two prompts.`, |
| 2076 | ); |
| 2077 | } |
| 2078 | const sourceContinuationPromptCount = input.sourceContinuationPromptCount ?? 0; |
| 2079 | const forkPromptEnd = input.prompts.length - sourceContinuationPromptCount; |
| 2080 | const sourcePromptCount = input.sourcePromptCount ?? forkPromptEnd - 1; |
| 2081 | if ( |
| 2082 | sourceContinuationPromptCount < 0 || |
| 2083 | sourceContinuationPromptCount >= input.prompts.length || |
| 2084 | sourcePromptCount < 1 || |
| 2085 | sourcePromptCount >= forkPromptEnd |
| 2086 | ) { |
| 2087 | throw new Error( |
| 2088 | `Claude fork-session replay scenario ${input.scenario} requires at least one source prompt and one fork prompt.`, |
| 2089 | ); |
| 2090 | } |
| 2091 | const forkFromPromptIndex = input.forkFromPromptIndex ?? sourcePromptCount; |
| 2092 | if (forkFromPromptIndex > sourcePromptCount) { |
| 2093 | throw new Error( |
| 2094 | `Claude fork-session replay scenario ${input.scenario} cannot fork from prompt ${forkFromPromptIndex} after recording ${sourcePromptCount} source prompts.`, |
| 2095 | ); |
| 2096 | } |
| 2097 | |
| 2098 | const sourcePromptQueue = new RecordingPromptQueue(); |
| 2099 | const sourceOptions = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 2100 | modelSelection: input.modelSelection, |
| 2101 | nativeThreadId: input.sessionId, |
| 2102 | resume: false, |
| 2103 | cwd: input.cwd, |
| 2104 | ...(input.enableTools === true |
| 2105 | ? { |
| 2106 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 2107 | permissionMode: input.permissionMode ?? "default", |
| 2108 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2109 | ...(input.disallowedTools === undefined |
| 2110 | ? {} |
| 2111 | : { disallowedTools: input.disallowedTools }), |
| 2112 | ...(input.allowDangerouslySkipPermissions === true |
| 2113 | ? { allowDangerouslySkipPermissions: true } |
| 2114 | : {}), |
| 2115 | } |
| 2116 | : {}), |
| 2117 | }); |
| 2118 | input.entries.push({ |
| 2119 | type: "expect_outbound", |
| 2120 | label: "query.open:source", |
| 2121 | frame: makeClaudeQueryOpenFrame({ options: sourceOptions }), |
| 2122 | }); |
| 2123 | const sourceRuntime = await openRecordingQuery({ |
| 2124 | prompt: sourcePromptQueue, |
| 2125 | options: sourceOptions, |
| 2126 | }); |
| 2127 | const sourceIterator = sourceRuntime[Symbol.asyncIterator](); |
| 2128 | |
| 2129 | try { |
| 2130 | const sourceCursors: Array<SDKAssistantMessage["uuid"]> = []; |
| 2131 | for (const [index, prompt] of input.prompts.slice(0, sourcePromptCount).entries()) { |
| 2132 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt }); |
| 2133 | input.entries.push({ |
| 2134 | type: "expect_outbound", |
| 2135 | label: `prompt.offer:${index + 1}`, |
| 2136 | frame: makeClaudePromptOfferFrame(message), |
| 2137 | }); |
| 2138 | sourcePromptQueue.offer(message); |
| 2139 | const result = await recordMessagesUntilTurnResultWithCursor({ |
| 2140 | iterator: sourceIterator, |
| 2141 | entries: input.entries, |
| 2142 | scenario: input.scenario, |
| 2143 | }); |
| 2144 | if (!result.completed) { |
| 2145 | throw new Error(`Claude source query ended before prompt ${index + 1} completed.`); |
| 2146 | } |
| 2147 | sourceCursors.push( |
| 2148 | requireAssistantCursor({ |
| 2149 | scenario: input.scenario, |
| 2150 | promptIndex: index + 1, |
| 2151 | cursor: result.assistantMessageUuid, |
| 2152 | }), |
| 2153 | ); |
| 2154 | } |
| 2155 | sourcePromptQueue.close(); |
| 2156 | sourceRuntime.close(); |
| 2157 | input.entries.push({ |
| 2158 | type: "runtime_exit", |
| 2159 | status: "success", |
| 2160 | }); |
| 2161 | |
| 2162 | const upToMessageId = sourceCursors[forkFromPromptIndex - 1]!; |
| 2163 | const forkPrompts = input.prompts.slice(sourcePromptCount, forkPromptEnd); |
| 2164 | const forkPromptGroups = input.forkPromptGroups ?? [forkPrompts]; |
| 2165 | if ( |
| 2166 | forkPromptGroups.length === 0 || |
| 2167 | forkPromptGroups.some((group) => group.length === 0) || |
| 2168 | forkPromptGroups.flat().join("\n") !== forkPrompts.join("\n") |
| 2169 | ) { |
| 2170 | throw new Error( |
| 2171 | `Claude fork-session replay scenario ${input.scenario} has invalid fork prompt groups.`, |
| 2172 | ); |
| 2173 | } |
| 2174 | input.metadata.sourceAssistantMessageUuids = sourceCursors; |
| 2175 | input.metadata.forkUpToMessageId = upToMessageId; |
| 2176 | const forkedNativeSessionIds: Array<string> = []; |
| 2177 | let promptOrdinal = sourcePromptCount; |
| 2178 | for (const [groupIndex, forkPrompts] of forkPromptGroups.entries()) { |
| 2179 | const labelSuffix = forkPromptGroups.length === 1 ? "" : `:${groupIndex + 1}`; |
| 2180 | input.entries.push({ |
| 2181 | type: "expect_outbound", |
| 2182 | label: `session.fork${labelSuffix}`, |
| 2183 | frame: { |
| 2184 | type: "session.fork", |
| 2185 | sessionId: input.sessionId, |
| 2186 | options: { |
| 2187 | upToMessageId, |
| 2188 | }, |
| 2189 | }, |
| 2190 | }); |
| 2191 | const forked = await forkSession(input.sessionId, { upToMessageId }); |
| 2192 | forkedNativeSessionIds.push(forked.sessionId); |
| 2193 | input.entries.push({ |
| 2194 | type: "emit_inbound", |
| 2195 | label: `session.forked${labelSuffix}`, |
| 2196 | frame: { |
| 2197 | type: "session.forked", |
| 2198 | sessionId: forked.sessionId, |
| 2199 | }, |
| 2200 | }); |
| 2201 | |
| 2202 | const targetPromptQueue = new RecordingPromptQueue(); |
| 2203 | const targetOptions = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 2204 | modelSelection: input.modelSelection, |
| 2205 | nativeThreadId: forked.sessionId, |
| 2206 | resume: true, |
| 2207 | cwd: input.cwd, |
| 2208 | ...(input.enableTools === true |
| 2209 | ? { |
| 2210 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 2211 | permissionMode: input.permissionMode ?? "default", |
| 2212 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2213 | ...(input.disallowedTools === undefined |
| 2214 | ? {} |
| 2215 | : { disallowedTools: input.disallowedTools }), |
| 2216 | ...(input.allowDangerouslySkipPermissions === true |
| 2217 | ? { allowDangerouslySkipPermissions: true } |
| 2218 | : {}), |
| 2219 | } |
| 2220 | : {}), |
| 2221 | }); |
| 2222 | input.entries.push({ |
| 2223 | type: "expect_outbound", |
| 2224 | label: `query.open:fork${labelSuffix}`, |
| 2225 | frame: makeClaudeQueryOpenFrame({ options: targetOptions }), |
| 2226 | }); |
| 2227 | const targetRuntime = await openRecordingQuery({ |
| 2228 | prompt: targetPromptQueue, |
| 2229 | options: targetOptions, |
| 2230 | }); |
| 2231 | const targetIterator = targetRuntime[Symbol.asyncIterator](); |
| 2232 | for (const prompt of forkPrompts) { |
| 2233 | promptOrdinal += 1; |
| 2234 | const targetMessage = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt }); |
| 2235 | input.entries.push({ |
| 2236 | type: "expect_outbound", |
| 2237 | label: `prompt.offer:${promptOrdinal}`, |
| 2238 | frame: makeClaudePromptOfferFrame(targetMessage), |
| 2239 | }); |
| 2240 | targetPromptQueue.offer(targetMessage); |
| 2241 | const completed = await recordMessagesUntilTurnResult({ |
| 2242 | iterator: targetIterator, |
| 2243 | entries: input.entries, |
| 2244 | scenario: input.scenario, |
| 2245 | }); |
| 2246 | if (!completed) { |
| 2247 | throw new Error(`Claude fork query ended before prompt ${promptOrdinal} completed.`); |
| 2248 | } |
| 2249 | } |
| 2250 | targetPromptQueue.close(); |
| 2251 | targetRuntime.close(); |
| 2252 | input.entries.push({ |
| 2253 | type: "runtime_exit", |
| 2254 | status: "success", |
| 2255 | }); |
| 2256 | } |
| 2257 | input.metadata.forkedNativeSessionId = forkedNativeSessionIds[0]; |
| 2258 | input.metadata.forkedNativeSessionIds = forkedNativeSessionIds; |
| 2259 | if (sourceContinuationPromptCount > 0) { |
| 2260 | const continuationPromptQueue = new RecordingPromptQueue(); |
| 2261 | const continuationOptions = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 2262 | modelSelection: input.modelSelection, |
| 2263 | nativeThreadId: input.sessionId, |
| 2264 | resume: true, |
| 2265 | cwd: input.cwd, |
| 2266 | ...(input.enableTools === true |
| 2267 | ? { |
| 2268 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 2269 | permissionMode: input.permissionMode ?? "default", |
| 2270 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2271 | ...(input.disallowedTools === undefined |
| 2272 | ? {} |
| 2273 | : { disallowedTools: input.disallowedTools }), |
| 2274 | ...(input.allowDangerouslySkipPermissions === true |
| 2275 | ? { allowDangerouslySkipPermissions: true } |
| 2276 | : {}), |
| 2277 | } |
| 2278 | : {}), |
| 2279 | }); |
| 2280 | input.entries.push({ |
| 2281 | type: "expect_outbound", |
| 2282 | label: "query.open:source-continuation", |
| 2283 | frame: makeClaudeQueryOpenFrame({ options: continuationOptions }), |
| 2284 | }); |
| 2285 | const continuationRuntime = await openRecordingQuery({ |
| 2286 | prompt: continuationPromptQueue, |
| 2287 | options: continuationOptions, |
| 2288 | }); |
| 2289 | const continuationIterator = continuationRuntime[Symbol.asyncIterator](); |
| 2290 | for (const prompt of input.prompts.slice(forkPromptEnd)) { |
| 2291 | promptOrdinal += 1; |
| 2292 | const continuationMessage = ClaudeAdapterV2.makeClaudeUserMessage({ text: prompt }); |
| 2293 | input.entries.push({ |
| 2294 | type: "expect_outbound", |
| 2295 | label: `prompt.offer:${promptOrdinal}`, |
| 2296 | frame: makeClaudePromptOfferFrame(continuationMessage), |
| 2297 | }); |
| 2298 | continuationPromptQueue.offer(continuationMessage); |
| 2299 | const completed = await recordMessagesUntilTurnResult({ |
| 2300 | iterator: continuationIterator, |
| 2301 | entries: input.entries, |
| 2302 | scenario: input.scenario, |
| 2303 | }); |
| 2304 | if (!completed) { |
| 2305 | throw new Error( |
| 2306 | `Claude source continuation ended before prompt ${promptOrdinal} completed.`, |
| 2307 | ); |
| 2308 | } |
| 2309 | } |
| 2310 | continuationPromptQueue.close(); |
| 2311 | continuationRuntime.close(); |
| 2312 | input.entries.push({ |
| 2313 | type: "runtime_exit", |
| 2314 | status: "success", |
| 2315 | }); |
| 2316 | input.metadata.sourceContinuationPromptCount = sourceContinuationPromptCount; |
| 2317 | } |
| 2318 | } catch (error) { |
| 2319 | sourcePromptQueue.close(); |
| 2320 | sourceRuntime.close(); |
| 2321 | input.entries.push({ |
| 2322 | type: "runtime_exit", |
| 2323 | status: "error", |
| 2324 | error: serializeReplayError(error, input.scenario), |
| 2325 | }); |
| 2326 | throw error; |
| 2327 | } |
| 2328 | } |
| 2329 | |
| 2330 | async function recordInterruptedClaudeQuery(input: { |
| 2331 | readonly scenario: string; |
| 2332 | readonly prompt: string; |
| 2333 | readonly modelSelection: ModelSelection; |
| 2334 | readonly cwd: string; |
| 2335 | readonly sessionId: string; |
| 2336 | readonly resume: boolean; |
| 2337 | readonly entries: Array<ProviderReplayEntry>; |
| 2338 | readonly queryOpenLabel: string; |
| 2339 | readonly promptOfferLabel: string; |
| 2340 | readonly interruptLabel: string; |
| 2341 | readonly interruptAfter?: "prompt_offer" | "tool_use"; |
| 2342 | readonly interruptAfterToolUses?: number; |
| 2343 | readonly enableTools?: boolean; |
| 2344 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 2345 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 2346 | readonly allowedTools?: ReadonlyArray<string>; |
| 2347 | readonly disallowedTools?: ReadonlyArray<string>; |
| 2348 | readonly allowDangerouslySkipPermissions?: boolean; |
| 2349 | }): Promise<void> { |
| 2350 | const promptQueue = new RecordingPromptQueue(); |
| 2351 | const options = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 2352 | modelSelection: input.modelSelection, |
| 2353 | nativeThreadId: input.sessionId, |
| 2354 | resume: input.resume, |
| 2355 | cwd: input.cwd, |
| 2356 | ...(input.enableTools === true |
| 2357 | ? { |
| 2358 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 2359 | permissionMode: input.permissionMode ?? "default", |
| 2360 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2361 | ...(input.disallowedTools === undefined |
| 2362 | ? {} |
| 2363 | : { disallowedTools: input.disallowedTools }), |
| 2364 | ...(input.allowDangerouslySkipPermissions === true |
| 2365 | ? { allowDangerouslySkipPermissions: true } |
| 2366 | : {}), |
| 2367 | } |
| 2368 | : {}), |
| 2369 | }); |
| 2370 | input.entries.push({ |
| 2371 | type: "expect_outbound", |
| 2372 | label: input.queryOpenLabel, |
| 2373 | frame: makeClaudeQueryOpenFrame({ options }), |
| 2374 | }); |
| 2375 | const runtime = await openRecordingQuery({ |
| 2376 | prompt: promptQueue, |
| 2377 | options, |
| 2378 | }); |
| 2379 | const iterator = runtime[Symbol.asyncIterator](); |
| 2380 | const message = ClaudeAdapterV2.makeClaudeUserMessage({ text: input.prompt }); |
| 2381 | input.entries.push({ |
| 2382 | type: "expect_outbound", |
| 2383 | label: input.promptOfferLabel, |
| 2384 | frame: makeClaudePromptOfferFrame(message), |
| 2385 | }); |
| 2386 | promptQueue.offer(message); |
| 2387 | |
| 2388 | try { |
| 2389 | if (input.interruptAfter === "tool_use") { |
| 2390 | await recordMessagesUntilToolUse({ |
| 2391 | iterator, |
| 2392 | entries: input.entries, |
| 2393 | scenario: input.scenario, |
| 2394 | toolUseCount: input.interruptAfterToolUses ?? 1, |
| 2395 | }); |
| 2396 | await Effect.runPromise(Effect.sleep(Duration.millis(250))); |
| 2397 | } |
| 2398 | input.entries.push({ |
| 2399 | type: "expect_outbound", |
| 2400 | label: input.interruptLabel, |
| 2401 | frame: { type: "query.interrupt" }, |
| 2402 | }); |
| 2403 | |
| 2404 | let cancelledError: unknown; |
| 2405 | try { |
| 2406 | await runtime.interrupt(); |
| 2407 | } catch (error) { |
| 2408 | cancelledError = error; |
| 2409 | } |
| 2410 | promptQueue.close(); |
| 2411 | runtime.close(); |
| 2412 | try { |
| 2413 | await recordMessagesUntilIteratorDone({ |
| 2414 | iterator, |
| 2415 | entries: input.entries, |
| 2416 | scenario: input.scenario, |
| 2417 | }); |
| 2418 | } catch (error) { |
| 2419 | cancelledError = error; |
| 2420 | } |
| 2421 | input.entries.push({ |
| 2422 | type: "runtime_exit", |
| 2423 | status: cancelledError === undefined ? "success" : "cancelled", |
| 2424 | ...(cancelledError === undefined |
| 2425 | ? {} |
| 2426 | : { error: serializeReplayError(cancelledError, input.scenario) }), |
| 2427 | }); |
| 2428 | } catch (error) { |
| 2429 | promptQueue.close(); |
| 2430 | runtime.close(); |
| 2431 | input.entries.push({ |
| 2432 | type: "runtime_exit", |
| 2433 | status: "error", |
| 2434 | error: serializeReplayError(error, input.scenario), |
| 2435 | }); |
| 2436 | throw error; |
| 2437 | } |
| 2438 | } |
| 2439 | |
| 2440 | async function recordClaudeInterruptQuery(input: { |
| 2441 | readonly scenario: string; |
| 2442 | readonly prompts: ReadonlyArray<string>; |
| 2443 | readonly modelSelection: ModelSelection; |
| 2444 | readonly cwd: string; |
| 2445 | readonly sessionId: string; |
| 2446 | readonly entries: Array<ProviderReplayEntry>; |
| 2447 | readonly enableTools?: boolean; |
| 2448 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 2449 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 2450 | readonly allowedTools?: ReadonlyArray<string>; |
| 2451 | readonly disallowedTools?: ReadonlyArray<string>; |
| 2452 | readonly allowDangerouslySkipPermissions?: boolean; |
| 2453 | readonly interruptAfter?: "prompt_offer" | "tool_use"; |
| 2454 | readonly interruptAfterToolUses?: number; |
| 2455 | }): Promise<void> { |
| 2456 | if (input.prompts.length !== 1) { |
| 2457 | throw new Error( |
| 2458 | `Claude interrupt replay scenario ${input.scenario} requires exactly one prompt.`, |
| 2459 | ); |
| 2460 | } |
| 2461 | |
| 2462 | await recordInterruptedClaudeQuery({ |
| 2463 | scenario: input.scenario, |
| 2464 | prompt: input.prompts[0]!, |
| 2465 | modelSelection: input.modelSelection, |
| 2466 | cwd: input.cwd, |
| 2467 | sessionId: input.sessionId, |
| 2468 | resume: false, |
| 2469 | entries: input.entries, |
| 2470 | queryOpenLabel: "query.open", |
| 2471 | promptOfferLabel: "prompt.offer:1", |
| 2472 | interruptLabel: "query.interrupt:1", |
| 2473 | ...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }), |
| 2474 | ...(input.interruptAfterToolUses === undefined |
| 2475 | ? {} |
| 2476 | : { interruptAfterToolUses: input.interruptAfterToolUses }), |
| 2477 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2478 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2479 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2480 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2481 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2482 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2483 | ? {} |
| 2484 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2485 | }); |
| 2486 | } |
| 2487 | |
| 2488 | async function recordClaudeInterruptRestartQuery(input: { |
| 2489 | readonly scenario: string; |
| 2490 | readonly prompts: ReadonlyArray<string>; |
| 2491 | readonly modelSelection: ModelSelection; |
| 2492 | readonly cwd: string; |
| 2493 | readonly sessionId: string; |
| 2494 | readonly entries: Array<ProviderReplayEntry>; |
| 2495 | readonly enableTools?: boolean; |
| 2496 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 2497 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 2498 | readonly allowedTools?: ReadonlyArray<string>; |
| 2499 | readonly disallowedTools?: ReadonlyArray<string>; |
| 2500 | readonly allowDangerouslySkipPermissions?: boolean; |
| 2501 | readonly interruptAfter?: "prompt_offer" | "tool_use"; |
| 2502 | }): Promise<void> { |
| 2503 | if (input.prompts.length !== 2) { |
| 2504 | throw new Error( |
| 2505 | `Claude interrupt-restart replay scenario ${input.scenario} requires exactly two prompts.`, |
| 2506 | ); |
| 2507 | } |
| 2508 | |
| 2509 | await recordInterruptedClaudeQuery({ |
| 2510 | scenario: input.scenario, |
| 2511 | prompt: input.prompts[0]!, |
| 2512 | modelSelection: input.modelSelection, |
| 2513 | cwd: input.cwd, |
| 2514 | sessionId: input.sessionId, |
| 2515 | resume: false, |
| 2516 | entries: input.entries, |
| 2517 | queryOpenLabel: "query.open:1", |
| 2518 | promptOfferLabel: "prompt.offer:1", |
| 2519 | interruptLabel: "query.interrupt:1", |
| 2520 | ...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }), |
| 2521 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2522 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2523 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2524 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2525 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2526 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2527 | ? {} |
| 2528 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2529 | }); |
| 2530 | |
| 2531 | const secondPromptQueue = new RecordingPromptQueue(); |
| 2532 | const secondOptions = ClaudeAdapterV2.makeClaudeQueryOptions({ |
| 2533 | modelSelection: input.modelSelection, |
| 2534 | nativeThreadId: input.sessionId, |
| 2535 | resume: true, |
| 2536 | cwd: input.cwd, |
| 2537 | ...(input.enableTools === true |
| 2538 | ? { |
| 2539 | tools: input.tools ?? { type: "preset", preset: "claude_code" }, |
| 2540 | permissionMode: input.permissionMode ?? "default", |
| 2541 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2542 | ...(input.disallowedTools === undefined |
| 2543 | ? {} |
| 2544 | : { disallowedTools: input.disallowedTools }), |
| 2545 | ...(input.allowDangerouslySkipPermissions === true |
| 2546 | ? { allowDangerouslySkipPermissions: true } |
| 2547 | : {}), |
| 2548 | } |
| 2549 | : {}), |
| 2550 | }); |
| 2551 | input.entries.push({ |
| 2552 | type: "expect_outbound", |
| 2553 | label: "query.open:2", |
| 2554 | frame: makeClaudeQueryOpenFrame({ options: secondOptions }), |
| 2555 | }); |
| 2556 | const secondMessage = ClaudeAdapterV2.makeClaudeUserMessage({ text: input.prompts[1]! }); |
| 2557 | input.entries.push({ |
| 2558 | type: "expect_outbound", |
| 2559 | label: "prompt.offer:2", |
| 2560 | frame: makeClaudePromptOfferFrame(secondMessage), |
| 2561 | }); |
| 2562 | |
| 2563 | try { |
| 2564 | const secondRuntime = await openRecordingQuery({ |
| 2565 | prompt: secondPromptQueue, |
| 2566 | options: secondOptions, |
| 2567 | }); |
| 2568 | secondPromptQueue.offer(secondMessage); |
| 2569 | secondPromptQueue.close(); |
| 2570 | const secondIterator = secondRuntime[Symbol.asyncIterator](); |
| 2571 | await recordMessagesUntilIteratorDone({ |
| 2572 | iterator: secondIterator, |
| 2573 | entries: input.entries, |
| 2574 | scenario: input.scenario, |
| 2575 | }); |
| 2576 | secondRuntime.close(); |
| 2577 | input.entries.push({ |
| 2578 | type: "runtime_exit", |
| 2579 | status: "success", |
| 2580 | }); |
| 2581 | } catch (error) { |
| 2582 | secondPromptQueue.close(); |
| 2583 | input.entries.push({ |
| 2584 | type: "runtime_exit", |
| 2585 | status: "error", |
| 2586 | error: serializeReplayError(error, input.scenario), |
| 2587 | }); |
| 2588 | throw error; |
| 2589 | } |
| 2590 | } |
| 2591 | |
| 2592 | export async function recordClaudeAgentSdkReplayTranscript(input: { |
| 2593 | readonly scenario: string; |
| 2594 | readonly prompts: ReadonlyArray<string>; |
| 2595 | readonly modelSelection: ModelSelection; |
| 2596 | readonly cwd: string; |
| 2597 | readonly sessionId?: string; |
| 2598 | readonly queryMode?: |
| 2599 | | "streaming" |
| 2600 | | "restart" |
| 2601 | | "resume_at_cursor" |
| 2602 | | "fork_session" |
| 2603 | | "fork_session_prior_turn" |
| 2604 | | "fork_session_merge_back_siblings" |
| 2605 | | "active_steering" |
| 2606 | | "interrupt" |
| 2607 | | "interrupt_restart"; |
| 2608 | readonly enableTools?: boolean; |
| 2609 | readonly tools?: ClaudeAdapterV2.ClaudeAgentSdkQueryTools; |
| 2610 | readonly permissionMode?: ClaudeAdapterV2.ClaudeAgentSdkQueryOptions["permissionMode"]; |
| 2611 | readonly allowedTools?: ReadonlyArray<string>; |
| 2612 | readonly disallowedTools?: ReadonlyArray<string>; |
| 2613 | readonly allowDangerouslySkipPermissions?: boolean; |
| 2614 | readonly enablePermissionCallback?: boolean; |
| 2615 | readonly permissionDecision?: ProviderApprovalDecision; |
| 2616 | readonly backgroundWakeCounts?: ReadonlyArray<number>; |
| 2617 | readonly offerNextPromptImmediately?: boolean; |
| 2618 | readonly interruptAfter?: "prompt_offer" | "tool_use"; |
| 2619 | readonly interruptAfterToolUses?: number; |
| 2620 | }): Promise<ClaudeAgentSdkReplayTranscript> { |
| 2621 | if (input.prompts.length === 0) { |
| 2622 | throw new Error( |
| 2623 | `Claude Agent SDK replay scenario ${input.scenario} needs at least one prompt.`, |
| 2624 | ); |
| 2625 | } |
| 2626 | |
| 2627 | const entries: Array<ProviderReplayEntry> = []; |
| 2628 | const sessionId = input.sessionId ?? (await Effect.runPromise(randomUuidV4)); |
| 2629 | const queryMode = input.queryMode ?? "streaming"; |
| 2630 | const recordingMetadata: Record<string, unknown> = {}; |
| 2631 | if (queryMode === "streaming") { |
| 2632 | await recordClaudeStreamingQuery({ |
| 2633 | scenario: input.scenario, |
| 2634 | prompts: input.prompts, |
| 2635 | modelSelection: input.modelSelection, |
| 2636 | cwd: input.cwd, |
| 2637 | sessionId, |
| 2638 | entries, |
| 2639 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2640 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2641 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2642 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2643 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2644 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2645 | ? {} |
| 2646 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2647 | ...(input.enablePermissionCallback === undefined |
| 2648 | ? {} |
| 2649 | : { enablePermissionCallback: input.enablePermissionCallback }), |
| 2650 | ...(input.backgroundWakeCounts === undefined |
| 2651 | ? {} |
| 2652 | : { backgroundWakeCounts: input.backgroundWakeCounts }), |
| 2653 | ...(input.offerNextPromptImmediately === undefined |
| 2654 | ? {} |
| 2655 | : { offerNextPromptImmediately: input.offerNextPromptImmediately }), |
| 2656 | ...(input.permissionDecision === undefined |
| 2657 | ? {} |
| 2658 | : { permissionDecision: input.permissionDecision }), |
| 2659 | }); |
| 2660 | } else if (queryMode === "active_steering") { |
| 2661 | await recordClaudeActiveSteeringQuery({ |
| 2662 | scenario: input.scenario, |
| 2663 | prompts: input.prompts, |
| 2664 | modelSelection: input.modelSelection, |
| 2665 | cwd: input.cwd, |
| 2666 | sessionId, |
| 2667 | entries, |
| 2668 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2669 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2670 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2671 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2672 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2673 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2674 | ? {} |
| 2675 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2676 | ...(input.enablePermissionCallback === undefined |
| 2677 | ? {} |
| 2678 | : { enablePermissionCallback: input.enablePermissionCallback }), |
| 2679 | ...(input.permissionDecision === undefined |
| 2680 | ? {} |
| 2681 | : { permissionDecision: input.permissionDecision }), |
| 2682 | }); |
| 2683 | } else if (queryMode === "restart") { |
| 2684 | await recordClaudeRestartingQueries({ |
| 2685 | scenario: input.scenario, |
| 2686 | prompts: input.prompts, |
| 2687 | modelSelection: input.modelSelection, |
| 2688 | cwd: input.cwd, |
| 2689 | sessionId, |
| 2690 | entries, |
| 2691 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2692 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2693 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2694 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2695 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2696 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2697 | ? {} |
| 2698 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2699 | }); |
| 2700 | } else if (queryMode === "resume_at_cursor") { |
| 2701 | await recordClaudeResumeAtCursorQuery({ |
| 2702 | scenario: input.scenario, |
| 2703 | prompts: input.prompts, |
| 2704 | modelSelection: input.modelSelection, |
| 2705 | cwd: input.cwd, |
| 2706 | sessionId, |
| 2707 | entries, |
| 2708 | metadata: recordingMetadata, |
| 2709 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2710 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2711 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2712 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2713 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2714 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2715 | ? {} |
| 2716 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2717 | }); |
| 2718 | } else if ( |
| 2719 | queryMode === "fork_session" || |
| 2720 | queryMode === "fork_session_prior_turn" || |
| 2721 | queryMode === "fork_session_merge_back_siblings" |
| 2722 | ) { |
| 2723 | await recordClaudeForkSessionQuery({ |
| 2724 | scenario: input.scenario, |
| 2725 | prompts: input.prompts, |
| 2726 | modelSelection: input.modelSelection, |
| 2727 | cwd: input.cwd, |
| 2728 | sessionId, |
| 2729 | entries, |
| 2730 | metadata: recordingMetadata, |
| 2731 | ...(queryMode === "fork_session_prior_turn" ? { forkFromPromptIndex: 1 as const } : {}), |
| 2732 | ...(queryMode === "fork_session_merge_back_siblings" |
| 2733 | ? { |
| 2734 | sourcePromptCount: 1, |
| 2735 | forkPromptGroups: [[input.prompts[1]!], [input.prompts[2]!]], |
| 2736 | sourceContinuationPromptCount: 3, |
| 2737 | } |
| 2738 | : {}), |
| 2739 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2740 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2741 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2742 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2743 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2744 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2745 | ? {} |
| 2746 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2747 | }); |
| 2748 | } else if (queryMode === "interrupt") { |
| 2749 | await recordClaudeInterruptQuery({ |
| 2750 | scenario: input.scenario, |
| 2751 | prompts: input.prompts, |
| 2752 | modelSelection: input.modelSelection, |
| 2753 | cwd: input.cwd, |
| 2754 | sessionId, |
| 2755 | entries, |
| 2756 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2757 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2758 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2759 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2760 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2761 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2762 | ? {} |
| 2763 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2764 | ...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }), |
| 2765 | ...(input.interruptAfterToolUses === undefined |
| 2766 | ? {} |
| 2767 | : { interruptAfterToolUses: input.interruptAfterToolUses }), |
| 2768 | }); |
| 2769 | } else { |
| 2770 | await recordClaudeInterruptRestartQuery({ |
| 2771 | scenario: input.scenario, |
| 2772 | prompts: input.prompts, |
| 2773 | modelSelection: input.modelSelection, |
| 2774 | cwd: input.cwd, |
| 2775 | sessionId, |
| 2776 | entries, |
| 2777 | ...(input.enableTools === undefined ? {} : { enableTools: input.enableTools }), |
| 2778 | ...(input.tools === undefined ? {} : { tools: input.tools }), |
| 2779 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2780 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2781 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2782 | ...(input.allowDangerouslySkipPermissions === undefined |
| 2783 | ? {} |
| 2784 | : { allowDangerouslySkipPermissions: input.allowDangerouslySkipPermissions }), |
| 2785 | ...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }), |
| 2786 | }); |
| 2787 | } |
| 2788 | |
| 2789 | return { |
| 2790 | provider: ClaudeAdapterV2.CLAUDE_PROVIDER, |
| 2791 | protocol: CLAUDE_AGENT_SDK_REPLAY_PROTOCOL, |
| 2792 | version: "0.2.111", |
| 2793 | scenario: input.scenario, |
| 2794 | metadata: { |
| 2795 | prompts: [...input.prompts], |
| 2796 | model: input.modelSelection.model, |
| 2797 | nativeSessionId: sessionId, |
| 2798 | queryMode, |
| 2799 | tools: input.enableTools === true ? (input.tools ?? "claude_code") : "none", |
| 2800 | ...(input.permissionMode === undefined ? {} : { permissionMode: input.permissionMode }), |
| 2801 | ...(input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools }), |
| 2802 | ...(input.disallowedTools === undefined ? {} : { disallowedTools: input.disallowedTools }), |
| 2803 | ...(input.enablePermissionCallback === undefined |
| 2804 | ? {} |
| 2805 | : { enablePermissionCallback: input.enablePermissionCallback }), |
| 2806 | ...(input.permissionDecision === undefined |
| 2807 | ? {} |
| 2808 | : { permissionDecision: input.permissionDecision }), |
| 2809 | ...(input.backgroundWakeCounts === undefined |
| 2810 | ? {} |
| 2811 | : { backgroundWakeCounts: [...input.backgroundWakeCounts] }), |
| 2812 | ...(input.offerNextPromptImmediately === true ? { offerNextPromptImmediately: true } : {}), |
| 2813 | ...(input.interruptAfter === undefined ? {} : { interruptAfter: input.interruptAfter }), |
| 2814 | ...(input.interruptAfterToolUses === undefined |
| 2815 | ? {} |
| 2816 | : { interruptAfterToolUses: input.interruptAfterToolUses }), |
| 2817 | generatedBy: "recordClaudeAgentSdkReplayTranscript", |
| 2818 | ...recordingMetadata, |
| 2819 | }, |
| 2820 | entries, |
| 2821 | }; |
| 2822 | } |
| 2823 | |
| 2824 | const decodeClaudeAgentSdkReplayTranscript = Schema.decodeUnknownEffect( |
| 2825 | ClaudeAgentSdkReplayTranscript, |
| 2826 | ); |
| 2827 | |
| 2828 | export const ClaudeOrchestratorReplayHarness: OrchestratorV2ProviderReplayHarness< |
| 2829 | ClaudeAgentSdkReplayTranscript, |
| 2830 | ClaudeOrchestratorReplayHarnessError |
| 2831 | > = { |
| 2832 | driver: ClaudeAdapterV2.CLAUDE_PROVIDER, |
| 2833 | decodeTranscript: (transcript) => |
| 2834 | decodeClaudeAgentSdkReplayTranscript(transcript).pipe( |
| 2835 | Effect.mapError( |
| 2836 | (cause) => |
| 2837 | new ClaudeReplayTranscriptDecodeError({ |
| 2838 | ...metadataFromTranscript(transcript), |
| 2839 | cause, |
| 2840 | }), |
| 2841 | ), |
| 2842 | ), |
| 2843 | makeProviderAdapterRegistryLayer: (transcript, options) => |
| 2844 | layerClaudeProviderAdapterRegistryReplay(transcript, options), |
| 2845 | }; |
| 2846 | |
| 2847 | export function makeClaudeRestartReplayHarness(transcript: ClaudeAgentSdkReplayTranscript) { |
| 2848 | const queryRunner = makeReplayQueryRunner(transcript); |
| 2849 | return { |
| 2850 | harness: { |
| 2851 | ...ClaudeOrchestratorReplayHarness, |
| 2852 | makeProviderAdapterRegistryLayer: (replayed) => |
| 2853 | layerClaudeProviderAdapterRegistryReplay(replayed, { queryRunner }), |
| 2854 | } satisfies typeof ClaudeOrchestratorReplayHarness, |
| 2855 | assertComplete: replayQueryRunnerService(transcript, queryRunner).assertComplete, |
| 2856 | }; |
| 2857 | } |