forked from liuup/claude-code-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessages.ts
More file actions
5512 lines (5070 loc) · 189 KB
/
Copy pathmessages.ts
File metadata and controls
5512 lines (5070 loc) · 189 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 { BetaUsage as Usage } from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import type {
ContentBlock,
ContentBlockParam,
RedactedThinkingBlock,
RedactedThinkingBlockParam,
TextBlockParam,
ThinkingBlock,
ThinkingBlockParam,
ToolResultBlockParam,
ToolUseBlock,
ToolUseBlockParam,
} from '@anthropic-ai/sdk/resources/index.mjs'
import { randomUUID, type UUID } from 'crypto'
import isObject from 'lodash-es/isObject.js'
import last from 'lodash-es/last.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { sanitizeToolNameForAnalytics } from 'src/services/analytics/metadata.js'
import type { AgentId } from 'src/types/ids.js'
import { companionIntroText } from '../buddy/prompt.js'
import { NO_CONTENT_MESSAGE } from '../constants/messages.js'
import { OUTPUT_STYLE_CONFIG } from '../constants/outputStyles.js'
import { isAutoMemoryEnabled } from '../memdir/paths.js'
import {
checkStatsigFeatureGate_CACHED_MAY_BE_STALE,
getFeatureValue_CACHED_MAY_BE_STALE,
} from '../services/analytics/growthbook.js'
import {
getImageTooLargeErrorMessage,
getPdfInvalidErrorMessage,
getPdfPasswordProtectedErrorMessage,
getPdfTooLargeErrorMessage,
getRequestTooLargeErrorMessage,
} from '../services/api/errors.js'
import type { AnyObject, Progress } from '../Tool.js'
import { isConnectorTextBlock } from '../types/connectorText.js'
import type {
AssistantMessage,
AttachmentMessage,
Message,
MessageOrigin,
NormalizedAssistantMessage,
NormalizedMessage,
NormalizedUserMessage,
PartialCompactDirection,
ProgressMessage,
RequestStartEvent,
StopHookInfo,
StreamEvent,
SystemAgentsKilledMessage,
SystemAPIErrorMessage,
SystemApiMetricsMessage,
SystemAwaySummaryMessage,
SystemBridgeStatusMessage,
SystemCompactBoundaryMessage,
SystemInformationalMessage,
SystemLocalCommandMessage,
SystemMemorySavedMessage,
SystemMessage,
SystemMessageLevel,
SystemMicrocompactBoundaryMessage,
SystemPermissionRetryMessage,
SystemScheduledTaskFireMessage,
SystemStopHookSummaryMessage,
SystemTurnDurationMessage,
TombstoneMessage,
ToolUseSummaryMessage,
UserMessage,
} from '../types/message.js'
import { isAdvisorBlock } from './advisor.js'
import { isAgentSwarmsEnabled } from './agentSwarmsEnabled.js'
import { count } from './array.js'
import {
type Attachment,
type HookAttachment,
type HookPermissionDecisionAttachment,
memoryHeader,
} from './attachments.js'
import { quote } from './bash/shellQuote.js'
import { formatNumber, formatTokens } from './format.js'
import { getPewterLedgerVariant } from './planModeV2.js'
import { jsonStringify } from './slowOperations.js'
// Hook attachments that have a hookName field (excludes HookPermissionDecisionAttachment)
type HookAttachmentWithName = Exclude<
HookAttachment,
HookPermissionDecisionAttachment
>
import type { APIError } from '@anthropic-ai/sdk'
import type {
BetaContentBlock,
BetaMessage,
BetaRedactedThinkingBlock,
BetaThinkingBlock,
BetaToolUseBlock,
} from '@anthropic-ai/sdk/resources/beta/messages/messages.mjs'
import type {
HookEvent,
SDKAssistantMessageError,
} from 'src/entrypoints/agentSdkTypes.js'
import { EXPLORE_AGENT } from 'src/tools/AgentTool/built-in/exploreAgent.js'
import { PLAN_AGENT } from 'src/tools/AgentTool/built-in/planAgent.js'
import { areExplorePlanAgentsEnabled } from 'src/tools/AgentTool/builtInAgents.js'
import { AGENT_TOOL_NAME } from 'src/tools/AgentTool/constants.js'
import { ASK_USER_QUESTION_TOOL_NAME } from 'src/tools/AskUserQuestionTool/prompt.js'
import { BashTool } from 'src/tools/BashTool/BashTool.js'
import { ExitPlanModeV2Tool } from 'src/tools/ExitPlanModeTool/ExitPlanModeV2Tool.js'
import { FileEditTool } from 'src/tools/FileEditTool/FileEditTool.js'
import {
FILE_READ_TOOL_NAME,
MAX_LINES_TO_READ,
} from 'src/tools/FileReadTool/prompt.js'
import { FileWriteTool } from 'src/tools/FileWriteTool/FileWriteTool.js'
import { GLOB_TOOL_NAME } from 'src/tools/GlobTool/prompt.js'
import { GREP_TOOL_NAME } from 'src/tools/GrepTool/prompt.js'
import type { DeepImmutable } from 'src/types/utils.js'
import { getStrictToolResultPairing } from '../bootstrap/state.js'
import type { SpinnerMode } from '../components/Spinner.js'
import {
COMMAND_ARGS_TAG,
COMMAND_MESSAGE_TAG,
COMMAND_NAME_TAG,
LOCAL_COMMAND_CAVEAT_TAG,
LOCAL_COMMAND_STDOUT_TAG,
} from '../constants/xml.js'
import { DiagnosticTrackingService } from '../services/diagnosticTracking.js'
import {
findToolByName,
type Tool,
type Tools,
toolMatchesName,
} from '../Tool.js'
import {
FileReadTool,
type Output as FileReadToolOutput,
} from '../tools/FileReadTool/FileReadTool.js'
import { SEND_MESSAGE_TOOL_NAME } from '../tools/SendMessageTool/constants.js'
import { TASK_CREATE_TOOL_NAME } from '../tools/TaskCreateTool/constants.js'
import { TASK_OUTPUT_TOOL_NAME } from '../tools/TaskOutputTool/constants.js'
import { TASK_UPDATE_TOOL_NAME } from '../tools/TaskUpdateTool/constants.js'
import type { PermissionMode } from '../types/permissions.js'
import { normalizeToolInput, normalizeToolInputForAPI } from './api.js'
import { getCurrentProjectConfig } from './config.js'
import { logAntError, logForDebugging } from './debug.js'
import { stripIdeContextTags } from './displayTags.js'
import { hasEmbeddedSearchTools } from './embeddedTools.js'
import { formatFileSize } from './format.js'
import { validateImagesForAPI } from './imageValidation.js'
import { safeParseJSON } from './json.js'
import { logError, logMCPDebug } from './log.js'
import { normalizeLegacyToolName } from './permissions/permissionRuleParser.js'
import {
getPlanModeV2AgentCount,
getPlanModeV2ExploreAgentCount,
isPlanModeInterviewPhaseEnabled,
} from './planModeV2.js'
import { escapeRegExp } from './stringUtils.js'
import { isTodoV2Enabled } from './tasks.js'
// Lazy import to avoid circular dependency (teammateMailbox -> teammate -> ... -> messages)
function getTeammateMailbox(): typeof import('./teammateMailbox.js') {
// eslint-disable-next-line @typescript-eslint/no-require-imports
return require('./teammateMailbox.js')
}
import {
isToolReferenceBlock,
isToolSearchEnabledOptimistic,
} from './toolSearch.js'
const MEMORY_CORRECTION_HINT =
"\n\nNote: The user's next message may contain a correction or preference. Pay close attention — if they explain what went wrong or how they'd prefer you to work, consider saving that to memory for future sessions."
const TOOL_REFERENCE_TURN_BOUNDARY = 'Tool loaded.'
/**
* Appends a memory correction hint to a rejection/cancellation message
* when auto-memory is enabled and the GrowthBook flag is on.
*/
export function withMemoryCorrectionHint(message: string): string {
if (
isAutoMemoryEnabled() &&
getFeatureValue_CACHED_MAY_BE_STALE('tengu_amber_prism', false)
) {
return message + MEMORY_CORRECTION_HINT
}
return message
}
/**
* Derive a short stable message ID (6-char base36 string) from a UUID.
* Used for snip tool referencing — injected into API-bound messages as [id:...] tags.
* Deterministic: same UUID always produces the same short ID.
*/
export function deriveShortMessageId(uuid: string): string {
// Take first 10 hex chars from the UUID (skipping dashes)
const hex = uuid.replace(/-/g, '').slice(0, 10)
// Convert to base36 for shorter representation, take 6 chars
return parseInt(hex, 16).toString(36).slice(0, 6)
}
export const INTERRUPT_MESSAGE = '[Request interrupted by user]'
export const INTERRUPT_MESSAGE_FOR_TOOL_USE =
'[Request interrupted by user for tool use]'
export const CANCEL_MESSAGE =
"The user doesn't want to take this action right now. STOP what you are doing and wait for the user to tell you how to proceed."
export const REJECT_MESSAGE =
"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). STOP what you are doing and wait for the user to tell you how to proceed."
export const REJECT_MESSAGE_WITH_REASON_PREFIX =
"The user doesn't want to proceed with this tool use. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). To tell you how to proceed, the user said:\n"
export const SUBAGENT_REJECT_MESSAGE =
'Permission for this tool use was denied. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). Try a different approach or report the limitation to complete your task.'
export const SUBAGENT_REJECT_MESSAGE_WITH_REASON_PREFIX =
'Permission for this tool use was denied. The tool use was rejected (eg. if it was a file edit, the new_string was NOT written to the file). The user said:\n'
export const PLAN_REJECTION_PREFIX =
'The agent proposed a plan that was rejected by the user. The user chose to stay in plan mode rather than proceed with implementation.\n\nRejected plan:\n'
/**
* Shared guidance for permission denials, instructing the model on appropriate workarounds.
*/
export const DENIAL_WORKAROUND_GUIDANCE =
`IMPORTANT: You *may* attempt to accomplish this action using other tools that might naturally be used to accomplish this goal, ` +
`e.g. using head instead of cat. But you *should not* attempt to work around this denial in malicious ways, ` +
`e.g. do not use your ability to run tests to execute non-test actions. ` +
`You should only try to work around this restriction in reasonable ways that do not attempt to bypass the intent behind this denial. ` +
`If you believe this capability is essential to complete the user's request, STOP and explain to the user ` +
`what you were trying to do and why you need this permission. Let the user decide how to proceed.`
export function AUTO_REJECT_MESSAGE(toolName: string): string {
return `Permission to use ${toolName} has been denied. ${DENIAL_WORKAROUND_GUIDANCE}`
}
export function DONT_ASK_REJECT_MESSAGE(toolName: string): string {
return `Permission to use ${toolName} has been denied because Claude Code is running in don't ask mode. ${DENIAL_WORKAROUND_GUIDANCE}`
}
export const NO_RESPONSE_REQUESTED = 'No response requested.'
// Synthetic tool_result content inserted by ensureToolResultPairing when a
// tool_use block has no matching tool_result. Exported so HFI submission can
// reject any payload containing it — placeholder satisfies pairing structurally
// but the content is fake, which poisons training data if submitted.
export const SYNTHETIC_TOOL_RESULT_PLACEHOLDER =
'[Tool result missing due to internal error]'
// Prefix used by UI to detect classifier denials and render them concisely
const AUTO_MODE_REJECTION_PREFIX =
'Permission for this action has been denied. Reason: '
/**
* Check if a tool result message is a classifier denial.
* Used by the UI to render a short summary instead of the full message.
*/
export function isClassifierDenial(content: string): boolean {
return content.startsWith(AUTO_MODE_REJECTION_PREFIX)
}
/**
* Build a rejection message for auto mode classifier denials.
* Encourages continuing with other tasks and suggests permission rules.
*
* @param reason - The classifier's reason for denying the action
*/
export function buildYoloRejectionMessage(reason: string): string {
const prefix = AUTO_MODE_REJECTION_PREFIX
const ruleHint = feature('BASH_CLASSIFIER')
? `To allow this type of action in the future, the user can add a permission rule like ` +
`Bash(prompt: <description of allowed action>) to their settings. ` +
`At the end of your session, recommend what permission rules to add so you don't get blocked again.`
: `To allow this type of action in the future, the user can add a Bash permission rule to their settings.`
return (
`${prefix}${reason}. ` +
`If you have other tasks that don't depend on this action, continue working on those. ` +
`${DENIAL_WORKAROUND_GUIDANCE} ` +
ruleHint
)
}
/**
* Build a message for when the auto mode classifier is temporarily unavailable.
* Tells the agent to wait and retry, and suggests working on other tasks.
*/
export function buildClassifierUnavailableMessage(
toolName: string,
classifierModel: string,
): string {
return (
`${classifierModel} is temporarily unavailable, so auto mode cannot determine the safety of ${toolName} right now. ` +
`Wait briefly and then try this action again. ` +
`If it keeps failing, continue with other tasks that don't require this action and come back to it later. ` +
`Note: reading files, searching code, and other read-only operations do not require the classifier and can still be used.`
)
}
export const SYNTHETIC_MODEL = '<synthetic>'
export const SYNTHETIC_MESSAGES = new Set([
INTERRUPT_MESSAGE,
INTERRUPT_MESSAGE_FOR_TOOL_USE,
CANCEL_MESSAGE,
REJECT_MESSAGE,
NO_RESPONSE_REQUESTED,
])
export function isSyntheticMessage(message: Message): boolean {
return (
message.type !== 'progress' &&
message.type !== 'attachment' &&
message.type !== 'system' &&
Array.isArray(message.message.content) &&
message.message.content[0]?.type === 'text' &&
SYNTHETIC_MESSAGES.has(message.message.content[0].text)
)
}
function isSyntheticApiErrorMessage(
message: Message,
): message is AssistantMessage & { isApiErrorMessage: true } {
return (
message.type === 'assistant' &&
message.isApiErrorMessage === true &&
message.message.model === SYNTHETIC_MODEL
)
}
export function getLastAssistantMessage(
messages: Message[],
): AssistantMessage | undefined {
// findLast exits early from the end — much faster than filter + last for
// large message arrays (called on every REPL render via useFeedbackSurvey).
return messages.findLast(
(msg): msg is AssistantMessage => msg.type === 'assistant',
)
}
export function hasToolCallsInLastAssistantTurn(messages: Message[]): boolean {
for (let i = messages.length - 1; i >= 0; i--) {
const message = messages[i]
if (message && message.type === 'assistant') {
const assistantMessage = message as AssistantMessage
const content = assistantMessage.message.content
if (Array.isArray(content)) {
return content.some(block => block.type === 'tool_use')
}
}
}
return false
}
function baseCreateAssistantMessage({
content,
isApiErrorMessage = false,
apiError,
error,
errorDetails,
isVirtual,
usage = {
input_tokens: 0,
output_tokens: 0,
cache_creation_input_tokens: 0,
cache_read_input_tokens: 0,
server_tool_use: { web_search_requests: 0, web_fetch_requests: 0 },
service_tier: null,
cache_creation: {
ephemeral_1h_input_tokens: 0,
ephemeral_5m_input_tokens: 0,
},
inference_geo: null,
iterations: null,
speed: null,
},
}: {
content: BetaContentBlock[]
isApiErrorMessage?: boolean
apiError?: AssistantMessage['apiError']
error?: SDKAssistantMessageError
errorDetails?: string
isVirtual?: true
usage?: Usage
}): AssistantMessage {
return {
type: 'assistant',
uuid: randomUUID(),
timestamp: new Date().toISOString(),
message: {
id: randomUUID(),
container: null,
model: SYNTHETIC_MODEL,
role: 'assistant',
stop_reason: 'stop_sequence',
stop_sequence: '',
type: 'message',
usage,
content,
context_management: null,
},
requestId: undefined,
apiError,
error,
errorDetails,
isApiErrorMessage,
isVirtual,
}
}
export function createAssistantMessage({
content,
usage,
isVirtual,
}: {
content: string | BetaContentBlock[]
usage?: Usage
isVirtual?: true
}): AssistantMessage {
return baseCreateAssistantMessage({
content:
typeof content === 'string'
? [
{
type: 'text' as const,
text: content === '' ? NO_CONTENT_MESSAGE : content,
} as BetaContentBlock, // NOTE: citations field is not supported in Bedrock API
]
: content,
usage,
isVirtual,
})
}
export function createAssistantAPIErrorMessage({
content,
apiError,
error,
errorDetails,
}: {
content: string
apiError?: AssistantMessage['apiError']
error?: SDKAssistantMessageError
errorDetails?: string
}): AssistantMessage {
return baseCreateAssistantMessage({
content: [
{
type: 'text' as const,
text: content === '' ? NO_CONTENT_MESSAGE : content,
} as BetaContentBlock, // NOTE: citations field is not supported in Bedrock API
],
isApiErrorMessage: true,
apiError,
error,
errorDetails,
})
}
export function createUserMessage({
content,
isMeta,
isVisibleInTranscriptOnly,
isVirtual,
isCompactSummary,
summarizeMetadata,
toolUseResult,
mcpMeta,
uuid,
timestamp,
imagePasteIds,
sourceToolAssistantUUID,
permissionMode,
origin,
}: {
content: string | ContentBlockParam[]
isMeta?: true
isVisibleInTranscriptOnly?: true
isVirtual?: true
isCompactSummary?: true
toolUseResult?: unknown // Matches tool's `Output` type
/** MCP protocol metadata to pass through to SDK consumers (never sent to model) */
mcpMeta?: {
_meta?: Record<string, unknown>
structuredContent?: Record<string, unknown>
}
uuid?: UUID | string
timestamp?: string
imagePasteIds?: number[]
// For tool_result messages: the UUID of the assistant message containing the matching tool_use
sourceToolAssistantUUID?: UUID
// Permission mode when message was sent (for rewind restoration)
permissionMode?: PermissionMode
summarizeMetadata?: {
messagesSummarized: number
userContext?: string
direction?: PartialCompactDirection
}
// Provenance of this message. undefined = human (keyboard).
origin?: MessageOrigin
}): UserMessage {
const m: UserMessage = {
type: 'user',
message: {
role: 'user',
content: content || NO_CONTENT_MESSAGE, // Make sure we don't send empty messages
},
isMeta,
isVisibleInTranscriptOnly,
isVirtual,
isCompactSummary,
summarizeMetadata,
uuid: (uuid as UUID | undefined) || randomUUID(),
timestamp: timestamp ?? new Date().toISOString(),
toolUseResult,
mcpMeta,
imagePasteIds,
sourceToolAssistantUUID,
permissionMode,
origin,
}
return m
}
export function prepareUserContent({
inputString,
precedingInputBlocks,
}: {
inputString: string
precedingInputBlocks: ContentBlockParam[]
}): string | ContentBlockParam[] {
if (precedingInputBlocks.length === 0) {
return inputString
}
return [
...precedingInputBlocks,
{
text: inputString,
type: 'text',
},
]
}
export function createUserInterruptionMessage({
toolUse = false,
}: {
toolUse?: boolean
}): UserMessage {
const content = toolUse ? INTERRUPT_MESSAGE_FOR_TOOL_USE : INTERRUPT_MESSAGE
return createUserMessage({
content: [
{
type: 'text',
text: content,
},
],
})
}
/**
* Creates a new synthetic user caveat message for local commands (eg. bash, slash).
* We need to create a new message each time because messages must have unique uuids.
*/
export function createSyntheticUserCaveatMessage(): UserMessage {
return createUserMessage({
content: `<${LOCAL_COMMAND_CAVEAT_TAG}>Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to.</${LOCAL_COMMAND_CAVEAT_TAG}>`,
isMeta: true,
})
}
/**
* Formats the command-input breadcrumb the model sees when a slash command runs.
*/
export function formatCommandInputTags(
commandName: string,
args: string,
): string {
return `<${COMMAND_NAME_TAG}>/${commandName}</${COMMAND_NAME_TAG}>
<${COMMAND_MESSAGE_TAG}>${commandName}</${COMMAND_MESSAGE_TAG}>
<${COMMAND_ARGS_TAG}>${args}</${COMMAND_ARGS_TAG}>`
}
/**
* Builds the breadcrumb trail the SDK set_model control handler injects
* so the model can see mid-conversation switches. Same shape the CLI's
* /model command produces via processSlashCommand.
*/
export function createModelSwitchBreadcrumbs(
modelArg: string,
resolvedDisplay: string,
): UserMessage[] {
return [
createSyntheticUserCaveatMessage(),
createUserMessage({ content: formatCommandInputTags('model', modelArg) }),
createUserMessage({
content: `<${LOCAL_COMMAND_STDOUT_TAG}>Set model to ${resolvedDisplay}</${LOCAL_COMMAND_STDOUT_TAG}>`,
}),
]
}
export function createProgressMessage<P extends Progress>({
toolUseID,
parentToolUseID,
data,
}: {
toolUseID: string
parentToolUseID: string
data: P
}): ProgressMessage<P> {
return {
type: 'progress',
data,
toolUseID,
parentToolUseID,
uuid: randomUUID(),
timestamp: new Date().toISOString(),
}
}
export function createToolResultStopMessage(
toolUseID: string,
): ToolResultBlockParam {
return {
type: 'tool_result',
content: CANCEL_MESSAGE,
is_error: true,
tool_use_id: toolUseID,
}
}
export function extractTag(html: string, tagName: string): string | null {
if (!html.trim() || !tagName.trim()) {
return null
}
const escapedTag = escapeRegExp(tagName)
// Create regex pattern that handles:
// 1. Self-closing tags
// 2. Tags with attributes
// 3. Nested tags of the same type
// 4. Multiline content
const pattern = new RegExp(
`<${escapedTag}(?:\\s+[^>]*)?>` + // Opening tag with optional attributes
'([\\s\\S]*?)' + // Content (non-greedy match)
`<\\/${escapedTag}>`, // Closing tag
'gi',
)
let match
let depth = 0
let lastIndex = 0
const openingTag = new RegExp(`<${escapedTag}(?:\\s+[^>]*?)?>`, 'gi')
const closingTag = new RegExp(`<\\/${escapedTag}>`, 'gi')
while ((match = pattern.exec(html)) !== null) {
// Check for nested tags
const content = match[1]
const beforeMatch = html.slice(lastIndex, match.index)
// Reset depth counter
depth = 0
// Count opening tags before this match
openingTag.lastIndex = 0
while (openingTag.exec(beforeMatch) !== null) {
depth++
}
// Count closing tags before this match
closingTag.lastIndex = 0
while (closingTag.exec(beforeMatch) !== null) {
depth--
}
// Only include content if we're at the correct nesting level
if (depth === 0 && content) {
return content
}
lastIndex = match.index + match[0].length
}
return null
}
export function isNotEmptyMessage(message: Message): boolean {
if (
message.type === 'progress' ||
message.type === 'attachment' ||
message.type === 'system'
) {
return true
}
if (typeof message.message.content === 'string') {
return message.message.content.trim().length > 0
}
if (message.message.content.length === 0) {
return false
}
// Skip multi-block messages for now
if (message.message.content.length > 1) {
return true
}
if (message.message.content[0]!.type !== 'text') {
return true
}
return (
message.message.content[0]!.text.trim().length > 0 &&
message.message.content[0]!.text !== NO_CONTENT_MESSAGE &&
message.message.content[0]!.text !== INTERRUPT_MESSAGE_FOR_TOOL_USE
)
}
// Deterministic UUID derivation. Produces a stable UUID-shaped string from a
// parent UUID + content block index so that the same input always produces the
// same key across calls. Used by normalizeMessages and synthetic message creation.
export function deriveUUID(parentUUID: UUID, index: number): UUID {
const hex = index.toString(16).padStart(12, '0')
return `${parentUUID.slice(0, 24)}${hex}` as UUID
}
// Split messages, so each content block gets its own message
export function normalizeMessages(
messages: AssistantMessage[],
): NormalizedAssistantMessage[]
export function normalizeMessages(
messages: UserMessage[],
): NormalizedUserMessage[]
export function normalizeMessages(
messages: (AssistantMessage | UserMessage)[],
): (NormalizedAssistantMessage | NormalizedUserMessage)[]
export function normalizeMessages(messages: Message[]): NormalizedMessage[]
export function normalizeMessages(messages: Message[]): NormalizedMessage[] {
// isNewChain tracks whether we need to generate new UUIDs for messages when normalizing.
// When a message has multiple content blocks, we split it into multiple messages,
// each with a single content block. When this happens, we need to generate new UUIDs
// for all subsequent messages to maintain proper ordering and prevent duplicate UUIDs.
// This flag is set to true once we encounter a message with multiple content blocks,
// and remains true for all subsequent messages in the normalization process.
let isNewChain = false
return messages.flatMap(message => {
switch (message.type) {
case 'assistant': {
isNewChain = isNewChain || message.message.content.length > 1
return message.message.content.map((_, index) => {
const uuid = isNewChain
? deriveUUID(message.uuid, index)
: message.uuid
return {
type: 'assistant' as const,
timestamp: message.timestamp,
message: {
...message.message,
content: [_],
context_management: message.message.context_management ?? null,
},
isMeta: message.isMeta,
isVirtual: message.isVirtual,
requestId: message.requestId,
uuid,
error: message.error,
isApiErrorMessage: message.isApiErrorMessage,
advisorModel: message.advisorModel,
} as NormalizedAssistantMessage
})
}
case 'attachment':
return [message]
case 'progress':
return [message]
case 'system':
return [message]
case 'user': {
if (typeof message.message.content === 'string') {
const uuid = isNewChain ? deriveUUID(message.uuid, 0) : message.uuid
return [
{
...message,
uuid,
message: {
...message.message,
content: [{ type: 'text', text: message.message.content }],
},
} as NormalizedMessage,
]
}
isNewChain = isNewChain || message.message.content.length > 1
let imageIndex = 0
return message.message.content.map((_, index) => {
const isImage = _.type === 'image'
// For image content blocks, extract just the ID for this image
const imageId =
isImage && message.imagePasteIds
? message.imagePasteIds[imageIndex]
: undefined
if (isImage) imageIndex++
return {
...createUserMessage({
content: [_],
toolUseResult: message.toolUseResult,
mcpMeta: message.mcpMeta,
isMeta: message.isMeta,
isVisibleInTranscriptOnly: message.isVisibleInTranscriptOnly,
isVirtual: message.isVirtual,
timestamp: message.timestamp,
imagePasteIds: imageId !== undefined ? [imageId] : undefined,
origin: message.origin,
}),
uuid: isNewChain ? deriveUUID(message.uuid, index) : message.uuid,
} as NormalizedMessage
})
}
}
})
}
type ToolUseRequestMessage = NormalizedAssistantMessage & {
message: { content: [ToolUseBlock] }
}
export function isToolUseRequestMessage(
message: Message,
): message is ToolUseRequestMessage {
return (
message.type === 'assistant' &&
// Note: stop_reason === 'tool_use' is unreliable -- it's not always set correctly
message.message.content.some(_ => _.type === 'tool_use')
)
}
type ToolUseResultMessage = NormalizedUserMessage & {
message: { content: [ToolResultBlockParam] }
}
export function isToolUseResultMessage(
message: Message,
): message is ToolUseResultMessage {
return (
message.type === 'user' &&
((Array.isArray(message.message.content) &&
message.message.content[0]?.type === 'tool_result') ||
Boolean(message.toolUseResult))
)
}
// Re-order, to move result messages to be after their tool use messages
export function reorderMessagesInUI(
messages: (
| NormalizedUserMessage
| NormalizedAssistantMessage
| AttachmentMessage
| SystemMessage
)[],
syntheticStreamingToolUseMessages: NormalizedAssistantMessage[],
): (
| NormalizedUserMessage
| NormalizedAssistantMessage
| AttachmentMessage
| SystemMessage
)[] {
// Maps tool use ID to its related messages
const toolUseGroups = new Map<
string,
{
toolUse: ToolUseRequestMessage | null
preHooks: AttachmentMessage[]
toolResult: NormalizedUserMessage | null
postHooks: AttachmentMessage[]
}
>()
// First pass: group messages by tool use ID
for (const message of messages) {
// Handle tool use messages
if (isToolUseRequestMessage(message)) {
const toolUseID = message.message.content[0]?.id
if (toolUseID) {
if (!toolUseGroups.has(toolUseID)) {
toolUseGroups.set(toolUseID, {
toolUse: null,
preHooks: [],
toolResult: null,
postHooks: [],
})
}
toolUseGroups.get(toolUseID)!.toolUse = message
}
continue
}
// Handle pre-tool-use hooks
if (
isHookAttachmentMessage(message) &&
message.attachment.hookEvent === 'PreToolUse'
) {
const toolUseID = message.attachment.toolUseID
if (!toolUseGroups.has(toolUseID)) {
toolUseGroups.set(toolUseID, {
toolUse: null,
preHooks: [],
toolResult: null,
postHooks: [],
})
}
toolUseGroups.get(toolUseID)!.preHooks.push(message)
continue
}
// Handle tool results
if (
message.type === 'user' &&
message.message.content[0]?.type === 'tool_result'
) {
const toolUseID = message.message.content[0].tool_use_id
if (!toolUseGroups.has(toolUseID)) {
toolUseGroups.set(toolUseID, {
toolUse: null,
preHooks: [],
toolResult: null,
postHooks: [],
})
}
toolUseGroups.get(toolUseID)!.toolResult = message
continue
}
// Handle post-tool-use hooks
if (
isHookAttachmentMessage(message) &&
message.attachment.hookEvent === 'PostToolUse'
) {
const toolUseID = message.attachment.toolUseID
if (!toolUseGroups.has(toolUseID)) {
toolUseGroups.set(toolUseID, {
toolUse: null,
preHooks: [],
toolResult: null,
postHooks: [],
})
}
toolUseGroups.get(toolUseID)!.postHooks.push(message)
continue
}
}
// Second pass: reconstruct the message list in the correct order
const result: (
| NormalizedUserMessage
| NormalizedAssistantMessage
| AttachmentMessage
| SystemMessage
)[] = []
const processedToolUses = new Set<string>()
for (const message of messages) {
// Check if this is a tool use
if (isToolUseRequestMessage(message)) {
const toolUseID = message.message.content[0]?.id
if (toolUseID && !processedToolUses.has(toolUseID)) {
processedToolUses.add(toolUseID)
const group = toolUseGroups.get(toolUseID)
if (group && group.toolUse) {
// Output in order: tool use, pre hooks, tool result, post hooks
result.push(group.toolUse)
result.push(...group.preHooks)
if (group.toolResult) {
result.push(group.toolResult)
}
result.push(...group.postHooks)
}
}
continue
}
// Check if this message is part of a tool use group
if (
isHookAttachmentMessage(message) &&
(message.attachment.hookEvent === 'PreToolUse' ||
message.attachment.hookEvent === 'PostToolUse')
) {
// Skip - already handled in tool use groups
continue
}
if (
message.type === 'user' &&
message.message.content[0]?.type === 'tool_result'
) {
// Skip - already handled in tool use groups
continue
}