forked from sanbuphy/learn-coding-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattachments.ts
More file actions
3997 lines (3651 loc) · 124 KB
/
attachments.ts
File metadata and controls
3997 lines (3651 loc) · 124 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
// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered
import {
logEvent,
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
} from 'src/services/analytics/index.js'
import {
toolMatchesName,
type Tools,
type ToolUseContext,
type ToolPermissionContext,
} from '../Tool.js'
import {
FileReadTool,
MaxFileReadTokenExceededError,
type Output as FileReadToolOutput,
readImageWithTokenBudget,
} from '../tools/FileReadTool/FileReadTool.js'
import { FileTooLargeError, readFileInRange } from './readFileInRange.js'
import { expandPath } from './path.js'
import { countCharInString } from './stringUtils.js'
import { count, uniq } from './array.js'
import { getFsImplementation } from './fsOperations.js'
import { readdir, stat } from 'fs/promises'
import type { IDESelection } from '../hooks/useIdeSelection.js'
import { TODO_WRITE_TOOL_NAME } from '../tools/TodoWriteTool/constants.js'
import { TASK_CREATE_TOOL_NAME } from '../tools/TaskCreateTool/constants.js'
import { TASK_UPDATE_TOOL_NAME } from '../tools/TaskUpdateTool/constants.js'
import { BASH_TOOL_NAME } from '../tools/BashTool/toolName.js'
import { SKILL_TOOL_NAME } from '../tools/SkillTool/constants.js'
import type { TodoList } from './todo/types.js'
import {
type Task,
listTasks,
getTaskListId,
isTodoV2Enabled,
} from './tasks.js'
import { getPlanFilePath, getPlan } from './plans.js'
import { getConnectedIdeName } from './ide.js'
import {
filterInjectedMemoryFiles,
getManagedAndUserConditionalRules,
getMemoryFiles,
getMemoryFilesForNestedDirectory,
getConditionalRulesForCwdLevelDirectory,
type MemoryFileInfo,
} from './claudemd.js'
import { dirname, parse, relative, resolve } from 'path'
import { getCwd } from 'src/utils/cwd.js'
import { getViewedTeammateTask } from '../state/selectors.js'
import { logError } from './log.js'
import { logAntError } from './debug.js'
import { isENOENT, toError } from './errors.js'
import type { DiagnosticFile } from '../services/diagnosticTracking.js'
import { diagnosticTracker } from '../services/diagnosticTracking.js'
import type {
AttachmentMessage,
Message,
MessageOrigin,
} from 'src/types/message.js'
import {
type QueuedCommand,
getImagePasteIds,
isValidImagePaste,
} from 'src/types/textInputTypes.js'
import { randomUUID, type UUID } from 'crypto'
import { getSettings_DEPRECATED } from './settings/settings.js'
import { getSnippetForTwoFileDiff } from 'src/tools/FileEditTool/utils.js'
import type {
ContentBlockParam,
ImageBlockParam,
Base64ImageSource,
} from '@anthropic-ai/sdk/resources/messages.mjs'
import { maybeResizeAndDownsampleImageBlock } from './imageResizer.js'
import type { PastedContent } from './config.js'
import { getGlobalConfig } from './config.js'
import {
getDefaultSonnetModel,
getDefaultHaikuModel,
getDefaultOpusModel,
} from './model/model.js'
import type { ReadResourceResult } from '@modelcontextprotocol/sdk/types.js'
import { getSkillToolCommands, getMcpSkillCommands } from '../commands.js'
import type { Command } from '../types/command.js'
import uniqBy from 'lodash-es/uniqBy.js'
import { getProjectRoot } from '../bootstrap/state.js'
import { formatCommandsWithinBudget } from '../tools/SkillTool/prompt.js'
import { getContextWindowForModel } from './context.js'
import type { DiscoverySignal } from '../services/skillSearch/signals.js'
// Conditional require for DCE. All skill-search string literals that would
// otherwise leak into external builds live inside these modules. The only
// surfaces in THIS file are: the maybe() call (gated via spread below) and
// the skill_listing suppression check (uses the same skillSearchModules null
// check). The type-only DiscoverySignal import above is erased at compile time.
/* eslint-disable @typescript-eslint/no-require-imports */
const skillSearchModules = feature('EXPERIMENTAL_SKILL_SEARCH')
? {
featureCheck:
require('../services/skillSearch/featureCheck.js') as typeof import('../services/skillSearch/featureCheck.js'),
prefetch:
require('../services/skillSearch/prefetch.js') as typeof import('../services/skillSearch/prefetch.js'),
}
: null
const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER')
? (require('./permissions/autoModeState.js') as typeof import('./permissions/autoModeState.js'))
: null
/* eslint-enable @typescript-eslint/no-require-imports */
import {
MAX_LINES_TO_READ,
FILE_READ_TOOL_NAME,
} from 'src/tools/FileReadTool/prompt.js'
import { getDefaultFileReadingLimits } from 'src/tools/FileReadTool/limits.js'
import { cacheKeys, type FileStateCache } from './fileStateCache.js'
import {
createAbortController,
createChildAbortController,
} from './abortController.js'
import { isAbortError } from './errors.js'
import {
getFileModificationTimeAsync,
isFileWithinReadSizeLimit,
} from './file.js'
import type { AgentDefinition } from '../tools/AgentTool/loadAgentsDir.js'
import { filterAgentsByMcpRequirements } from '../tools/AgentTool/loadAgentsDir.js'
import { AGENT_TOOL_NAME } from '../tools/AgentTool/constants.js'
import {
formatAgentLine,
shouldInjectAgentListInMessages,
} from '../tools/AgentTool/prompt.js'
import { filterDeniedAgents } from './permissions/permissions.js'
import { getSubscriptionType } from './auth.js'
import { mcpInfoFromString } from '../services/mcp/mcpStringUtils.js'
import {
matchingRuleForInput,
pathInAllowedWorkingPath,
} from './permissions/filesystem.js'
import {
generateTaskAttachments,
applyTaskOffsetsAndEvictions,
} from './task/framework.js'
import { getTaskOutputPath } from './task/diskOutput.js'
import { drainPendingMessages } from '../tasks/LocalAgentTask/LocalAgentTask.js'
import type { TaskType, TaskStatus } from '../Task.js'
import {
getOriginalCwd,
getSessionId,
getSdkBetas,
getTotalCostUSD,
getTotalOutputTokens,
getCurrentTurnTokenBudget,
getTurnOutputTokens,
hasExitedPlanModeInSession,
setHasExitedPlanMode,
needsPlanModeExitAttachment,
setNeedsPlanModeExitAttachment,
needsAutoModeExitAttachment,
setNeedsAutoModeExitAttachment,
getLastEmittedDate,
setLastEmittedDate,
getKairosActive,
} from '../bootstrap/state.js'
import type { QuerySource } from '../constants/querySource.js'
import {
getDeferredToolsDelta,
isDeferredToolsDeltaEnabled,
isToolSearchEnabledOptimistic,
isToolSearchToolAvailable,
modelSupportsToolReference,
type DeferredToolsDeltaScanContext,
} from './toolSearch.js'
import {
getMcpInstructionsDelta,
isMcpInstructionsDeltaEnabled,
type ClientSideInstruction,
} from './mcpInstructionsDelta.js'
import { CLAUDE_IN_CHROME_MCP_SERVER_NAME } from './claudeInChrome/common.js'
import { CHROME_TOOL_SEARCH_INSTRUCTIONS } from './claudeInChrome/prompt.js'
import type { MCPServerConnection } from '../services/mcp/types.js'
import type {
HookEvent,
SyncHookJSONOutput,
} from 'src/entrypoints/agentSdkTypes.js'
import {
checkForAsyncHookResponses,
removeDeliveredAsyncHooks,
} from './hooks/AsyncHookRegistry.js'
import {
checkForLSPDiagnostics,
clearAllLSPDiagnostics,
} from '../services/lsp/LSPDiagnosticRegistry.js'
import { logForDebugging } from './debug.js'
import {
extractTextContent,
getUserMessageText,
isThinkingMessage,
} from './messages.js'
import { isHumanTurn } from './messagePredicates.js'
import { isEnvTruthy, getClaudeConfigHomeDir } from './envUtils.js'
import { feature } from 'bun:bundle'
/* eslint-disable @typescript-eslint/no-require-imports */
const BRIEF_TOOL_NAME: string | null =
feature('KAIROS') || feature('KAIROS_BRIEF')
? (
require('../tools/BriefTool/prompt.js') as typeof import('../tools/BriefTool/prompt.js')
).BRIEF_TOOL_NAME
: null
const sessionTranscriptModule = feature('KAIROS')
? (require('../services/sessionTranscript/sessionTranscript.js') as typeof import('../services/sessionTranscript/sessionTranscript.js'))
: null
/* eslint-enable @typescript-eslint/no-require-imports */
import { hasUltrathinkKeyword, isUltrathinkEnabled } from './thinking.js'
import {
tokenCountFromLastAPIResponse,
tokenCountWithEstimation,
} from './tokens.js'
import {
getEffectiveContextWindowSize,
isAutoCompactEnabled,
} from '../services/compact/autoCompact.js'
import { getFeatureValue_CACHED_MAY_BE_STALE } from '../services/analytics/growthbook.js'
import {
hasInstructionsLoadedHook,
executeInstructionsLoadedHooks,
type HookBlockingError,
type InstructionsMemoryType,
} from './hooks.js'
import { jsonStringify } from './slowOperations.js'
import { isPDFExtension } from './pdfUtils.js'
import { getLocalISODate } from '../constants/common.js'
import { getPDFPageCount } from './pdf.js'
import { PDF_AT_MENTION_INLINE_THRESHOLD } from '../constants/apiLimits.js'
import { isAgentSwarmsEnabled } from './agentSwarmsEnabled.js'
import { findRelevantMemories } from '../memdir/findRelevantMemories.js'
import { memoryAge, memoryFreshnessText } from '../memdir/memoryAge.js'
import { getAutoMemPath, isAutoMemoryEnabled } from '../memdir/paths.js'
import { getAgentMemoryDir } from '../tools/AgentTool/agentMemory.js'
import {
readUnreadMessages,
markMessagesAsReadByPredicate,
isShutdownApproved,
isStructuredProtocolMessage,
isIdleNotification,
} from './teammateMailbox.js'
import {
getAgentName,
getAgentId,
getTeamName,
isTeamLead,
} from './teammate.js'
import { isInProcessTeammate } from './teammateContext.js'
import { removeTeammateFromTeamFile } from './swarm/teamHelpers.js'
import { unassignTeammateTasks } from './tasks.js'
import { getCompanionIntroAttachment } from '../buddy/prompt.js'
export const TODO_REMINDER_CONFIG = {
TURNS_SINCE_WRITE: 10,
TURNS_BETWEEN_REMINDERS: 10,
} as const
export const PLAN_MODE_ATTACHMENT_CONFIG = {
TURNS_BETWEEN_ATTACHMENTS: 5,
FULL_REMINDER_EVERY_N_ATTACHMENTS: 5,
} as const
export const AUTO_MODE_ATTACHMENT_CONFIG = {
TURNS_BETWEEN_ATTACHMENTS: 5,
FULL_REMINDER_EVERY_N_ATTACHMENTS: 5,
} as const
const MAX_MEMORY_LINES = 200
// Line cap alone doesn't bound size (200 × 500-char lines = 100KB). The
// surfacer injects up to 5 files per turn via <system-reminder>, bypassing
// the per-message tool-result budget, so a tight per-file byte cap keeps
// aggregate injection bounded (5 × 4KB = 20KB/turn). Enforced via
// readFileInRange's truncateOnByteLimit option. Truncation means the
// most-relevant memory still surfaces: the frontmatter + opening context
// is usually what matters.
const MAX_MEMORY_BYTES = 4096
export const RELEVANT_MEMORIES_CONFIG = {
// Per-turn cap (5 × 4KB = 20KB) bounds a single injection, but over a
// long session the selector keeps surfacing distinct files — ~26K tokens/
// session observed in prod. Cap the cumulative bytes: once hit, stop
// prefetching entirely. Budget is ~3 full injections; after that the
// most-relevant memories are already in context. Scanning messages
// (rather than tracking in toolUseContext) means compact naturally
// resets the counter — old attachments are gone from context, so
// re-surfacing is valid.
MAX_SESSION_BYTES: 60 * 1024,
} as const
export const VERIFY_PLAN_REMINDER_CONFIG = {
TURNS_BETWEEN_REMINDERS: 10,
} as const
export type FileAttachment = {
type: 'file'
filename: string
content: FileReadToolOutput
/**
* Whether the file was truncated due to size limits
*/
truncated?: boolean
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
export type CompactFileReferenceAttachment = {
type: 'compact_file_reference'
filename: string
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
export type PDFReferenceAttachment = {
type: 'pdf_reference'
filename: string
pageCount: number
fileSize: number
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
export type AlreadyReadFileAttachment = {
type: 'already_read_file'
filename: string
content: FileReadToolOutput
/**
* Whether the file was truncated due to size limits
*/
truncated?: boolean
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
export type AgentMentionAttachment = {
type: 'agent_mention'
agentType: string
}
export type AsyncHookResponseAttachment = {
type: 'async_hook_response'
processId: string
hookName: string
hookEvent: HookEvent | 'StatusLine' | 'FileSuggestion'
toolName?: string
response: SyncHookJSONOutput
stdout: string
stderr: string
exitCode?: number
}
export type HookAttachment =
| HookCancelledAttachment
| {
type: 'hook_blocking_error'
blockingError: HookBlockingError
hookName: string
toolUseID: string
hookEvent: HookEvent
}
| HookNonBlockingErrorAttachment
| HookErrorDuringExecutionAttachment
| {
type: 'hook_stopped_continuation'
message: string
hookName: string
toolUseID: string
hookEvent: HookEvent
}
| HookSuccessAttachment
| {
type: 'hook_additional_context'
content: string[]
hookName: string
toolUseID: string
hookEvent: HookEvent
}
| HookSystemMessageAttachment
| HookPermissionDecisionAttachment
export type HookPermissionDecisionAttachment = {
type: 'hook_permission_decision'
decision: 'allow' | 'deny'
toolUseID: string
hookEvent: HookEvent
}
export type HookSystemMessageAttachment = {
type: 'hook_system_message'
content: string
hookName: string
toolUseID: string
hookEvent: HookEvent
}
export type HookCancelledAttachment = {
type: 'hook_cancelled'
hookName: string
toolUseID: string
hookEvent: HookEvent
command?: string
durationMs?: number
}
export type HookErrorDuringExecutionAttachment = {
type: 'hook_error_during_execution'
content: string
hookName: string
toolUseID: string
hookEvent: HookEvent
command?: string
durationMs?: number
}
export type HookSuccessAttachment = {
type: 'hook_success'
content: string
hookName: string
toolUseID: string
hookEvent: HookEvent
stdout?: string
stderr?: string
exitCode?: number
command?: string
durationMs?: number
}
export type HookNonBlockingErrorAttachment = {
type: 'hook_non_blocking_error'
hookName: string
stderr: string
stdout: string
exitCode: number
toolUseID: string
hookEvent: HookEvent
command?: string
durationMs?: number
}
export type Attachment =
/**
* User at-mentioned the file
*/
| FileAttachment
| CompactFileReferenceAttachment
| PDFReferenceAttachment
| AlreadyReadFileAttachment
/**
* An at-mentioned file was edited
*/
| {
type: 'edited_text_file'
filename: string
snippet: string
}
| {
type: 'edited_image_file'
filename: string
content: FileReadToolOutput
}
| {
type: 'directory'
path: string
content: string
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
| {
type: 'selected_lines_in_ide'
ideName: string
lineStart: number
lineEnd: number
filename: string
content: string
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
| {
type: 'opened_file_in_ide'
filename: string
}
| {
type: 'todo_reminder'
content: TodoList
itemCount: number
}
| {
type: 'task_reminder'
content: Task[]
itemCount: number
}
| {
type: 'nested_memory'
path: string
content: MemoryFileInfo
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
| {
type: 'relevant_memories'
memories: {
path: string
content: string
mtimeMs: number
/**
* Pre-computed header string (age + path prefix). Computed once
* at attachment-creation time so the rendered bytes are stable
* across turns — recomputing memoryAge(mtimeMs) at render time
* calls Date.now(), so "saved 3 days ago" becomes "saved 4 days
* ago" across turns → different bytes → prompt cache bust.
* Optional for backward compat with resumed sessions; render
* path falls back to recomputing if missing.
*/
header?: string
/**
* lineCount when the file was truncated by readMemoriesForSurfacing,
* else undefined. Threaded to the readFileState write so
* getChangedFiles skips truncated memories (partial content would
* yield a misleading diff).
*/
limit?: number
}[]
}
| {
type: 'dynamic_skill'
skillDir: string
skillNames: string[]
/** Path relative to CWD at creation time, for stable display */
displayPath: string
}
| {
type: 'skill_listing'
content: string
skillCount: number
isInitial: boolean
}
| {
type: 'skill_discovery'
skills: { name: string; description: string; shortId?: string }[]
signal: DiscoverySignal
source: 'native' | 'aki' | 'both'
}
| {
type: 'queued_command'
prompt: string | Array<ContentBlockParam>
source_uuid?: UUID
imagePasteIds?: number[]
/** Original queue mode — 'prompt' for user messages, 'task-notification' for system events */
commandMode?: string
/** Provenance carried from QueuedCommand so mid-turn drains preserve it */
origin?: MessageOrigin
/** Carried from QueuedCommand.isMeta — distinguishes human-typed from system-injected */
isMeta?: boolean
}
| {
type: 'output_style'
style: string
}
| {
type: 'diagnostics'
files: DiagnosticFile[]
isNew: boolean
}
| {
type: 'plan_mode'
reminderType: 'full' | 'sparse'
isSubAgent?: boolean
planFilePath: string
planExists: boolean
}
| {
type: 'plan_mode_reentry'
planFilePath: string
}
| {
type: 'plan_mode_exit'
planFilePath: string
planExists: boolean
}
| {
type: 'auto_mode'
reminderType: 'full' | 'sparse'
}
| {
type: 'auto_mode_exit'
}
| {
type: 'critical_system_reminder'
content: string
}
| {
type: 'plan_file_reference'
planFilePath: string
planContent: string
}
| {
type: 'mcp_resource'
server: string
uri: string
name: string
description?: string
content: ReadResourceResult
}
| {
type: 'command_permissions'
allowedTools: string[]
model?: string
}
| AgentMentionAttachment
| {
type: 'task_status'
taskId: string
taskType: TaskType
status: TaskStatus
description: string
deltaSummary: string | null
outputFilePath?: string
}
| AsyncHookResponseAttachment
| {
type: 'token_usage'
used: number
total: number
remaining: number
}
| {
type: 'budget_usd'
used: number
total: number
remaining: number
}
| {
type: 'output_token_usage'
turn: number
session: number
budget: number | null
}
| {
type: 'structured_output'
data: unknown
}
| TeammateMailboxAttachment
| TeamContextAttachment
| HookAttachment
| {
type: 'invoked_skills'
skills: Array<{
name: string
path: string
content: string
}>
}
| {
type: 'verify_plan_reminder'
}
| {
type: 'max_turns_reached'
maxTurns: number
turnCount: number
}
| {
type: 'current_session_memory'
content: string
path: string
tokenCount: number
}
| {
type: 'teammate_shutdown_batch'
count: number
}
| {
type: 'compaction_reminder'
}
| {
type: 'context_efficiency'
}
| {
type: 'date_change'
newDate: string
}
| {
type: 'ultrathink_effort'
level: 'high'
}
| {
type: 'deferred_tools_delta'
addedNames: string[]
addedLines: string[]
removedNames: string[]
}
| {
type: 'agent_listing_delta'
addedTypes: string[]
addedLines: string[]
removedTypes: string[]
/** True when this is the first announcement in the conversation */
isInitial: boolean
/** Whether to include the "launch multiple agents concurrently" note (non-pro subscriptions) */
showConcurrencyNote: boolean
}
| {
type: 'mcp_instructions_delta'
addedNames: string[]
addedBlocks: string[]
removedNames: string[]
}
| {
type: 'companion_intro'
name: string
species: string
}
| {
type: 'bagel_console'
errorCount: number
warningCount: number
sample: string
}
export type TeammateMailboxAttachment = {
type: 'teammate_mailbox'
messages: Array<{
from: string
text: string
timestamp: string
color?: string
summary?: string
}>
}
export type TeamContextAttachment = {
type: 'team_context'
agentId: string
agentName: string
teamName: string
teamConfigPath: string
taskListPath: string
}
/**
* This is janky
* TODO: Generate attachments when we create messages
*/
export async function getAttachments(
input: string | null,
toolUseContext: ToolUseContext,
ideSelection: IDESelection | null,
queuedCommands: QueuedCommand[],
messages?: Message[],
querySource?: QuerySource,
options?: { skipSkillDiscovery?: boolean },
): Promise<Attachment[]> {
if (
isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_ATTACHMENTS) ||
isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)
) {
// query.ts:removeFromQueue dequeues these unconditionally after
// getAttachmentMessages runs — returning [] here silently drops them.
// Coworker runs with --bare and depends on task-notification for
// mid-tool-call notifications from Local*Task/Remote*Task.
return getQueuedCommandAttachments(queuedCommands)
}
// This will slow down submissions
// TODO: Compute attachments as the user types, not here (though we use this
// function for slash command prompts too)
const abortController = createAbortController()
const timeoutId = setTimeout(ac => ac.abort(), 1000, abortController)
const context = { ...toolUseContext, abortController }
const isMainThread = !toolUseContext.agentId
// Attachments which are added in response to on user input
const userInputAttachments = input
? [
maybe('at_mentioned_files', () =>
processAtMentionedFiles(input, context),
),
maybe('mcp_resources', () =>
processMcpResourceAttachments(input, context),
),
maybe('agent_mentions', () =>
Promise.resolve(
processAgentMentions(
input,
toolUseContext.options.agentDefinitions.activeAgents,
),
),
),
// Skill discovery on turn 0 (user input as signal). Inter-turn
// discovery runs via startSkillDiscoveryPrefetch in query.ts,
// gated on write-pivot detection — see skillSearch/prefetch.ts.
// feature() here lets DCE drop the 'skill_discovery' string (and the
// function it calls) from external builds.
//
// skipSkillDiscovery gates out the SKILL.md-expansion path
// (getMessagesForPromptSlashCommand). When a skill is invoked, its
// SKILL.md content is passed as `input` here to extract @-mentions —
// but that content is NOT user intent and must not trigger discovery.
// Without this gate, a 110KB SKILL.md fires ~3.3s of chunked AKI
// queries on every skill invocation (session 13a9afae).
...(feature('EXPERIMENTAL_SKILL_SEARCH') &&
skillSearchModules &&
!options?.skipSkillDiscovery
? [
maybe('skill_discovery', () =>
skillSearchModules.prefetch.getTurnZeroSkillDiscovery(
input,
messages ?? [],
context,
),
),
]
: []),
]
: []
// Process user input attachments first (includes @mentioned files)
// This ensures files are added to nestedMemoryAttachmentTriggers before nested_memory processes them
const userAttachmentResults = await Promise.all(userInputAttachments)
// Thread-safe attachments available in sub-agents
// NOTE: These must be created AFTER userInputAttachments completes to ensure
// nestedMemoryAttachmentTriggers is populated before getNestedMemoryAttachments runs
const allThreadAttachments = [
// queuedCommands is already agent-scoped by the drain gate in query.ts —
// main thread gets agentId===undefined, subagents get their own agentId.
// Must run for all threads or subagent notifications drain into the void
// (removed from queue by removeFromQueue but never attached).
maybe('queued_commands', () => getQueuedCommandAttachments(queuedCommands)),
maybe('date_change', () =>
Promise.resolve(getDateChangeAttachments(messages)),
),
maybe('ultrathink_effort', () =>
Promise.resolve(getUltrathinkEffortAttachment(input)),
),
maybe('deferred_tools_delta', () =>
Promise.resolve(
getDeferredToolsDeltaAttachment(
toolUseContext.options.tools,
toolUseContext.options.mainLoopModel,
messages,
{
callSite: isMainThread
? 'attachments_main'
: 'attachments_subagent',
querySource,
},
),
),
),
maybe('agent_listing_delta', () =>
Promise.resolve(getAgentListingDeltaAttachment(toolUseContext, messages)),
),
maybe('mcp_instructions_delta', () =>
Promise.resolve(
getMcpInstructionsDeltaAttachment(
toolUseContext.options.mcpClients,
toolUseContext.options.tools,
toolUseContext.options.mainLoopModel,
messages,
),
),
),
...(feature('BUDDY')
? [
maybe('companion_intro', () =>
Promise.resolve(getCompanionIntroAttachment(messages)),
),
]
: []),
maybe('changed_files', () => getChangedFiles(context)),
maybe('nested_memory', () => getNestedMemoryAttachments(context)),
// relevant_memories moved to async prefetch (startRelevantMemoryPrefetch)
maybe('dynamic_skill', () => getDynamicSkillAttachments(context)),
maybe('skill_listing', () => getSkillListingAttachments(context)),
// Inter-turn skill discovery now runs via startSkillDiscoveryPrefetch
// (query.ts, concurrent with the main turn). The blocking call that
// previously lived here was the assistant_turn signal — 97% of those
// Haiku calls found nothing in prod. Prefetch + await-at-collection
// replaces it; see src/services/skillSearch/prefetch.ts.
maybe('plan_mode', () => getPlanModeAttachments(messages, toolUseContext)),
maybe('plan_mode_exit', () => getPlanModeExitAttachment(toolUseContext)),
...(feature('TRANSCRIPT_CLASSIFIER')
? [
maybe('auto_mode', () =>
getAutoModeAttachments(messages, toolUseContext),
),
maybe('auto_mode_exit', () =>
getAutoModeExitAttachment(toolUseContext),
),
]
: []),
maybe('todo_reminders', () =>
isTodoV2Enabled()
? getTaskReminderAttachments(messages, toolUseContext)
: getTodoReminderAttachments(messages, toolUseContext),
),
...(isAgentSwarmsEnabled()
? [
// Skip teammate mailbox for the session_memory forked agent.
// It shares AppState.teamContext with the leader, so isTeamLead resolves
// true and it reads+marks-as-read the leader's DMs as ephemeral attachments,
// silently stealing messages that should be delivered as permanent turns.
...(querySource === 'session_memory'
? []
: [
maybe('teammate_mailbox', async () =>
getTeammateMailboxAttachments(toolUseContext),
),
]),
maybe('team_context', async () =>
getTeamContextAttachment(messages ?? []),
),
]
: []),
maybe('agent_pending_messages', async () =>
getAgentPendingMessageAttachments(toolUseContext),
),
maybe('critical_system_reminder', () =>
Promise.resolve(getCriticalSystemReminderAttachment(toolUseContext)),
),
...(feature('COMPACTION_REMINDERS')
? [
maybe('compaction_reminder', () =>
Promise.resolve(
getCompactionReminderAttachment(
messages ?? [],
toolUseContext.options.mainLoopModel,
),
),
),
]
: []),
...(feature('HISTORY_SNIP')
? [
maybe('context_efficiency', () =>
Promise.resolve(getContextEfficiencyAttachment(messages ?? [])),
),
]
: []),
]
// Attachments which are semantically only for the main conversation or don't have concurrency-safe implementations
const mainThreadAttachments = isMainThread
? [
maybe('ide_selection', async () =>
getSelectedLinesFromIDE(ideSelection, toolUseContext),
),
maybe('ide_opened_file', async () =>
getOpenedFileFromIDE(ideSelection, toolUseContext),
),
maybe('output_style', async () =>
Promise.resolve(getOutputStyleAttachment()),
),
maybe('diagnostics', async () =>
getDiagnosticAttachments(toolUseContext),
),
maybe('lsp_diagnostics', async () =>
getLSPDiagnosticAttachments(toolUseContext),
),
maybe('unified_tasks', async () =>
getUnifiedTaskAttachments(toolUseContext),
),
maybe('async_hook_responses', async () =>
getAsyncHookResponseAttachments(),
),
maybe('token_usage', async () =>
Promise.resolve(
getTokenUsageAttachment(
messages ?? [],
toolUseContext.options.mainLoopModel,
),
),
),
maybe('budget_usd', async () =>
Promise.resolve(
getMaxBudgetUsdAttachment(toolUseContext.options.maxBudgetUsd),
),
),
maybe('output_token_usage', async () =>
Promise.resolve(getOutputTokenUsageAttachment()),
),
maybe('verify_plan_reminder', async () =>
getVerifyPlanReminderAttachment(messages, toolUseContext),
),
]
: []
// Process thread and main thread attachments in parallel (no dependencies between them)
const [threadAttachmentResults, mainThreadAttachmentResults] =
await Promise.all([
Promise.all(allThreadAttachments),
Promise.all(mainThreadAttachments),
])
clearTimeout(timeoutId)
// Defensive: a getter leaking [undefined] crashes .map(a => a.type) below.
return [
...userAttachmentResults.flat(),
...threadAttachmentResults.flat(),