-
Notifications
You must be signed in to change notification settings - Fork 15.9k
Expand file tree
/
Copy pathBashTool.tsx
More file actions
1472 lines (1345 loc) · 46.7 KB
/
BashTool.tsx
File metadata and controls
1472 lines (1345 loc) · 46.7 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 { ToolResultBlockParam } from '@anthropic-ai/sdk/resources/index.mjs'
import {
copyFile,
stat as fsStat,
truncate as fsTruncate,
link,
} from 'fs/promises'
import * as React from 'react'
import type { CanUseToolFn } from 'src/hooks/useCanUseTool.js'
import type { AppState } from 'src/state/AppState.js'
import { z } from 'zod/v4'
import { getKairosActive } from 'src/bootstrap/state.js'
import { TOOL_SUMMARY_MAX_LENGTH } from 'src/constants/toolLimits.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import { notifyVscodeFileUpdated } from 'src/services/mcp/vscodeSdkMcp.js'
import type {
SetToolJSXFn,
ToolCallProgress,
ToolUseContext,
ValidationResult,
} from 'src/Tool.js'
import { buildTool, type ToolDef } from 'src/Tool.js'
import {
backgroundExistingForegroundTask,
markTaskNotified,
registerForeground,
spawnShellTask,
unregisterForeground,
} from 'src/tasks/LocalShellTask/LocalShellTask.js'
import type { AgentId } from 'src/types/ids.js'
import type { AssistantMessage } from 'src/types/message.js'
import { parseForSecurity } from 'src/utils/bash/ast.js'
import {
splitCommand_DEPRECATED,
splitCommandWithOperators,
} from 'src/utils/bash/commands.js'
import { extractClaudeCodeHints } from 'src/utils/claudeCodeHints.js'
import { detectCodeIndexingFromCommand } from 'src/utils/codeIndexing.js'
import { isEnvTruthy } from 'src/utils/envUtils.js'
import { isENOENT, ShellError } from 'src/utils/errors.js'
import {
detectFileEncoding,
detectLineEndings,
getFileModificationTime,
writeTextContent,
} from 'src/utils/file.js'
import {
fileHistoryEnabled,
fileHistoryTrackEdit,
} from 'src/utils/fileHistory.js'
import { truncate } from 'src/utils/format.js'
import { getFsImplementation } from 'src/utils/fsOperations.js'
import { lazySchema } from 'src/utils/lazySchema.js'
import { expandPath } from 'src/utils/path.js'
import type { PermissionResult } from 'src/utils/permissions/PermissionResult.js'
import { maybeRecordPluginHint } from 'src/utils/plugins/hintRecommendation.js'
import { exec } from 'src/utils/Shell.js'
import type { ExecResult } from 'src/utils/ShellCommand.js'
import { SandboxManager } from 'src/utils/sandbox/sandbox-adapter.js'
import { semanticBoolean } from 'src/utils/semanticBoolean.js'
import { semanticNumber } from 'src/utils/semanticNumber.js'
import { EndTruncatingAccumulator } from 'src/utils/stringUtils.js'
import { getTaskOutputPath } from 'src/utils/task/diskOutput.js'
import { TaskOutput } from 'src/utils/task/TaskOutput.js'
import { isOutputLineTruncated } from 'src/utils/terminal.js'
import {
buildLargeToolResultMessage,
ensureToolResultsDir,
generatePreview,
getToolResultPath,
PREVIEW_SIZE_BYTES,
} from 'src/utils/toolResultStorage.js'
import { userFacingName as fileEditUserFacingName } from '../FileEditTool/UI.js'
import { trackGitOperations } from '../shared/gitOperationTracking.js'
import {
bashToolHasPermission,
commandHasAnyCd,
matchWildcardPattern,
permissionRuleExtractPrefix,
} from './bashPermissions.js'
import { interpretCommandResult } from './commandSemantics.js'
import {
getDefaultTimeoutMs,
getMaxTimeoutMs,
getSimplePrompt,
} from './prompt.js'
import { checkReadOnlyConstraints } from './readOnlyValidation.js'
import { parseSedEditCommand } from './sedEditParser.js'
import { shouldUseSandbox } from './shouldUseSandbox.js'
import { BASH_TOOL_NAME } from './toolName.js'
import {
BackgroundHint,
renderToolResultMessage,
renderToolUseErrorMessage,
renderToolUseMessage,
renderToolUseProgressMessage,
renderToolUseQueuedMessage,
} from './UI.js'
import {
buildImageToolResult,
isImageOutput,
resetCwdIfOutsideProject,
resizeShellImageOutput,
stdErrAppendShellResetMessage,
stripEmptyLines,
} from './utils.js'
const EOL = '\n'
// Progress display constants
const PROGRESS_THRESHOLD_MS = 2000 // Show progress after 2 seconds
// In assistant mode, blocking bash auto-backgrounds after this many ms in the main agent
const ASSISTANT_BLOCKING_BUDGET_MS = 15_000
// Search commands for collapsible display (grep, find, etc.)
const BASH_SEARCH_COMMANDS = new Set([
'find',
'grep',
'rg',
'ag',
'ack',
'locate',
'which',
'whereis',
])
// Read/view commands for collapsible display (cat, head, etc.)
const BASH_READ_COMMANDS = new Set([
'cat',
'head',
'tail',
'less',
'more',
// Analysis commands
'wc',
'stat',
'file',
'strings',
// Data processing — commonly used to parse/transform file content in pipes
'jq',
'awk',
'cut',
'sort',
'uniq',
'tr',
])
// Directory-listing commands for collapsible display (ls, tree, du).
// Split from BASH_READ_COMMANDS so the summary says "Listed N directories"
// instead of the misleading "Read N files".
const BASH_LIST_COMMANDS = new Set(['ls', 'tree', 'du'])
// Commands that are semantic-neutral in any position — pure output/status commands
// that don't change the read/search nature of the overall pipeline.
// e.g. `ls dir && echo "---" && ls dir2` is still a read-only compound command.
const BASH_SEMANTIC_NEUTRAL_COMMANDS = new Set([
'echo',
'printf',
'true',
'false',
':', // bash no-op
])
// Commands that typically produce no stdout on success
const BASH_SILENT_COMMANDS = new Set([
'mv',
'cp',
'rm',
'mkdir',
'rmdir',
'chmod',
'chown',
'chgrp',
'touch',
'ln',
'cd',
'export',
'unset',
'wait',
])
/**
* Checks if a bash command is a search or read operation.
* Used to determine if the command should be collapsed in the UI.
* Returns an object indicating whether it's a search or read operation.
*
* For pipelines (e.g., `cat file | bq`), ALL parts must be search/read commands
* for the whole command to be considered collapsible.
*
* Semantic-neutral commands (echo, printf, true, false, :) are skipped in any
* position, as they're pure output/status commands that don't affect the read/search
* nature of the pipeline (e.g. `ls dir && echo "---" && ls dir2` is still a read).
*/
export function isSearchOrReadBashCommand(command: string): {
isSearch: boolean
isRead: boolean
isList: boolean
} {
let partsWithOperators: string[]
try {
partsWithOperators = splitCommandWithOperators(command)
} catch {
// If we can't parse the command due to malformed syntax,
// it's not a search/read command
return { isSearch: false, isRead: false, isList: false }
}
if (partsWithOperators.length === 0) {
return { isSearch: false, isRead: false, isList: false }
}
let hasSearch = false
let hasRead = false
let hasList = false
let hasNonNeutralCommand = false
let skipNextAsRedirectTarget = false
for (const part of partsWithOperators) {
if (skipNextAsRedirectTarget) {
skipNextAsRedirectTarget = false
continue
}
if (part === '>' || part === '>>' || part === '>&') {
skipNextAsRedirectTarget = true
continue
}
if (part === '||' || part === '&&' || part === '|' || part === ';') {
continue
}
const baseCommand = part.trim().split(/\s+/)[0]
if (!baseCommand) {
continue
}
if (BASH_SEMANTIC_NEUTRAL_COMMANDS.has(baseCommand)) {
continue
}
hasNonNeutralCommand = true
const isPartSearch = BASH_SEARCH_COMMANDS.has(baseCommand)
const isPartRead = BASH_READ_COMMANDS.has(baseCommand)
const isPartList = BASH_LIST_COMMANDS.has(baseCommand)
if (!isPartSearch && !isPartRead && !isPartList) {
return { isSearch: false, isRead: false, isList: false }
}
if (isPartSearch) hasSearch = true
if (isPartRead) hasRead = true
if (isPartList) hasList = true
}
// Only neutral commands (e.g., just "echo foo") -- not collapsible
if (!hasNonNeutralCommand) {
return { isSearch: false, isRead: false, isList: false }
}
return { isSearch: hasSearch, isRead: hasRead, isList: hasList }
}
/**
* Checks if a bash command is expected to produce no stdout on success.
* Used to show "Done" instead of "(No output)" in the UI.
*/
function isSilentBashCommand(command: string): boolean {
let partsWithOperators: string[]
try {
partsWithOperators = splitCommandWithOperators(command)
} catch {
return false
}
if (partsWithOperators.length === 0) {
return false
}
let hasNonFallbackCommand = false
let lastOperator: string | null = null
let skipNextAsRedirectTarget = false
for (const part of partsWithOperators) {
if (skipNextAsRedirectTarget) {
skipNextAsRedirectTarget = false
continue
}
if (part === '>' || part === '>>' || part === '>&') {
skipNextAsRedirectTarget = true
continue
}
if (part === '||' || part === '&&' || part === '|' || part === ';') {
lastOperator = part
continue
}
const baseCommand = part.trim().split(/\s+/)[0]
if (!baseCommand) {
continue
}
if (
lastOperator === '||' &&
BASH_SEMANTIC_NEUTRAL_COMMANDS.has(baseCommand)
) {
continue
}
hasNonFallbackCommand = true
if (!BASH_SILENT_COMMANDS.has(baseCommand)) {
return false
}
}
return hasNonFallbackCommand
}
// Commands that should not be auto-backgrounded
const DISALLOWED_AUTO_BACKGROUND_COMMANDS = [
'sleep', // Sleep should run in foreground unless explicitly backgrounded by user
]
// Check if background tasks are disabled at module load time
const isBackgroundTasksDisabled =
// eslint-disable-next-line custom-rules/no-process-env-top-level -- Intentional: schema must be defined at module load
isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS)
const fullInputSchema = lazySchema(() =>
z.strictObject({
command: z.string().describe('The command to execute'),
timeout: semanticNumber(z.number().optional()).describe(
`Optional timeout in milliseconds (max ${getMaxTimeoutMs()})`,
),
description: z
.string()
.optional()
.describe(`Clear, concise description of what this command does in active voice. Never use words like "complex" or "risk" in the description - just describe what it does.
For simple commands (git, npm, standard CLI tools), keep it brief (5-10 words):
- ls → "List files in current directory"
- git status → "Show working tree status"
- npm install → "Install package dependencies"
For commands that are harder to parse at a glance (piped commands, obscure flags, etc.), add enough context to clarify what it does:
- find . -name "*.tmp" -exec rm {} \\; → "Find and delete all .tmp files recursively"
- git reset --hard origin/main → "Discard all local changes and match remote main"
- curl -s url | jq '.data[]' → "Fetch JSON from URL and extract data array elements"`),
run_in_background: semanticBoolean(z.boolean().optional()).describe(
`Set to true to run this command in the background. Use Read to read the output later.`,
),
dangerouslyDisableSandbox: semanticBoolean(z.boolean().optional()).describe(
'Set this to true to dangerously override sandbox mode and run commands without sandboxing.',
),
_simulatedSedEdit: z
.object({
filePath: z.string(),
newContent: z.string(),
})
.optional()
.describe('Internal: pre-computed sed edit result from preview'),
}),
)
// Always omit _simulatedSedEdit from the model-facing schema. It is an internal-only
// field set by SedEditPermissionRequest after the user approves a sed edit preview.
// Exposing it in the schema would let the model bypass permission checks and the
// sandbox by pairing an innocuous command with an arbitrary file write.
// Also conditionally remove run_in_background when background tasks are disabled.
const inputSchema = lazySchema(() =>
isBackgroundTasksDisabled
? fullInputSchema().omit({
run_in_background: true,
_simulatedSedEdit: true,
})
: fullInputSchema().omit({ _simulatedSedEdit: true }),
)
type InputSchema = ReturnType<typeof inputSchema>
// Use fullInputSchema for the type to always include run_in_background
// (even when it's omitted from the schema, the code needs to handle it)
export type BashToolInput = z.infer<ReturnType<typeof fullInputSchema>>
const COMMON_BACKGROUND_COMMANDS = [
'npm',
'yarn',
'pnpm',
'node',
'python',
'python3',
'go',
'cargo',
'make',
'docker',
'terraform',
'webpack',
'vite',
'jest',
'pytest',
'curl',
'wget',
'build',
'test',
'serve',
'watch',
'dev',
] as const
function getCommandTypeForLogging(
command: string,
): AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS {
const parts = splitCommand_DEPRECATED(command)
if (parts.length === 0)
return 'other' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
// Check each part of the command to see if any match common background commands
for (const part of parts) {
const baseCommand = part.split(' ')[0] || ''
if (
COMMON_BACKGROUND_COMMANDS.includes(
baseCommand as (typeof COMMON_BACKGROUND_COMMANDS)[number],
)
) {
return baseCommand as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
}
}
return 'other' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
}
const outputSchema = lazySchema(() =>
z.object({
stdout: z.string().describe('The standard output of the command'),
stderr: z.string().describe('The standard error output of the command'),
rawOutputPath: z
.string()
.optional()
.describe('Path to raw output file for large MCP tool outputs'),
interrupted: z.boolean().describe('Whether the command was interrupted'),
isImage: z
.boolean()
.optional()
.describe('Flag to indicate if stdout contains image data'),
backgroundTaskId: z
.string()
.optional()
.describe(
'ID of the background task if command is running in background',
),
backgroundedByUser: z
.boolean()
.optional()
.describe(
'True if the user manually backgrounded the command with Ctrl+B',
),
assistantAutoBackgrounded: z
.boolean()
.optional()
.describe(
'True if assistant-mode auto-backgrounded a long-running blocking command',
),
dangerouslyDisableSandbox: z
.boolean()
.optional()
.describe('Flag to indicate if sandbox mode was overridden'),
returnCodeInterpretation: z
.string()
.optional()
.describe(
'Semantic interpretation for non-error exit codes with special meaning',
),
noOutputExpected: z
.boolean()
.optional()
.describe(
'Whether the command is expected to produce no output on success',
),
structuredContent: z
.array(z.any())
.optional()
.describe('Structured content blocks'),
persistedOutputPath: z
.string()
.optional()
.describe(
'Path to the persisted full output in tool-results dir (set when output is too large for inline)',
),
persistedOutputSize: z
.number()
.optional()
.describe(
'Total size of the output in bytes (set when output is too large for inline)',
),
}),
)
type OutputSchema = ReturnType<typeof outputSchema>
export type Out = z.infer<OutputSchema>
// Re-export BashProgress from centralized types to break import cycles
export type { BashProgress } from 'src/types/tools.js'
import type { BashProgress } from 'src/types/tools.js'
/**
* Checks if a command is allowed to be automatically backgrounded
* @param command The command to check
* @returns false for commands that should not be auto-backgrounded (like sleep)
*/
function isAutobackgroundingAllowed(command: string): boolean {
const parts = splitCommand_DEPRECATED(command)
if (parts.length === 0) return true
// Get the first part which should be the base command
const baseCommand = parts[0]?.trim()
if (!baseCommand) return true
return !DISALLOWED_AUTO_BACKGROUND_COMMANDS.includes(baseCommand)
}
/**
* Detect standalone or leading `sleep N` patterns that should use Monitor
* instead. Catches `sleep 5`, `sleep 5 && check`, `sleep 5; check` — but
* not sleep inside pipelines, subshells, or scripts (those are fine).
*/
export function detectBlockedSleepPattern(command: string): string | null {
const parts = splitCommand_DEPRECATED(command)
if (parts.length === 0) return null
const first = parts[0]?.trim() ?? ''
// Bare `sleep N` or `sleep N.N` as the first subcommand.
// Float durations (sleep 0.5) are allowed — those are legit pacing, not polls.
const m = /^sleep\s+(\d+)\s*$/.exec(first)
if (!m) return null
const secs = parseInt(m[1]!, 10)
if (secs < 2) return null // sub-2s sleeps are fine (rate limiting, pacing)
// `sleep N` alone → "what are you waiting for?"
// `sleep N && check` → "use Monitor { command: check }"
const rest = parts.slice(1).join(' ').trim()
return rest
? `sleep ${secs} followed by: ${rest}`
: `standalone sleep ${secs}`
}
/**
* Checks if a command contains tools that shouldn't run in sandbox
* This includes:
* - Dynamic config-based disabled commands and substrings (tengu_sandbox_disabled_commands)
* - User-configured commands from settings.json (sandbox.excludedCommands)
*
* User-configured commands support the same pattern syntax as permission rules:
* - Exact matches: "npm run lint"
* - Prefix patterns: "npm run test:*"
*/
type SimulatedSedEditResult = {
data: Out
}
type SimulatedSedEditContext = Pick<
ToolUseContext,
'readFileState' | 'updateFileHistoryState'
>
/**
* Applies a simulated sed edit directly instead of running sed.
* This is used by the permission dialog to ensure what the user previews
* is exactly what gets written to the file.
*/
async function applySedEdit(
simulatedEdit: { filePath: string; newContent: string },
toolUseContext: SimulatedSedEditContext,
parentMessage?: AssistantMessage,
): Promise<SimulatedSedEditResult> {
const { filePath, newContent } = simulatedEdit
const absoluteFilePath = expandPath(filePath)
const fs = getFsImplementation()
// Read original content for VS Code notification
const encoding = detectFileEncoding(absoluteFilePath)
let originalContent: string
try {
originalContent = await fs.readFile(absoluteFilePath, { encoding })
} catch (e) {
if (isENOENT(e)) {
return {
data: {
stdout: '',
stderr: `sed: ${filePath}: No such file or directory\nExit code 1`,
interrupted: false,
},
}
}
throw e
}
// Track file history before making changes (for undo support)
if (fileHistoryEnabled() && parentMessage) {
await fileHistoryTrackEdit(
toolUseContext.updateFileHistoryState,
absoluteFilePath,
parentMessage.uuid,
)
}
// Detect line endings and write new content
const endings = detectLineEndings(absoluteFilePath)
writeTextContent(absoluteFilePath, newContent, encoding, endings)
// Notify VS Code about the file change
notifyVscodeFileUpdated(absoluteFilePath, originalContent, newContent)
// Update read timestamp to invalidate stale writes
toolUseContext.readFileState.set(absoluteFilePath, {
content: newContent,
timestamp: getFileModificationTime(absoluteFilePath),
offset: undefined,
limit: undefined,
})
// Return success result matching sed output format (sed produces no output on success)
return {
data: {
stdout: '',
stderr: '',
interrupted: false,
},
}
}
export const BashTool = buildTool({
name: BASH_TOOL_NAME,
searchHint: 'execute shell commands',
// 30K chars - tool result persistence threshold
maxResultSizeChars: 30_000,
strict: true,
async description({ description }) {
return description || 'Run shell command'
},
async prompt() {
return getSimplePrompt()
},
isConcurrencySafe(input) {
return this.isReadOnly?.(input) ?? false
},
isReadOnly(input) {
const compoundCommandHasCd = commandHasAnyCd(input.command)
const result = checkReadOnlyConstraints(input, compoundCommandHasCd)
return result.behavior === 'allow'
},
toAutoClassifierInput(input) {
return input.command
},
async preparePermissionMatcher({ command }) {
// Hook `if` filtering is "no match → skip hook" (deny-like semantics), so
// compound commands must fire the hook if ANY subcommand matches. Without
// splitting, `ls && git push` would bypass a `Bash(git *)` security hook.
const parsed = await parseForSecurity(command)
if (parsed.kind !== 'simple') {
// parse-unavailable / too-complex: fail safe by running the hook.
return () => true
}
// Match on argv (strips leading VAR=val) so `FOO=bar git push` still
// matches `Bash(git *)`.
const subcommands = parsed.commands.map(c => c.argv.join(' '))
return pattern => {
const prefix = permissionRuleExtractPrefix(pattern)
return subcommands.some(cmd => {
if (prefix !== null) {
return cmd === prefix || cmd.startsWith(`${prefix} `)
}
return matchWildcardPattern(pattern, cmd)
})
}
},
isSearchOrReadCommand(input) {
const parsed = inputSchema().safeParse(input)
if (!parsed.success)
return { isSearch: false, isRead: false, isList: false }
return isSearchOrReadBashCommand(parsed.data.command)
},
get inputSchema(): InputSchema {
return inputSchema()
},
get outputSchema(): OutputSchema {
return outputSchema()
},
userFacingName(input) {
if (!input) {
return 'Bash'
}
// Render sed in-place edits as file edits
if (input.command) {
const sedInfo = parseSedEditCommand(input.command)
if (sedInfo) {
return fileEditUserFacingName({
file_path: sedInfo.filePath,
old_string: 'x',
})
}
}
// Env var FIRST: shouldUseSandbox → splitCommand_DEPRECATED → shell-quote's
// `new RegExp` per call. userFacingName runs per-render for every bash
// message in history; with ~50 msgs + one slow-to-tokenize command, this
// exceeds the shimmer tick → transition abort → infinite retry (#21605).
return isEnvTruthy(process.env.CLAUDE_CODE_BASH_SANDBOX_SHOW_INDICATOR) &&
shouldUseSandbox(input)
? 'SandboxedBash'
: 'Bash'
},
getToolUseSummary(input) {
if (!input?.command) {
return null
}
const { command, description } = input
if (description) {
return description
}
return truncate(command, TOOL_SUMMARY_MAX_LENGTH)
},
getActivityDescription(input) {
if (!input?.command) {
return 'Running command'
}
const desc =
input.description ?? truncate(input.command, TOOL_SUMMARY_MAX_LENGTH)
return `Running ${desc}`
},
async validateInput(input: BashToolInput): Promise<ValidationResult> {
if (
feature('MONITOR_TOOL') &&
!isBackgroundTasksDisabled &&
!input.run_in_background
) {
const sleepPattern = detectBlockedSleepPattern(input.command)
if (sleepPattern !== null) {
return {
result: false,
message: `Blocked: ${sleepPattern}. Run blocking commands in the background with run_in_background: true — you'll get a completion notification when done. For streaming events (watching logs, polling APIs), use the Monitor tool. If you genuinely need a delay (rate limiting, deliberate pacing), keep it under 2 seconds.`,
errorCode: 10,
}
}
}
return { result: true }
},
async checkPermissions(input, context): Promise<PermissionResult> {
return bashToolHasPermission(input, context)
},
renderToolUseMessage,
renderToolUseProgressMessage,
renderToolUseQueuedMessage,
renderToolResultMessage,
// BashToolResultMessage shows <OutputLine content={stdout}> + stderr.
// UI never shows persistedOutputPath wrapper, backgroundInfo — those are
// model-facing (mapToolResult... below).
extractSearchText({ stdout, stderr }) {
return stderr ? `${stdout}\n${stderr}` : stdout
},
mapToolResultToToolResultBlockParam(
{
interrupted,
stdout,
stderr,
isImage,
backgroundTaskId,
backgroundedByUser,
assistantAutoBackgrounded,
structuredContent,
persistedOutputPath,
persistedOutputSize,
},
toolUseID,
): ToolResultBlockParam {
// Handle structured content
if (structuredContent && structuredContent.length > 0) {
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: structuredContent,
}
}
// For image data, format as image content block for Claude
if (isImage) {
const block = buildImageToolResult(stdout, toolUseID)
if (block) return block
}
let processedStdout = stdout
if (stdout) {
// Replace any leading newlines or lines with only whitespace
processedStdout = stdout.replace(/^(\s*\n)+/, '')
// Still trim the end as before
processedStdout = processedStdout.trimEnd()
}
// For large output that was persisted to disk, build <persisted-output>
// message for the model. The UI never sees this — it uses data.stdout.
if (persistedOutputPath) {
const preview = generatePreview(processedStdout, PREVIEW_SIZE_BYTES)
processedStdout = buildLargeToolResultMessage({
filepath: persistedOutputPath,
originalSize: persistedOutputSize ?? 0,
isJson: false,
preview: preview.preview,
hasMore: preview.hasMore,
})
}
let errorMessage = stderr.trim()
if (interrupted) {
if (stderr) errorMessage += EOL
errorMessage += '<error>Command was aborted before completion</error>'
}
let backgroundInfo = ''
if (backgroundTaskId) {
const outputPath = getTaskOutputPath(backgroundTaskId)
if (assistantAutoBackgrounded) {
backgroundInfo = `Command exceeded the assistant-mode blocking budget (${ASSISTANT_BLOCKING_BUDGET_MS / 1000}s) and was moved to the background with ID: ${backgroundTaskId}. It is still running — you will be notified when it completes. Output is being written to: ${outputPath}. In assistant mode, delegate long-running work to a subagent or use run_in_background to keep this conversation responsive.`
} else if (backgroundedByUser) {
backgroundInfo = `Command was manually backgrounded by user with ID: ${backgroundTaskId}. Output is being written to: ${outputPath}`
} else {
backgroundInfo = `Command running in background with ID: ${backgroundTaskId}. Output is being written to: ${outputPath}`
}
}
return {
tool_use_id: toolUseID,
type: 'tool_result',
content: [processedStdout, errorMessage, backgroundInfo]
.filter(Boolean)
.join('\n'),
is_error: interrupted,
}
},
async call(
input: BashToolInput,
toolUseContext,
_canUseTool?: CanUseToolFn,
parentMessage?: AssistantMessage,
onProgress?: ToolCallProgress<BashProgress>,
) {
// Handle simulated sed edit - apply directly instead of running sed
// This ensures what the user previewed is exactly what gets written
if (input._simulatedSedEdit) {
return applySedEdit(
input._simulatedSedEdit,
toolUseContext,
parentMessage,
)
}
const { abortController, getAppState, setAppState, setToolJSX } =
toolUseContext
const stdoutAccumulator = new EndTruncatingAccumulator()
let stderrForShellReset = ''
let interpretationResult:
| ReturnType<typeof interpretCommandResult>
| undefined
let progressCounter = 0
let wasInterrupted = false
let result: ExecResult
const isMainThread = !toolUseContext.agentId
const preventCwdChanges = !isMainThread
try {
// Use the new async generator version of runShellCommand
const commandGenerator = runShellCommand({
input,
abortController,
// Use the always-shared task channel so async agents' background
// bash tasks are actually registered (and killable on agent exit).
setAppState: toolUseContext.setAppStateForTasks ?? setAppState,
setToolJSX,
preventCwdChanges,
isMainThread,
toolUseId: toolUseContext.toolUseId,
agentId: toolUseContext.agentId,
})
// Consume the generator and capture the return value
let generatorResult
do {
generatorResult = await commandGenerator.next()
if (!generatorResult.done && onProgress) {
const progress = generatorResult.value
onProgress({
toolUseID: `bash-progress-${progressCounter++}`,
data: {
type: 'bash_progress',
output: progress.output,
fullOutput: progress.fullOutput,
elapsedTimeSeconds: progress.elapsedTimeSeconds,
totalLines: progress.totalLines,
totalBytes: progress.totalBytes,
taskId: progress.taskId,
timeoutMs: progress.timeoutMs,
},
})
}
} while (!generatorResult.done)
// Get the final result from the generator's return value
result = generatorResult.value
trackGitOperations(input.command, result.code, result.stdout)
const isInterrupt =
result.interrupted && abortController.signal.reason === 'interrupt'
// stderr is interleaved in stdout (merged fd) — result.stdout has both
stdoutAccumulator.append((result.stdout || '').trimEnd() + EOL)
// Interpret the command result using semantic rules
interpretationResult = interpretCommandResult(
input.command,
result.code,
result.stdout || '',
'',
)
// Check for git index.lock error (stderr is in stdout now)
if (
result.stdout &&
result.stdout.includes(".git/index.lock': File exists")
) {
logEvent('tengu_git_index_lock_error', {})
}
if (interpretationResult.isError && !isInterrupt) {
// Only add exit code if it's actually an error
if (result.code !== 0) {
stdoutAccumulator.append(`Exit code ${result.code}`)
}
}
if (!preventCwdChanges) {
const appState = getAppState()
if (resetCwdIfOutsideProject(appState.toolPermissionContext)) {
stderrForShellReset = stdErrAppendShellResetMessage('')
}
}
// Annotate output with sandbox violations if any (stderr is in stdout)
const outputWithSbFailures =
SandboxManager.annotateStderrWithSandboxFailures(
input.command,
result.stdout || '',
)
if (result.preSpawnError) {
throw new Error(result.preSpawnError)
}
if (interpretationResult.isError && !isInterrupt) {
// stderr is merged into stdout (merged fd); outputWithSbFailures
// already has the full output. Pass '' for stdout to avoid
// duplication in getErrorParts() and processBashCommand.
throw new ShellError(
'',
outputWithSbFailures,
result.code,
result.interrupted,
)
}
wasInterrupted = result.interrupted
} finally {
if (setToolJSX) setToolJSX(null)
}
// Get final string from accumulator
const stdout = stdoutAccumulator.toString()
// Large output: the file on disk has more than getMaxOutputLength() bytes.
// stdout already contains the first chunk (from getStdout()). Copy the
// output file to the tool-results dir so the model can read it via
// FileRead. If > 64 MB, truncate after copying.
const MAX_PERSISTED_SIZE = 64 * 1024 * 1024
let persistedOutputPath: string | undefined
let persistedOutputSize: number | undefined
if (result.outputFilePath && result.outputTaskId) {
try {
const fileStat = await fsStat(result.outputFilePath)
persistedOutputSize = fileStat.size
await ensureToolResultsDir()
const dest = getToolResultPath(result.outputTaskId, false)
if (fileStat.size > MAX_PERSISTED_SIZE) {