forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermissions.ts
More file actions
1486 lines (1390 loc) · 51 KB
/
Copy pathpermissions.ts
File metadata and controls
1486 lines (1390 loc) · 51 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 { APIUserAbortError } from '@anthropic-ai/sdk'
import type { CanUseToolFn } from '../../hooks/useCanUseTool.js'
import {
getToolNameForPermissionCheck,
mcpInfoFromString,
} from '../../services/mcp/mcpStringUtils.js'
import type { Tool, ToolPermissionContext, ToolUseContext } from '../../Tool.js'
import { AGENT_TOOL_NAME } from '../../tools/AgentTool/constants.js'
import { shouldUseSandbox } from '../../tools/BashTool/shouldUseSandbox.js'
import { BASH_TOOL_NAME } from '../../tools/BashTool/toolName.js'
import { POWERSHELL_TOOL_NAME } from '../../tools/PowerShellTool/toolName.js'
import { REPL_TOOL_NAME } from '../../tools/REPLTool/constants.js'
import type { AssistantMessage } from '../../types/message.js'
import { extractOutputRedirections } from '../bash/commands.js'
import { logForDebugging } from '../debug.js'
import { AbortError, toError } from '../errors.js'
import { logError } from '../log.js'
import { SandboxManager } from '../sandbox/sandbox-adapter.js'
import {
getSettingSourceDisplayNameLowercase,
SETTING_SOURCES,
} from '../settings/constants.js'
import { plural } from '../stringUtils.js'
import { permissionModeTitle } from './PermissionMode.js'
import type {
PermissionAskDecision,
PermissionDecision,
PermissionDecisionReason,
PermissionDenyDecision,
PermissionResult,
} from './PermissionResult.js'
import type {
PermissionBehavior,
PermissionRule,
PermissionRuleSource,
PermissionRuleValue,
} from './PermissionRule.js'
import {
applyPermissionUpdate,
applyPermissionUpdates,
persistPermissionUpdates,
} from './PermissionUpdate.js'
import type {
PermissionUpdate,
PermissionUpdateDestination,
} from './PermissionUpdateSchema.js'
import {
permissionRuleValueFromString,
permissionRuleValueToString,
} from './permissionRuleParser.js'
import {
deletePermissionRuleFromSettings,
type PermissionRuleFromEditableSettings,
shouldAllowManagedPermissionRulesOnly,
} from './permissionsLoader.js'
/* eslint-disable @typescript-eslint/no-require-imports */
const classifierDecisionModule = feature('TRANSCRIPT_CLASSIFIER')
? (require('./classifierDecision.js') as typeof import('./classifierDecision.js'))
: null
const autoModeStateModule = feature('TRANSCRIPT_CLASSIFIER')
? (require('./autoModeState.js') as typeof import('./autoModeState.js'))
: null
import {
addToTurnClassifierDuration,
getTotalCacheCreationInputTokens,
getTotalCacheReadInputTokens,
getTotalInputTokens,
getTotalOutputTokens,
} from '../../bootstrap/state.js'
import { getFeatureValue_CACHED_WITH_REFRESH } from '../../services/analytics/growthbook.js'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from '../../services/analytics/index.js'
import { sanitizeToolNameForAnalytics } from '../../services/analytics/metadata.js'
import {
clearClassifierChecking,
setClassifierChecking,
} from '../classifierApprovals.js'
import { isInProtectedNamespace } from '../envUtils.js'
import { executePermissionRequestHooks } from '../hooks.js'
import {
AUTO_REJECT_MESSAGE,
buildClassifierUnavailableMessage,
buildYoloRejectionMessage,
DONT_ASK_REJECT_MESSAGE,
} from '../messages.js'
import { calculateCostFromTokens } from '../modelCost.js'
/* eslint-enable @typescript-eslint/no-require-imports */
import { jsonStringify } from '../slowOperations.js'
import {
createDenialTrackingState,
DENIAL_LIMITS,
type DenialTrackingState,
recordDenial,
recordSuccess,
shouldFallbackToPrompting,
} from './denialTracking.js'
import {
classifyYoloAction,
formatActionForClassifier,
} from './yoloClassifier.js'
const CLASSIFIER_FAIL_CLOSED_REFRESH_MS = 30 * 60 * 1000 // 30 minutes
const PERMISSION_RULE_SOURCES = [
...SETTING_SOURCES,
'cliArg',
'command',
'session',
] as const satisfies readonly PermissionRuleSource[]
export function permissionRuleSourceDisplayString(
source: PermissionRuleSource,
): string {
return getSettingSourceDisplayNameLowercase(source)
}
export function getAllowRules(
context: ToolPermissionContext,
): PermissionRule[] {
return PERMISSION_RULE_SOURCES.flatMap(source =>
(context.alwaysAllowRules[source] || []).map(ruleString => ({
source,
ruleBehavior: 'allow',
ruleValue: permissionRuleValueFromString(ruleString),
})),
)
}
/**
* Creates a permission request message that explain the permission request
*/
export function createPermissionRequestMessage(
toolName: string,
decisionReason?: PermissionDecisionReason,
): string {
// Handle different decision reason types
if (decisionReason) {
if (
(feature('BASH_CLASSIFIER') || feature('TRANSCRIPT_CLASSIFIER')) &&
decisionReason.type === 'classifier'
) {
return `Classifier '${decisionReason.classifier}' requires approval for this ${toolName} command: ${decisionReason.reason}`
}
switch (decisionReason.type) {
case 'hook': {
const hookMessage = decisionReason.reason
? `Hook '${decisionReason.hookName}' blocked this action: ${decisionReason.reason}`
: `Hook '${decisionReason.hookName}' requires approval for this ${toolName} command`
return hookMessage
}
case 'rule': {
const ruleString = permissionRuleValueToString(
decisionReason.rule.ruleValue,
)
const sourceString = permissionRuleSourceDisplayString(
decisionReason.rule.source,
)
return `Permission rule '${ruleString}' from ${sourceString} requires approval for this ${toolName} command`
}
case 'subcommandResults': {
const needsApproval: string[] = []
for (const [cmd, result] of decisionReason.reasons) {
if (result.behavior === 'ask' || result.behavior === 'passthrough') {
// Strip output redirections for display to avoid showing filenames as commands
// Only do this for Bash tool to avoid affecting other tools
if (toolName === 'Bash') {
const { commandWithoutRedirections, redirections } =
extractOutputRedirections(cmd)
// Only use stripped version if there were actual redirections
const displayCmd =
redirections.length > 0 ? commandWithoutRedirections : cmd
needsApproval.push(displayCmd)
} else {
needsApproval.push(cmd)
}
}
}
if (needsApproval.length > 0) {
const n = needsApproval.length
return `This ${toolName} command contains multiple operations. The following ${plural(n, 'part')} ${plural(n, 'requires', 'require')} approval: ${needsApproval.join(', ')}`
}
return `This ${toolName} command contains multiple operations that require approval`
}
case 'permissionPromptTool':
return `Tool '${decisionReason.permissionPromptToolName}' requires approval for this ${toolName} command`
case 'sandboxOverride':
return 'Run outside of the sandbox'
case 'workingDir':
return decisionReason.reason
case 'safetyCheck':
case 'other':
return decisionReason.reason
case 'mode': {
const modeTitle = permissionModeTitle(decisionReason.mode)
return `Current permission mode (${modeTitle}) requires approval for this ${toolName} command`
}
case 'asyncAgent':
return decisionReason.reason
}
}
// Default message without listing allowed commands
const message = `Claude requested permissions to use ${toolName}, but you haven't granted it yet.`
return message
}
export function getDenyRules(context: ToolPermissionContext): PermissionRule[] {
return PERMISSION_RULE_SOURCES.flatMap(source =>
(context.alwaysDenyRules[source] || []).map(ruleString => ({
source,
ruleBehavior: 'deny',
ruleValue: permissionRuleValueFromString(ruleString),
})),
)
}
export function getAskRules(context: ToolPermissionContext): PermissionRule[] {
return PERMISSION_RULE_SOURCES.flatMap(source =>
(context.alwaysAskRules[source] || []).map(ruleString => ({
source,
ruleBehavior: 'ask',
ruleValue: permissionRuleValueFromString(ruleString),
})),
)
}
/**
* Check if the entire tool matches a rule
* For example, this matches "Bash" but not "Bash(prefix:*)" for BashTool
* This also matches MCP tools with a server name, e.g. the rule "mcp__server1"
*/
function toolMatchesRule(
tool: Pick<Tool, 'name' | 'mcpInfo'>,
rule: PermissionRule,
): boolean {
// Rule must not have content to match the entire tool
if (rule.ruleValue.ruleContent !== undefined) {
return false
}
// MCP tools are matched by their fully qualified mcp__server__tool name. In
// skip-prefix mode (CLAUDE_AGENT_SDK_MCP_NO_PREFIX), MCP tools have unprefixed
// display names (e.g., "Write") that collide with builtin names; rules targeting
// builtins should not match their MCP replacements.
const nameForRuleMatch = getToolNameForPermissionCheck(tool)
// Direct tool name match
if (rule.ruleValue.toolName === nameForRuleMatch) {
return true
}
// MCP server-level permission: rule "mcp__server1" matches tool "mcp__server1__tool1"
// Also supports wildcard: rule "mcp__server1__*" matches all tools from server1
const ruleInfo = mcpInfoFromString(rule.ruleValue.toolName)
const toolInfo = mcpInfoFromString(nameForRuleMatch)
return (
ruleInfo !== null &&
toolInfo !== null &&
(ruleInfo.toolName === undefined || ruleInfo.toolName === '*') &&
ruleInfo.serverName === toolInfo.serverName
)
}
/**
* Check if the entire tool is listed in the always allow rules
* For example, this finds "Bash" but not "Bash(prefix:*)" for BashTool
*/
export function toolAlwaysAllowedRule(
context: ToolPermissionContext,
tool: Pick<Tool, 'name' | 'mcpInfo'>,
): PermissionRule | null {
return (
getAllowRules(context).find(rule => toolMatchesRule(tool, rule)) || null
)
}
/**
* Check if the tool is listed in the always deny rules
*/
export function getDenyRuleForTool(
context: ToolPermissionContext,
tool: Pick<Tool, 'name' | 'mcpInfo'>,
): PermissionRule | null {
return getDenyRules(context).find(rule => toolMatchesRule(tool, rule)) || null
}
/**
* Check if the tool is listed in the always ask rules
*/
export function getAskRuleForTool(
context: ToolPermissionContext,
tool: Pick<Tool, 'name' | 'mcpInfo'>,
): PermissionRule | null {
return getAskRules(context).find(rule => toolMatchesRule(tool, rule)) || null
}
/**
* Check if a specific agent is denied via Agent(agentType) syntax.
* For example, Agent(Explore) would deny the Explore agent.
*/
export function getDenyRuleForAgent(
context: ToolPermissionContext,
agentToolName: string,
agentType: string,
): PermissionRule | null {
return (
getDenyRules(context).find(
rule =>
rule.ruleValue.toolName === agentToolName &&
rule.ruleValue.ruleContent === agentType,
) || null
)
}
/**
* Filter agents to exclude those that are denied via Agent(agentType) syntax.
*/
export function filterDeniedAgents<T extends { agentType: string }>(
agents: T[],
context: ToolPermissionContext,
agentToolName: string,
): T[] {
// Parse deny rules once and collect Agent(x) contents into a Set.
// Previously this called getDenyRuleForAgent per agent, which re-parsed
// every deny rule for every agent (O(agents×rules) parse calls).
const deniedAgentTypes = new Set<string>()
for (const rule of getDenyRules(context)) {
if (
rule.ruleValue.toolName === agentToolName &&
rule.ruleValue.ruleContent !== undefined
) {
deniedAgentTypes.add(rule.ruleValue.ruleContent)
}
}
return agents.filter(agent => !deniedAgentTypes.has(agent.agentType))
}
/**
* Map of rule contents to the associated rule for a given tool.
* e.g. the string key is "prefix:*" from "Bash(prefix:*)" for BashTool
*/
export function getRuleByContentsForTool(
context: ToolPermissionContext,
tool: Tool,
behavior: PermissionBehavior,
): Map<string, PermissionRule> {
return getRuleByContentsForToolName(
context,
getToolNameForPermissionCheck(tool),
behavior,
)
}
// Used to break circular dependency where a Tool calls this function
export function getRuleByContentsForToolName(
context: ToolPermissionContext,
toolName: string,
behavior: PermissionBehavior,
): Map<string, PermissionRule> {
const ruleByContents = new Map<string, PermissionRule>()
let rules: PermissionRule[] = []
switch (behavior) {
case 'allow':
rules = getAllowRules(context)
break
case 'deny':
rules = getDenyRules(context)
break
case 'ask':
rules = getAskRules(context)
break
}
for (const rule of rules) {
if (
rule.ruleValue.toolName === toolName &&
rule.ruleValue.ruleContent !== undefined &&
rule.ruleBehavior === behavior
) {
ruleByContents.set(rule.ruleValue.ruleContent, rule)
}
}
return ruleByContents
}
/**
* Runs PermissionRequest hooks for headless/async agents that cannot show
* permission prompts. This gives hooks an opportunity to allow or deny
* tool use before the fallback auto-deny kicks in.
*
* Returns a PermissionDecision if a hook made a decision, or null if no
* hook provided a decision (caller should proceed to auto-deny).
*/
async function runPermissionRequestHooksForHeadlessAgent(
tool: Tool,
input: { [key: string]: unknown },
toolUseID: string,
context: ToolUseContext,
permissionMode: string | undefined,
suggestions: PermissionUpdate[] | undefined,
): Promise<PermissionDecision | null> {
try {
for await (const hookResult of executePermissionRequestHooks(
tool.name,
toolUseID,
input,
context,
permissionMode,
suggestions,
context.abortController.signal,
)) {
if (!hookResult.permissionRequestResult) {
continue
}
const decision = hookResult.permissionRequestResult
if (decision.behavior === 'allow') {
const finalInput = decision.updatedInput ?? input
// Persist permission updates if provided
if (decision.updatedPermissions?.length) {
persistPermissionUpdates(decision.updatedPermissions)
context.setAppState(prev => ({
...prev,
toolPermissionContext: applyPermissionUpdates(
prev.toolPermissionContext,
decision.updatedPermissions!,
),
}))
}
return {
behavior: 'allow',
updatedInput: finalInput,
decisionReason: {
type: 'hook',
hookName: 'PermissionRequest',
},
}
}
if (decision.behavior === 'deny') {
if (decision.interrupt) {
logForDebugging(
`Hook interrupt: tool=${tool.name} hookMessage=${decision.message}`,
)
context.abortController.abort()
}
return {
behavior: 'deny',
message: decision.message || 'Permission denied by hook',
decisionReason: {
type: 'hook',
hookName: 'PermissionRequest',
reason: decision.message,
},
}
}
}
} catch (error) {
// If hooks fail, fall through to auto-deny rather than crashing
logError(
new Error('PermissionRequest hook failed for headless agent', {
cause: toError(error),
}),
)
}
return null
}
export const hasPermissionsToUseTool: CanUseToolFn = async (
tool,
input,
context,
assistantMessage,
toolUseID,
): Promise<PermissionDecision> => {
const result = await hasPermissionsToUseToolInner(tool, input, context)
// Reset consecutive denials on any allowed tool use in auto mode.
// This ensures that a successful tool use (even one auto-allowed by rules)
// breaks the consecutive denial streak.
if (result.behavior === 'allow') {
const appState = context.getAppState()
if (feature('TRANSCRIPT_CLASSIFIER')) {
const currentDenialState =
context.localDenialTracking ?? appState.denialTracking
if (
appState.toolPermissionContext.mode === 'auto' &&
currentDenialState &&
currentDenialState.consecutiveDenials > 0
) {
const newDenialState = recordSuccess(currentDenialState)
persistDenialState(context, newDenialState)
}
}
return result
}
// Apply dontAsk mode transformation: convert 'ask' to 'deny'
// This is done at the end so it can't be bypassed by early returns
if (result.behavior === 'ask') {
const appState = context.getAppState()
if (appState.toolPermissionContext.mode === 'dontAsk') {
return {
behavior: 'deny',
decisionReason: {
type: 'mode',
mode: 'dontAsk',
},
message: DONT_ASK_REJECT_MESSAGE(tool.name),
}
}
// Apply auto mode: use AI classifier instead of prompting user
// Check this BEFORE shouldAvoidPermissionPrompts so classifiers work in headless mode
if (
feature('TRANSCRIPT_CLASSIFIER') &&
(appState.toolPermissionContext.mode === 'auto' ||
(appState.toolPermissionContext.mode === 'plan' &&
(autoModeStateModule?.isAutoModeActive() ?? false)))
) {
// Non-classifier-approvable safetyCheck decisions stay immune to ALL
// auto-approve paths: the acceptEdits fast-path, the safe-tool allowlist,
// and the classifier. Step 1g only guards bypassPermissions; this guards
// auto. classifierApprovable safetyChecks (sensitive-file paths) fall
// through to the classifier — the fast-paths below naturally don't fire
// because the tool's own checkPermissions still returns 'ask'.
if (
result.decisionReason?.type === 'safetyCheck' &&
!result.decisionReason.classifierApprovable
) {
if (appState.toolPermissionContext.shouldAvoidPermissionPrompts) {
return {
behavior: 'deny',
message: result.message,
decisionReason: {
type: 'asyncAgent',
reason:
'Safety check requires interactive approval and permission prompts are not available in this context',
},
}
}
return result
}
if (tool.requiresUserInteraction?.() && result.behavior === 'ask') {
return result
}
// Use local denial tracking for async subagents (whose setAppState
// is a no-op), otherwise read from appState as before.
const denialState =
context.localDenialTracking ??
appState.denialTracking ??
createDenialTrackingState()
// PowerShell requires explicit user permission in auto mode unless
// POWERSHELL_AUTO_MODE (ant-only build flag) is on. When disabled, this
// guard keeps PS out of the classifier and skips the acceptEdits
// fast-path below. When enabled, PS flows through to the classifier like
// Bash — the classifier prompt gets POWERSHELL_DENY_GUIDANCE appended so
// it recognizes `iex (iwr ...)` as download-and-execute, etc.
// Note: this runs inside the behavior === 'ask' branch, so allow rules
// that fire earlier (step 2b toolAlwaysAllowedRule, PS prefix allow)
// return before reaching here. Allow-rule protection is handled by
// permissionSetup.ts: isOverlyBroadPowerShellAllowRule strips PowerShell(*)
// and isDangerousPowerShellPermission strips iex/pwsh/Start-Process
// prefix rules for ant users and auto mode entry.
if (
tool.name === POWERSHELL_TOOL_NAME &&
!feature('POWERSHELL_AUTO_MODE')
) {
if (appState.toolPermissionContext.shouldAvoidPermissionPrompts) {
return {
behavior: 'deny',
message: 'PowerShell tool requires interactive approval',
decisionReason: {
type: 'asyncAgent',
reason:
'PowerShell tool requires interactive approval and permission prompts are not available in this context',
},
}
}
logForDebugging(
`Skipping auto mode classifier for ${tool.name}: tool requires explicit user permission`,
)
return result
}
// Before running the auto mode classifier, check if acceptEdits mode would
// allow this action. This avoids expensive classifier API calls for safe
// operations like file edits in the working directory.
// Skip for Agent and REPL — their checkPermissions returns 'allow' for
// acceptEdits mode, which would silently bypass the classifier. REPL
// code can contain VM escapes between inner tool calls; the classifier
// must see the glue JavaScript, not just the inner tool calls.
if (
result.behavior === 'ask' &&
tool.name !== AGENT_TOOL_NAME &&
tool.name !== REPL_TOOL_NAME
) {
try {
const parsedInput = tool.inputSchema.parse(input)
const acceptEditsResult = await tool.checkPermissions(parsedInput, {
...context,
getAppState: () => {
const state = context.getAppState()
return {
...state,
toolPermissionContext: {
...state.toolPermissionContext,
mode: 'acceptEdits' as const,
},
}
},
})
if (acceptEditsResult.behavior === 'allow') {
const newDenialState = recordSuccess(denialState)
persistDenialState(context, newDenialState)
logForDebugging(
`Skipping auto mode classifier for ${tool.name}: would be allowed in acceptEdits mode`,
)
logEvent('tengu_auto_mode_decision', {
decision:
'allowed' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
inProtectedNamespace: isInProtectedNamespace(),
// msg_id of the agent completion that produced this tool_use —
// the action at the bottom of the classifier transcript. Joins
// the decision back to the main agent's API response.
agentMsgId: assistantMessage.message
.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
confidence:
'high' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
fastPath:
'acceptEdits' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
behavior: 'allow',
updatedInput: acceptEditsResult.updatedInput ?? input,
decisionReason: {
type: 'mode',
mode: 'auto',
},
}
}
} catch (e) {
if (e instanceof AbortError || e instanceof APIUserAbortError) {
throw e
}
// If the acceptEdits check fails, fall through to the classifier
}
}
// Allowlisted tools are safe and don't need YOLO classification.
// This uses the safe-tool allowlist to skip unnecessary classifier API calls.
if (classifierDecisionModule!.isAutoModeAllowlistedTool(tool.name)) {
const newDenialState = recordSuccess(denialState)
persistDenialState(context, newDenialState)
logForDebugging(
`Skipping auto mode classifier for ${tool.name}: tool is on the safe allowlist`,
)
logEvent('tengu_auto_mode_decision', {
decision:
'allowed' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
inProtectedNamespace: isInProtectedNamespace(),
agentMsgId: assistantMessage.message
.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
confidence:
'high' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
fastPath:
'allowlist' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
})
return {
behavior: 'allow',
updatedInput: input,
decisionReason: {
type: 'mode',
mode: 'auto',
},
}
}
// Run the auto mode classifier
const action = formatActionForClassifier(tool.name, input)
setClassifierChecking(toolUseID)
let classifierResult
try {
classifierResult = await classifyYoloAction(
context.messages,
action,
context.options.tools,
appState.toolPermissionContext,
context.abortController.signal,
)
} finally {
clearClassifierChecking(toolUseID)
}
// Notify ants when classifier error dumped prompts (will be in /share)
if (
process.env.USER_TYPE === 'ant' &&
classifierResult.errorDumpPath &&
context.addNotification
) {
context.addNotification({
key: 'auto-mode-error-dump',
text: `Auto mode classifier error — prompts dumped to ${classifierResult.errorDumpPath} (included in /share)`,
priority: 'immediate',
color: 'error',
})
}
// Log classifier decision for metrics (including overhead telemetry)
const yoloDecision = classifierResult.unavailable
? 'unavailable'
: classifierResult.shouldBlock
? 'blocked'
: 'allowed'
// Compute classifier cost in USD for overhead analysis
const classifierCostUSD =
classifierResult.usage && classifierResult.model
? calculateCostFromTokens(
classifierResult.model,
classifierResult.usage,
)
: undefined
logEvent('tengu_auto_mode_decision', {
decision:
yoloDecision as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
inProtectedNamespace: isInProtectedNamespace(),
// msg_id of the agent completion that produced this tool_use —
// the action at the bottom of the classifier transcript.
agentMsgId: assistantMessage.message
.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierModel:
classifierResult.model as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
consecutiveDenials: classifierResult.shouldBlock
? denialState.consecutiveDenials + 1
: 0,
totalDenials: classifierResult.shouldBlock
? denialState.totalDenials + 1
: denialState.totalDenials,
// Overhead telemetry: token usage and latency for the classifier API call
classifierInputTokens: classifierResult.usage?.inputTokens,
classifierOutputTokens: classifierResult.usage?.outputTokens,
classifierCacheReadInputTokens:
classifierResult.usage?.cacheReadInputTokens,
classifierCacheCreationInputTokens:
classifierResult.usage?.cacheCreationInputTokens,
classifierDurationMs: classifierResult.durationMs,
// Character lengths of the prompt components sent to the classifier
classifierSystemPromptLength:
classifierResult.promptLengths?.systemPrompt,
classifierToolCallsLength: classifierResult.promptLengths?.toolCalls,
classifierUserPromptsLength:
classifierResult.promptLengths?.userPrompts,
// Session totals at time of classifier call (for computing overhead %).
// These are main-transcript-only — sideQuery (used by the classifier)
// does NOT call addToTotalSessionCost, so classifier tokens are excluded.
sessionInputTokens: getTotalInputTokens(),
sessionOutputTokens: getTotalOutputTokens(),
sessionCacheReadInputTokens: getTotalCacheReadInputTokens(),
sessionCacheCreationInputTokens: getTotalCacheCreationInputTokens(),
classifierCostUSD,
classifierStage:
classifierResult.stage as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierStage1InputTokens: classifierResult.stage1Usage?.inputTokens,
classifierStage1OutputTokens:
classifierResult.stage1Usage?.outputTokens,
classifierStage1CacheReadInputTokens:
classifierResult.stage1Usage?.cacheReadInputTokens,
classifierStage1CacheCreationInputTokens:
classifierResult.stage1Usage?.cacheCreationInputTokens,
classifierStage1DurationMs: classifierResult.stage1DurationMs,
classifierStage1RequestId:
classifierResult.stage1RequestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierStage1MsgId:
classifierResult.stage1MsgId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierStage1CostUSD:
classifierResult.stage1Usage && classifierResult.model
? calculateCostFromTokens(
classifierResult.model,
classifierResult.stage1Usage,
)
: undefined,
classifierStage2InputTokens: classifierResult.stage2Usage?.inputTokens,
classifierStage2OutputTokens:
classifierResult.stage2Usage?.outputTokens,
classifierStage2CacheReadInputTokens:
classifierResult.stage2Usage?.cacheReadInputTokens,
classifierStage2CacheCreationInputTokens:
classifierResult.stage2Usage?.cacheCreationInputTokens,
classifierStage2DurationMs: classifierResult.stage2DurationMs,
classifierStage2RequestId:
classifierResult.stage2RequestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierStage2MsgId:
classifierResult.stage2MsgId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
classifierStage2CostUSD:
classifierResult.stage2Usage && classifierResult.model
? calculateCostFromTokens(
classifierResult.model,
classifierResult.stage2Usage,
)
: undefined,
})
if (classifierResult.durationMs !== undefined) {
addToTurnClassifierDuration(classifierResult.durationMs)
}
if (classifierResult.shouldBlock) {
// Transcript exceeded the classifier's context window — deterministic
// error, won't recover on retry. Skip iron_gate and fall back to
// normal prompting so the user can approve/deny manually.
if (classifierResult.transcriptTooLong) {
if (appState.toolPermissionContext.shouldAvoidPermissionPrompts) {
// Permanent condition (transcript only grows) — deny-retry-deny
// wastes tokens without ever hitting the denial-limit abort.
throw new AbortError(
'Agent aborted: auto mode classifier transcript exceeded context window in headless mode',
)
}
logForDebugging(
'Auto mode classifier transcript too long, falling back to normal permission handling',
{ level: 'warn' },
)
return {
...result,
decisionReason: {
type: 'other',
reason:
'Auto mode classifier transcript exceeded context window — falling back to manual approval',
},
}
}
// When classifier is unavailable (API error), behavior depends on
// the tengu_iron_gate_closed gate.
if (classifierResult.unavailable) {
if (
getFeatureValue_CACHED_WITH_REFRESH(
'tengu_iron_gate_closed',
true,
CLASSIFIER_FAIL_CLOSED_REFRESH_MS,
)
) {
logForDebugging(
'Auto mode classifier unavailable, denying with retry guidance (fail closed)',
{ level: 'warn' },
)
return {
behavior: 'deny',
decisionReason: {
type: 'classifier',
classifier: 'auto-mode',
reason: 'Classifier unavailable',
},
message: buildClassifierUnavailableMessage(
tool.name,
classifierResult.model,
),
}
}
// Fail open: fall back to normal permission handling
logForDebugging(
'Auto mode classifier unavailable, falling back to normal permission handling (fail open)',
{ level: 'warn' },
)
return result
}
// Update denial tracking and check limits
const newDenialState = recordDenial(denialState)
persistDenialState(context, newDenialState)
logForDebugging(
`Auto mode classifier blocked action: ${classifierResult.reason}`,
{ level: 'warn' },
)
// If denial limit hit, fall back to prompting so the user
// can review. We check after the classifier so we can include
// its reason in the prompt.
const denialLimitResult = handleDenialLimitExceeded(
newDenialState,
appState,
classifierResult.reason,
assistantMessage,
tool,
result,
context,
)
if (denialLimitResult) {
return denialLimitResult
}
return {
behavior: 'deny',
decisionReason: {
type: 'classifier',
classifier: 'auto-mode',
reason: classifierResult.reason,
},
message: buildYoloRejectionMessage(classifierResult.reason),
}
}
// Reset consecutive denials on success
const newDenialState = recordSuccess(denialState)
persistDenialState(context, newDenialState)
return {
behavior: 'allow',
updatedInput: input,
decisionReason: {
type: 'classifier',
classifier: 'auto-mode',
reason: classifierResult.reason,
},
}
}
// When permission prompts should be avoided (e.g., background/headless agents),
// run PermissionRequest hooks first to give them a chance to allow/deny.
// Only auto-deny if no hook provides a decision.
if (appState.toolPermissionContext.shouldAvoidPermissionPrompts) {
const hookDecision = await runPermissionRequestHooksForHeadlessAgent(
tool,
input,
toolUseID,
context,
appState.toolPermissionContext.mode,
result.suggestions,
)
if (hookDecision) {
return hookDecision
}
return {
behavior: 'deny',
decisionReason: {
type: 'asyncAgent',
reason: 'Permission prompts are not available in this context',
},
message: AUTO_REJECT_MESSAGE(tool.name),
}
}
}
return result
}
/**
* Persist denial tracking state. For async subagents with localDenialTracking,
* mutate the local state in place (since setAppState is a no-op). Otherwise,
* write to appState as usual.
*/
function persistDenialState(
context: ToolUseContext,
newState: DenialTrackingState,
): void {
if (context.localDenialTracking) {
Object.assign(context.localDenialTracking, newState)
} else {
context.setAppState(prev => {
// recordSuccess returns the same reference when state is
// unchanged. Returning prev here lets store.setState's Object.is check
// skip the listener loop entirely.
if (prev.denialTracking === newState) return prev
return { ...prev, denialTracking: newState }
})
}
}
/**
* Check if a denial limit was exceeded and return an 'ask' result
* so the user can review. Returns null if no limit was hit.
*/
function handleDenialLimitExceeded(
denialState: DenialTrackingState,
appState: {
toolPermissionContext: { shouldAvoidPermissionPrompts?: boolean }
},
classifierReason: string,
assistantMessage: AssistantMessage,
tool: Tool,
result: PermissionDecision,
context: ToolUseContext,
): PermissionDecision | null {
if (!shouldFallbackToPrompting(denialState)) {
return null
}
const hitTotalLimit = denialState.totalDenials >= DENIAL_LIMITS.maxTotal
const isHeadless = appState.toolPermissionContext.shouldAvoidPermissionPrompts