forked from soufianebouaddis/claude-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQueryEngine.ts
More file actions
1295 lines (1234 loc) · 45.5 KB
/
QueryEngine.ts
File metadata and controls
1295 lines (1234 loc) · 45.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { feature } from 'bun:bundle'
import type { ContentBlockParam } from '@anthropic-ai/sdk/resources/messages.mjs'
import { randomUUID } from 'crypto'
import last from 'lodash-es/last.js'
import {
getSessionId,
isSessionPersistenceDisabled,
} from 'src/bootstrap/state.js'
import type {
PermissionMode,
SDKCompactBoundaryMessage,
SDKMessage,
SDKPermissionDenial,
SDKStatus,
SDKUserMessageReplay,
} from 'src/entrypoints/agentSdkTypes.js'
import { accumulateUsage, updateUsage } from 'src/services/api/claude.js'
import type { NonNullableUsage } from 'src/services/api/logging.js'
import { EMPTY_USAGE } from 'src/services/api/logging.js'
import stripAnsi from 'strip-ansi'
import type { Command } from './commands.js'
import { getSlashCommandToolSkills } from './commands.js'
import {
LOCAL_COMMAND_STDERR_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from './constants/xml.js'
import {
getModelUsage,
getTotalAPIDuration,
getTotalCost,
} from './cost-tracker.js'
import type { CanUseToolFn } from './hooks/useCanUseTool.js'
import { loadMemoryPrompt } from './memdir/memdir.js'
import { hasAutoMemPathOverride } from './memdir/paths.js'
import { query } from './query.js'
import { categorizeRetryableAPIError } from './services/api/errors.js'
import type { MCPServerConnection } from './services/mcp/types.js'
import type { AppState } from './state/AppState.js'
import { type Tools, type ToolUseContext, toolMatchesName } from './Tool.js'
import type { AgentDefinition } from './tools/AgentTool/loadAgentsDir.js'
import { SYNTHETIC_OUTPUT_TOOL_NAME } from './tools/SyntheticOutputTool/SyntheticOutputTool.js'
import type { Message } from './types/message.js'
import type { OrphanedPermission } from './types/textInputTypes.js'
import { createAbortController } from './utils/abortController.js'
import type { AttributionState } from './utils/commitAttribution.js'
import { getGlobalConfig } from './utils/config.js'
import { getCwd } from './utils/cwd.js'
import { isBareMode, isEnvTruthy } from './utils/envUtils.js'
import { getFastModeState } from './utils/fastMode.js'
import {
type FileHistoryState,
fileHistoryEnabled,
fileHistoryMakeSnapshot,
} from './utils/fileHistory.js'
import {
cloneFileStateCache,
type FileStateCache,
} from './utils/fileStateCache.js'
import { headlessProfilerCheckpoint } from './utils/headlessProfiler.js'
import { registerStructuredOutputEnforcement } from './utils/hooks/hookHelpers.js'
import { getInMemoryErrors } from './utils/log.js'
import { countToolCalls, SYNTHETIC_MESSAGES } from './utils/messages.js'
import {
getMainLoopModel,
parseUserSpecifiedModel,
} from './utils/model/model.js'
import { loadAllPluginsCacheOnly } from './utils/plugins/pluginLoader.js'
import {
type ProcessUserInputContext,
processUserInput,
} from './utils/processUserInput/processUserInput.js'
import { fetchSystemPromptParts } from './utils/queryContext.js'
import { setCwd } from './utils/Shell.js'
import {
flushSessionStorage,
recordTranscript,
} from './utils/sessionStorage.js'
import { asSystemPrompt } from './utils/systemPromptType.js'
import { resolveThemeSetting } from './utils/systemTheme.js'
import {
shouldEnableThinkingByDefault,
type ThinkingConfig,
} from './utils/thinking.js'
// Lazy: MessageSelector.tsx pulls React/ink; only needed for message filtering at query time
/* eslint-disable @typescript-eslint/no-require-imports */
const messageSelector =
(): typeof import('src/components/MessageSelector.js') =>
require('src/components/MessageSelector.js')
import {
localCommandOutputToSDKAssistantMessage,
toSDKCompactMetadata,
} from './utils/messages/mappers.js'
import {
buildSystemInitMessage,
sdkCompatToolName,
} from './utils/messages/systemInit.js'
import {
getScratchpadDir,
isScratchpadEnabled,
} from './utils/permissions/filesystem.js'
/* eslint-enable @typescript-eslint/no-require-imports */
import {
handleOrphanedPermission,
isResultSuccessful,
normalizeMessage,
} from './utils/queryHelpers.js'
// Dead code elimination: conditional import for coordinator mode
/* eslint-disable @typescript-eslint/no-require-imports */
const getCoordinatorUserContext: (
mcpClients: ReadonlyArray<{ name: string }>,
scratchpadDir?: string,
) => { [k: string]: string } = feature('COORDINATOR_MODE')
? require('./coordinator/coordinatorMode.js').getCoordinatorUserContext
: () => ({})
/* eslint-enable @typescript-eslint/no-require-imports */
// Dead code elimination: conditional import for snip compaction
/* eslint-disable @typescript-eslint/no-require-imports */
const snipModule = feature('HISTORY_SNIP')
? (require('./services/compact/snipCompact.js') as typeof import('./services/compact/snipCompact.js'))
: null
const snipProjection = feature('HISTORY_SNIP')
? (require('./services/compact/snipProjection.js') as typeof import('./services/compact/snipProjection.js'))
: null
/* eslint-enable @typescript-eslint/no-require-imports */
export type QueryEngineConfig = {
cwd: string
tools: Tools
commands: Command[]
mcpClients: MCPServerConnection[]
agents: AgentDefinition[]
canUseTool: CanUseToolFn
getAppState: () => AppState
setAppState: (f: (prev: AppState) => AppState) => void
initialMessages?: Message[]
readFileCache: FileStateCache
customSystemPrompt?: string
appendSystemPrompt?: string
userSpecifiedModel?: string
fallbackModel?: string
thinkingConfig?: ThinkingConfig
maxTurns?: number
maxBudgetUsd?: number
taskBudget?: { total: number }
jsonSchema?: Record<string, unknown>
verbose?: boolean
replayUserMessages?: boolean
/** Handler for URL elicitations triggered by MCP tool -32042 errors. */
handleElicitation?: ToolUseContext['handleElicitation']
includePartialMessages?: boolean
setSDKStatus?: (status: SDKStatus) => void
abortController?: AbortController
orphanedPermission?: OrphanedPermission
/**
* Snip-boundary handler: receives each yielded system message plus the
* current mutableMessages store. Returns undefined if the message is not a
* snip boundary; otherwise returns the replayed snip result. Injected by
* ask() when HISTORY_SNIP is enabled so feature-gated strings stay inside
* the gated module (keeps QueryEngine free of excluded strings and testable
* despite feature() returning false under bun test). SDK-only: the REPL
* keeps full history for UI scrollback and projects on demand via
* projectSnippedView; QueryEngine truncates here to bound memory in long
* headless sessions (no UI to preserve).
*/
snipReplay?: (
yieldedSystemMsg: Message,
store: Message[],
) => { messages: Message[]; executed: boolean } | undefined
}
/**
* QueryEngine owns the query lifecycle and session state for a conversation.
* It extracts the core logic from ask() into a standalone class that can be
* used by both the headless/SDK path and (in a future phase) the REPL.
*
* One QueryEngine per conversation. Each submitMessage() call starts a new
* turn within the same conversation. State (messages, file cache, usage, etc.)
* persists across turns.
*/
export class QueryEngine {
private config: QueryEngineConfig
private mutableMessages: Message[]
private abortController: AbortController
private permissionDenials: SDKPermissionDenial[]
private totalUsage: NonNullableUsage
private hasHandledOrphanedPermission = false
private readFileState: FileStateCache
// Turn-scoped skill discovery tracking (feeds was_discovered on
// tengu_skill_tool_invocation). Must persist across the two
// processUserInputContext rebuilds inside submitMessage, but is cleared
// at the start of each submitMessage to avoid unbounded growth across
// many turns in SDK mode.
private discoveredSkillNames = new Set<string>()
private loadedNestedMemoryPaths = new Set<string>()
constructor(config: QueryEngineConfig) {
this.config = config
this.mutableMessages = config.initialMessages ?? []
this.abortController = config.abortController ?? createAbortController()
this.permissionDenials = []
this.readFileState = config.readFileCache
this.totalUsage = EMPTY_USAGE
}
async *submitMessage(
prompt: string | ContentBlockParam[],
options?: { uuid?: string; isMeta?: boolean },
): AsyncGenerator<SDKMessage, void, unknown> {
const {
cwd,
commands,
tools,
mcpClients,
verbose = false,
thinkingConfig,
maxTurns,
maxBudgetUsd,
taskBudget,
canUseTool,
customSystemPrompt,
appendSystemPrompt,
userSpecifiedModel,
fallbackModel,
jsonSchema,
getAppState,
setAppState,
replayUserMessages = false,
includePartialMessages = false,
agents = [],
setSDKStatus,
orphanedPermission,
} = this.config
this.discoveredSkillNames.clear()
setCwd(cwd)
const persistSession = !isSessionPersistenceDisabled()
const startTime = Date.now()
// Wrap canUseTool to track permission denials
const wrappedCanUseTool: CanUseToolFn = async (
tool,
input,
toolUseContext,
assistantMessage,
toolUseID,
forceDecision,
) => {
const result = await canUseTool(
tool,
input,
toolUseContext,
assistantMessage,
toolUseID,
forceDecision,
)
// Track denials for SDK reporting
if (result.behavior !== 'allow') {
this.permissionDenials.push({
tool_name: sdkCompatToolName(tool.name),
tool_use_id: toolUseID,
tool_input: input,
})
}
return result
}
const initialAppState = getAppState()
const initialMainLoopModel = userSpecifiedModel
? parseUserSpecifiedModel(userSpecifiedModel)
: getMainLoopModel()
const initialThinkingConfig: ThinkingConfig = thinkingConfig
? thinkingConfig
: shouldEnableThinkingByDefault() !== false
? { type: 'adaptive' }
: { type: 'disabled' }
headlessProfilerCheckpoint('before_getSystemPrompt')
// Narrow once so TS tracks the type through the conditionals below.
const customPrompt =
typeof customSystemPrompt === 'string' ? customSystemPrompt : undefined
const {
defaultSystemPrompt,
userContext: baseUserContext,
systemContext,
} = await fetchSystemPromptParts({
tools,
mainLoopModel: initialMainLoopModel,
additionalWorkingDirectories: Array.from(
initialAppState.toolPermissionContext.additionalWorkingDirectories.keys(),
),
mcpClients,
customSystemPrompt: customPrompt,
})
headlessProfilerCheckpoint('after_getSystemPrompt')
const userContext = {
...baseUserContext,
...getCoordinatorUserContext(
mcpClients,
isScratchpadEnabled() ? getScratchpadDir() : undefined,
),
}
// When an SDK caller provides a custom system prompt AND has set
// CLAUDE_COWORK_MEMORY_PATH_OVERRIDE, inject the memory-mechanics prompt.
// The env var is an explicit opt-in signal — the caller has wired up
// a memory directory and needs Claude to know how to use it (which
// Write/Edit tools to call, MEMORY.md filename, loading semantics).
// The caller can layer their own policy text via appendSystemPrompt.
const memoryMechanicsPrompt =
customPrompt !== undefined && hasAutoMemPathOverride()
? await loadMemoryPrompt()
: null
const systemPrompt = asSystemPrompt([
...(customPrompt !== undefined ? [customPrompt] : defaultSystemPrompt),
...(memoryMechanicsPrompt ? [memoryMechanicsPrompt] : []),
...(appendSystemPrompt ? [appendSystemPrompt] : []),
])
// Register function hook for structured output enforcement
const hasStructuredOutputTool = tools.some(t =>
toolMatchesName(t, SYNTHETIC_OUTPUT_TOOL_NAME),
)
if (jsonSchema && hasStructuredOutputTool) {
registerStructuredOutputEnforcement(setAppState, getSessionId())
}
let processUserInputContext: ProcessUserInputContext = {
messages: this.mutableMessages,
// Slash commands that mutate the message array (e.g. /force-snip)
// call setMessages(fn). In interactive mode this writes back to
// AppState; in print mode we write back to mutableMessages so the
// rest of the query loop (push at :389, snapshot at :392) sees
// the result. The second processUserInputContext below (after
// slash-command processing) keeps the no-op — nothing else calls
// setMessages past that point.
setMessages: fn => {
this.mutableMessages = fn(this.mutableMessages)
},
onChangeAPIKey: () => {},
handleElicitation: this.config.handleElicitation,
options: {
commands,
debug: false, // we use stdout, so don't want to clobber it
tools,
verbose,
mainLoopModel: initialMainLoopModel,
thinkingConfig: initialThinkingConfig,
mcpClients,
mcpResources: {},
ideInstallationStatus: null,
isNonInteractiveSession: true,
customSystemPrompt,
appendSystemPrompt,
agentDefinitions: { activeAgents: agents, allAgents: [] },
theme: resolveThemeSetting(getGlobalConfig().theme),
maxBudgetUsd,
},
getAppState,
setAppState,
abortController: this.abortController,
readFileState: this.readFileState,
nestedMemoryAttachmentTriggers: new Set<string>(),
loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
dynamicSkillDirTriggers: new Set<string>(),
discoveredSkillNames: this.discoveredSkillNames,
setInProgressToolUseIDs: () => {},
setResponseLength: () => {},
updateFileHistoryState: (
updater: (prev: FileHistoryState) => FileHistoryState,
) => {
setAppState(prev => {
const updated = updater(prev.fileHistory)
if (updated === prev.fileHistory) return prev
return { ...prev, fileHistory: updated }
})
},
updateAttributionState: (
updater: (prev: AttributionState) => AttributionState,
) => {
setAppState(prev => {
const updated = updater(prev.attribution)
if (updated === prev.attribution) return prev
return { ...prev, attribution: updated }
})
},
setSDKStatus,
}
// Handle orphaned permission (only once per engine lifetime)
if (orphanedPermission && !this.hasHandledOrphanedPermission) {
this.hasHandledOrphanedPermission = true
for await (const message of handleOrphanedPermission(
orphanedPermission,
tools,
this.mutableMessages,
processUserInputContext,
)) {
yield message
}
}
const {
messages: messagesFromUserInput,
shouldQuery,
allowedTools,
model: modelFromUserInput,
resultText,
} = await processUserInput({
input: prompt,
mode: 'prompt',
setToolJSX: () => {},
context: {
...processUserInputContext,
messages: this.mutableMessages,
},
messages: this.mutableMessages,
uuid: options?.uuid,
isMeta: options?.isMeta,
querySource: 'sdk',
})
// Push new messages, including user input and any attachments
this.mutableMessages.push(...messagesFromUserInput)
// Update params to reflect updates from processing /slash commands
const messages = [...this.mutableMessages]
// Persist the user's message(s) to transcript BEFORE entering the query
// loop. The for-await below only calls recordTranscript when ask() yields
// an assistant/user/compact_boundary message — which doesn't happen until
// the API responds. If the process is killed before that (e.g. user clicks
// Stop in cowork seconds after send), the transcript is left with only
// queue-operation entries; getLastSessionLog filters those out, returns
// null, and --resume fails with "No conversation found". Writing now makes
// the transcript resumable from the point the user message was accepted,
// even if no API response ever arrives.
//
// --bare / SIMPLE: fire-and-forget. Scripted calls don't --resume after
// kill-mid-request. The await is ~4ms on SSD, ~30ms under disk contention
// — the single largest controllable critical-path cost after module eval.
// Transcript is still written (for post-hoc debugging); just not blocking.
if (persistSession && messagesFromUserInput.length > 0) {
const transcriptPromise = recordTranscript(messages)
if (isBareMode()) {
void transcriptPromise
} else {
await transcriptPromise
if (
isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) ||
isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)
) {
await flushSessionStorage()
}
}
}
// Filter messages that should be acknowledged after transcript
const replayableMessages = messagesFromUserInput.filter(
msg =>
(msg.type === 'user' &&
!msg.isMeta && // Skip synthetic caveat messages
!msg.toolUseResult && // Skip tool results (they'll be acked from query)
messageSelector().selectableUserMessagesFilter(msg)) || // Skip non-user-authored messages (task notifications, etc.)
(msg.type === 'system' && msg.subtype === 'compact_boundary'), // Always ack compact boundaries
)
const messagesToAck = replayUserMessages ? replayableMessages : []
// Update the ToolPermissionContext based on user input processing (as necessary)
setAppState(prev => ({
...prev,
toolPermissionContext: {
...prev.toolPermissionContext,
alwaysAllowRules: {
...prev.toolPermissionContext.alwaysAllowRules,
command: allowedTools,
},
},
}))
const mainLoopModel = modelFromUserInput ?? initialMainLoopModel
// Recreate after processing the prompt to pick up updated messages and
// model (from slash commands).
processUserInputContext = {
messages,
setMessages: () => {},
onChangeAPIKey: () => {},
handleElicitation: this.config.handleElicitation,
options: {
commands,
debug: false,
tools,
verbose,
mainLoopModel,
thinkingConfig: initialThinkingConfig,
mcpClients,
mcpResources: {},
ideInstallationStatus: null,
isNonInteractiveSession: true,
customSystemPrompt,
appendSystemPrompt,
theme: resolveThemeSetting(getGlobalConfig().theme),
agentDefinitions: { activeAgents: agents, allAgents: [] },
maxBudgetUsd,
},
getAppState,
setAppState,
abortController: this.abortController,
readFileState: this.readFileState,
nestedMemoryAttachmentTriggers: new Set<string>(),
loadedNestedMemoryPaths: this.loadedNestedMemoryPaths,
dynamicSkillDirTriggers: new Set<string>(),
discoveredSkillNames: this.discoveredSkillNames,
setInProgressToolUseIDs: () => {},
setResponseLength: () => {},
updateFileHistoryState: processUserInputContext.updateFileHistoryState,
updateAttributionState: processUserInputContext.updateAttributionState,
setSDKStatus,
}
headlessProfilerCheckpoint('before_skills_plugins')
// Cache-only: headless/SDK/CCR startup must not block on network for
// ref-tracked plugins. CCR populates the cache via CLAUDE_CODE_SYNC_PLUGIN_INSTALL
// (headlessPluginInstall) or CLAUDE_CODE_PLUGIN_SEED_DIR before this runs;
// SDK callers that need fresh source can call /reload-plugins.
const [skills, { enabled: enabledPlugins }] = await Promise.all([
getSlashCommandToolSkills(getCwd()),
loadAllPluginsCacheOnly(),
])
headlessProfilerCheckpoint('after_skills_plugins')
yield buildSystemInitMessage({
tools,
mcpClients,
model: mainLoopModel,
permissionMode: initialAppState.toolPermissionContext
.mode as PermissionMode, // TODO: avoid the cast
commands,
agents,
skills,
plugins: enabledPlugins,
fastMode: initialAppState.fastMode,
})
// Record when system message is yielded for headless latency tracking
headlessProfilerCheckpoint('system_message_yielded')
if (!shouldQuery) {
// Return the results of local slash commands.
// Use messagesFromUserInput (not replayableMessages) for command output
// because selectableUserMessagesFilter excludes local-command-stdout tags.
for (const msg of messagesFromUserInput) {
if (
msg.type === 'user' &&
typeof msg.message.content === 'string' &&
(msg.message.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) ||
msg.message.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`) ||
msg.isCompactSummary)
) {
yield {
type: 'user',
message: {
...msg.message,
content: stripAnsi(msg.message.content),
},
session_id: getSessionId(),
parent_tool_use_id: null,
uuid: msg.uuid,
timestamp: msg.timestamp,
isReplay: !msg.isCompactSummary,
isSynthetic: msg.isMeta || msg.isVisibleInTranscriptOnly,
} as SDKUserMessageReplay
}
// Local command output — yield as a synthetic assistant message so
// RC renders it as assistant-style text rather than a user bubble.
// Emitted as assistant (not the dedicated SDKLocalCommandOutputMessage
// system subtype) so mobile clients + session-ingress can parse it.
if (
msg.type === 'system' &&
msg.subtype === 'local_command' &&
typeof msg.content === 'string' &&
(msg.content.includes(`<${LOCAL_COMMAND_STDOUT_TAG}>`) ||
msg.content.includes(`<${LOCAL_COMMAND_STDERR_TAG}>`))
) {
yield localCommandOutputToSDKAssistantMessage(msg.content, msg.uuid)
}
if (msg.type === 'system' && msg.subtype === 'compact_boundary') {
yield {
type: 'system',
subtype: 'compact_boundary' as const,
session_id: getSessionId(),
uuid: msg.uuid,
compact_metadata: toSDKCompactMetadata(msg.compactMetadata),
} as SDKCompactBoundaryMessage
}
}
if (persistSession) {
await recordTranscript(messages)
if (
isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) ||
isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)
) {
await flushSessionStorage()
}
}
yield {
type: 'result',
subtype: 'success',
is_error: false,
duration_ms: Date.now() - startTime,
duration_api_ms: getTotalAPIDuration(),
num_turns: messages.length - 1,
result: resultText ?? '',
stop_reason: null,
session_id: getSessionId(),
total_cost_usd: getTotalCost(),
usage: this.totalUsage,
modelUsage: getModelUsage(),
permission_denials: this.permissionDenials,
fast_mode_state: getFastModeState(
mainLoopModel,
initialAppState.fastMode,
),
uuid: randomUUID(),
}
return
}
if (fileHistoryEnabled() && persistSession) {
messagesFromUserInput
.filter(messageSelector().selectableUserMessagesFilter)
.forEach(message => {
void fileHistoryMakeSnapshot(
(updater: (prev: FileHistoryState) => FileHistoryState) => {
setAppState(prev => ({
...prev,
fileHistory: updater(prev.fileHistory),
}))
},
message.uuid,
)
})
}
// Track current message usage (reset on each message_start)
let currentMessageUsage: NonNullableUsage = EMPTY_USAGE
let turnCount = 1
let hasAcknowledgedInitialMessages = false
// Track structured output from StructuredOutput tool calls
let structuredOutputFromTool: unknown
// Track the last stop_reason from assistant messages
let lastStopReason: string | null = null
// Reference-based watermark so error_during_execution's errors[] is
// turn-scoped. A length-based index breaks when the 100-entry ring buffer
// shift()s during the turn — the index slides. If this entry is rotated
// out, lastIndexOf returns -1 and we include everything (safe fallback).
const errorLogWatermark = getInMemoryErrors().at(-1)
// Snapshot count before this query for delta-based retry limiting
const initialStructuredOutputCalls = jsonSchema
? countToolCalls(this.mutableMessages, SYNTHETIC_OUTPUT_TOOL_NAME)
: 0
for await (const message of query({
messages,
systemPrompt,
userContext,
systemContext,
canUseTool: wrappedCanUseTool,
toolUseContext: processUserInputContext,
fallbackModel,
querySource: 'sdk',
maxTurns,
taskBudget,
})) {
// Record assistant, user, and compact boundary messages
if (
message.type === 'assistant' ||
message.type === 'user' ||
(message.type === 'system' && message.subtype === 'compact_boundary')
) {
// Before writing a compact boundary, flush any in-memory-only
// messages up through the preservedSegment tail. Attachments and
// progress are now recorded inline (their switch cases below), but
// this flush still matters for the preservedSegment tail walk.
// If the SDK subprocess restarts before then (claude-desktop kills
// between turns), tailUuid points to a never-written message →
// applyPreservedSegmentRelinks fails its tail→head walk → returns
// without pruning → resume loads full pre-compact history.
if (
persistSession &&
message.type === 'system' &&
message.subtype === 'compact_boundary'
) {
const tailUuid = message.compactMetadata?.preservedSegment?.tailUuid
if (tailUuid) {
const tailIdx = this.mutableMessages.findLastIndex(
m => m.uuid === tailUuid,
)
if (tailIdx !== -1) {
await recordTranscript(this.mutableMessages.slice(0, tailIdx + 1))
}
}
}
messages.push(message)
if (persistSession) {
// Fire-and-forget for assistant messages. claude.ts yields one
// assistant message per content block, then mutates the last
// one's message.usage/stop_reason on message_delta — relying on
// the write queue's 100ms lazy jsonStringify. Awaiting here
// blocks ask()'s generator, so message_delta can't run until
// every block is consumed; the drain timer (started at block 1)
// elapses first. Interactive CC doesn't hit this because
// useLogMessages.ts fire-and-forgets. enqueueWrite is
// order-preserving so fire-and-forget here is safe.
if (message.type === 'assistant') {
void recordTranscript(messages)
} else {
await recordTranscript(messages)
}
}
// Acknowledge initial user messages after first transcript recording
if (!hasAcknowledgedInitialMessages && messagesToAck.length > 0) {
hasAcknowledgedInitialMessages = true
for (const msgToAck of messagesToAck) {
if (msgToAck.type === 'user') {
yield {
type: 'user',
message: msgToAck.message,
session_id: getSessionId(),
parent_tool_use_id: null,
uuid: msgToAck.uuid,
timestamp: msgToAck.timestamp,
isReplay: true,
} as SDKUserMessageReplay
}
}
}
}
if (message.type === 'user') {
turnCount++
}
switch (message.type) {
case 'tombstone':
// Tombstone messages are control signals for removing messages, skip them
break
case 'assistant':
// Capture stop_reason if already set (synthetic messages). For
// streamed responses, this is null at content_block_stop time;
// the real value arrives via message_delta (handled below).
if (message.message.stop_reason != null) {
lastStopReason = message.message.stop_reason
}
this.mutableMessages.push(message)
yield* normalizeMessage(message)
break
case 'progress':
this.mutableMessages.push(message)
// Record inline so the dedup loop in the next ask() call sees it
// as already-recorded. Without this, deferred progress interleaves
// with already-recorded tool_results in mutableMessages, and the
// dedup walk freezes startingParentUuid at the wrong message —
// forking the chain and orphaning the conversation on resume.
if (persistSession) {
messages.push(message)
void recordTranscript(messages)
}
yield* normalizeMessage(message)
break
case 'user':
this.mutableMessages.push(message)
yield* normalizeMessage(message)
break
case 'stream_event':
if (message.event.type === 'message_start') {
// Reset current message usage for new message
currentMessageUsage = EMPTY_USAGE
currentMessageUsage = updateUsage(
currentMessageUsage,
message.event.message.usage,
)
}
if (message.event.type === 'message_delta') {
currentMessageUsage = updateUsage(
currentMessageUsage,
message.event.usage,
)
// Capture stop_reason from message_delta. The assistant message
// is yielded at content_block_stop with stop_reason=null; the
// real value only arrives here (see claude.ts message_delta
// handler). Without this, result.stop_reason is always null.
if (message.event.delta.stop_reason != null) {
lastStopReason = message.event.delta.stop_reason
}
}
if (message.event.type === 'message_stop') {
// Accumulate current message usage into total
this.totalUsage = accumulateUsage(
this.totalUsage,
currentMessageUsage,
)
}
if (includePartialMessages) {
yield {
type: 'stream_event' as const,
event: message.event,
session_id: getSessionId(),
parent_tool_use_id: null,
uuid: randomUUID(),
}
}
break
case 'attachment':
this.mutableMessages.push(message)
// Record inline (same reason as progress above).
if (persistSession) {
messages.push(message)
void recordTranscript(messages)
}
// Extract structured output from StructuredOutput tool calls
if (message.attachment.type === 'structured_output') {
structuredOutputFromTool = message.attachment.data
}
// Handle max turns reached signal from query.ts
else if (message.attachment.type === 'max_turns_reached') {
if (persistSession) {
if (
isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) ||
isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)
) {
await flushSessionStorage()
}
}
yield {
type: 'result',
subtype: 'error_max_turns',
duration_ms: Date.now() - startTime,
duration_api_ms: getTotalAPIDuration(),
is_error: true,
num_turns: message.attachment.turnCount,
stop_reason: lastStopReason,
session_id: getSessionId(),
total_cost_usd: getTotalCost(),
usage: this.totalUsage,
modelUsage: getModelUsage(),
permission_denials: this.permissionDenials,
fast_mode_state: getFastModeState(
mainLoopModel,
initialAppState.fastMode,
),
uuid: randomUUID(),
errors: [
`Reached maximum number of turns (${message.attachment.maxTurns})`,
],
}
return
}
// Yield queued_command attachments as SDK user message replays
else if (
replayUserMessages &&
message.attachment.type === 'queued_command'
) {
yield {
type: 'user',
message: {
role: 'user' as const,
content: message.attachment.prompt,
},
session_id: getSessionId(),
parent_tool_use_id: null,
uuid: message.attachment.source_uuid || message.uuid,
timestamp: message.timestamp,
isReplay: true,
} as SDKUserMessageReplay
}
break
case 'stream_request_start':
// Don't yield stream request start messages
break
case 'system': {
// Snip boundary: replay on our store to remove zombie messages and
// stale markers. The yielded boundary is a signal, not data to push —
// the replay produces its own equivalent boundary. Without this,
// markers persist and re-trigger on every turn, and mutableMessages
// never shrinks (memory leak in long SDK sessions). The subtype
// check lives inside the injected callback so feature-gated strings
// stay out of this file (excluded-strings check).
const snipResult = this.config.snipReplay?.(
message,
this.mutableMessages,
)
if (snipResult !== undefined) {
if (snipResult.executed) {
this.mutableMessages.length = 0
this.mutableMessages.push(...snipResult.messages)
}
break
}
this.mutableMessages.push(message)
// Yield compact boundary messages to SDK
if (
message.subtype === 'compact_boundary' &&
message.compactMetadata
) {
// Release pre-compaction messages for GC. The boundary was just
// pushed so it's the last element. query.ts already uses
// getMessagesAfterCompactBoundary() internally, so only
// post-boundary messages are needed going forward.
const mutableBoundaryIdx = this.mutableMessages.length - 1
if (mutableBoundaryIdx > 0) {
this.mutableMessages.splice(0, mutableBoundaryIdx)
}
const localBoundaryIdx = messages.length - 1
if (localBoundaryIdx > 0) {
messages.splice(0, localBoundaryIdx)
}
yield {
type: 'system',
subtype: 'compact_boundary' as const,
session_id: getSessionId(),
uuid: message.uuid,
compact_metadata: toSDKCompactMetadata(message.compactMetadata),
}
}
if (message.subtype === 'api_error') {
yield {
type: 'system',
subtype: 'api_retry' as const,
attempt: message.retryAttempt,
max_retries: message.maxRetries,
retry_delay_ms: message.retryInMs,
error_status: message.error.status ?? null,
error: categorizeRetryableAPIError(message.error),
session_id: getSessionId(),
uuid: message.uuid,
}
}
// Don't yield other system messages in headless mode
break
}
case 'tool_use_summary':
// Yield tool use summary messages to SDK
yield {
type: 'tool_use_summary' as const,
summary: message.summary,
preceding_tool_use_ids: message.precedingToolUseIds,
session_id: getSessionId(),
uuid: message.uuid,
}
break
}
// Check if USD budget has been exceeded
if (maxBudgetUsd !== undefined && getTotalCost() >= maxBudgetUsd) {
if (persistSession) {
if (
isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) ||
isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)
) {
await flushSessionStorage()
}
}
yield {
type: 'result',
subtype: 'error_max_budget_usd',
duration_ms: Date.now() - startTime,
duration_api_ms: getTotalAPIDuration(),
is_error: true,
num_turns: turnCount,
stop_reason: lastStopReason,
session_id: getSessionId(),
total_cost_usd: getTotalCost(),
usage: this.totalUsage,
modelUsage: getModelUsage(),
permission_denials: this.permissionDenials,
fast_mode_state: getFastModeState(
mainLoopModel,
initialAppState.fastMode,
),
uuid: randomUUID(),
errors: [`Reached maximum budget ($${maxBudgetUsd})`],
}