({
promptMessages,
cacheSafeParams,
canUseTool,
querySource,
forkLabel,
overrides,
maxOutputTokens,
maxTurns,
onMessage,
skipTranscript,
skipCacheWrite,
}: ForkedAgentParams)
| 515 | } |
| 516 | |
| 517 | export async function runForkedAgent({ |
| 518 | promptMessages, |
| 519 | cacheSafeParams, |
| 520 | canUseTool, |
| 521 | querySource, |
| 522 | forkLabel, |
| 523 | overrides, |
| 524 | maxOutputTokens, |
| 525 | maxTurns, |
| 526 | onMessage, |
| 527 | skipTranscript, |
| 528 | skipCacheWrite, |
| 529 | }: ForkedAgentParams): Promise<ForkedAgentResult> { |
| 530 | const startTime = Date.now() |
| 531 | const outputMessages: Message[] = [] |
| 532 | let totalUsage: NonNullableUsage = { ...EMPTY_USAGE } |
| 533 | |
| 534 | const { |
| 535 | systemPrompt, |
| 536 | userContext, |
| 537 | systemContext, |
| 538 | toolUseContext, |
| 539 | forkContextMessages, |
| 540 | } = cacheSafeParams |
| 541 | |
| 542 | // Create isolated context to prevent mutation of parent state |
| 543 | const isolatedToolUseContext = createSubagentContext( |
| 544 | toolUseContext, |
| 545 | overrides, |
| 546 | ) |
| 547 | |
| 548 | // Do NOT filterIncompleteToolCalls here — it drops the whole assistant on |
| 549 | // partial tool batches, orphaning the paired results (API 400). Dangling |
| 550 | // tool_uses are repaired downstream by ensureToolResultPairing in claude.ts, |
| 551 | // same as the main thread — identical post-repair prefix keeps the cache hit. |
| 552 | const initialMessages: Message[] = [...forkContextMessages, ...promptMessages] |
| 553 | |
| 554 | // Generate agent ID and record initial messages for transcript |
| 555 | // When skipTranscript is set, skip agent ID creation and all transcript I/O |
| 556 | const agentId = skipTranscript ? undefined : createAgentId(forkLabel) |
| 557 | let lastRecordedUuid: UUID | null = null |
| 558 | if (agentId) { |
| 559 | await recordSidechainTranscript(initialMessages, agentId).catch(err => |
| 560 | logForDebugging( |
| 561 | `Forked agent [${forkLabel}] failed to record initial transcript: ${err}`, |
| 562 | ), |
| 563 | ) |
| 564 | // Track the last recorded message UUID for parent chain continuity |
| 565 | lastRecordedUuid = |
| 566 | initialMessages.length > 0 |
| 567 | ? initialMessages[initialMessages.length - 1]!.uuid |
| 568 | : null |
| 569 | } |
| 570 | |
| 571 | // Run the query loop with isolated context (cache-safe params preserved) |
| 572 | try { |
| 573 | for await (const message of query({ |
| 574 | messages: initialMessages, |
no test coverage detected