MCPcopy
hub / github.com/codeaashu/claude-code / runForkedAgent

Function runForkedAgent

src/utils/forkedAgent.ts:489–626  ·  view source on GitHub ↗
({
  promptMessages,
  cacheSafeParams,
  canUseTool,
  querySource,
  forkLabel,
  overrides,
  maxOutputTokens,
  maxTurns,
  onMessage,
  skipTranscript,
  skipCacheWrite,
}: ForkedAgentParams)

Source from the content-addressed store, hash-verified

487 * ```
488 */
489export async function runForkedAgent({
490 promptMessages,
491 cacheSafeParams,
492 canUseTool,
493 querySource,
494 forkLabel,
495 overrides,
496 maxOutputTokens,
497 maxTurns,
498 onMessage,
499 skipTranscript,
500 skipCacheWrite,
501}: ForkedAgentParams): Promise<ForkedAgentResult> {
502 const startTime = Date.now()
503 const outputMessages: Message[] = []
504 let totalUsage: NonNullableUsage = { ...EMPTY_USAGE }
505
506 const {
507 systemPrompt,
508 userContext,
509 systemContext,
510 toolUseContext,
511 forkContextMessages,
512 } = cacheSafeParams
513
514 // Create isolated context to prevent mutation of parent state
515 const isolatedToolUseContext = createSubagentContext(
516 toolUseContext,
517 overrides,
518 )
519
520 // Do NOT filterIncompleteToolCalls here — it drops the whole assistant on
521 // partial tool batches, orphaning the paired results (API 400). Dangling
522 // tool_uses are repaired downstream by ensureToolResultPairing in claude.ts,
523 // same as the main thread — identical post-repair prefix keeps the cache hit.
524 const initialMessages: Message[] = [...forkContextMessages, ...promptMessages]
525
526 // Generate agent ID and record initial messages for transcript
527 // When skipTranscript is set, skip agent ID creation and all transcript I/O
528 const agentId = skipTranscript ? undefined : createAgentId(forkLabel)
529 let lastRecordedUuid: UUID | null = null
530 if (agentId) {
531 await recordSidechainTranscript(initialMessages, agentId).catch(err =>
532 logForDebugging(
533 `Forked agent [${forkLabel}] failed to record initial transcript: ${err}`,
534 ),
535 )
536 // Track the last recorded message UUID for parent chain continuity
537 lastRecordedUuid =
538 initialMessages.length > 0
539 ? initialMessages[initialMessages.length - 1]!.uuid
540 : null
541 }
542
543 // Run the query loop with isolated context (cache-safe params preserved)
544 try {
545 for await (const message of query({
546 messages: initialMessages,

Callers 9

runSideQuestionFunction · 0.85
streamCompactSummaryFunction · 0.85
initAutoDreamFunction · 0.85
runExtractionFunction · 0.85
sessionMemory.tsFile · 0.85
runSummaryFunction · 0.85
startSpeculationFunction · 0.85
generateSuggestionFunction · 0.85

Calls 10

createSubagentContextFunction · 0.85
createAgentIdFunction · 0.85
logForDebuggingFunction · 0.85
updateUsageFunction · 0.85
accumulateUsageFunction · 0.85
logForkAgentQueryEventFunction · 0.85
queryFunction · 0.50
pushMethod · 0.45
clearMethod · 0.45

Tested by

no test coverage detected