forked from ultraworkers/claw-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoolExecution.ts
More file actions
1745 lines (1651 loc) · 58.9 KB
/
Copy pathtoolExecution.ts
File metadata and controls
1745 lines (1651 loc) · 58.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { feature } from 'bun:bundle'
import type {
ContentBlockParam,
ToolResultBlockParam,
ToolUseBlock,
} from '@anthropic-ai/sdk/resources/index.mjs'
import {
type AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
logEvent,
} from 'src/services/analytics/index.js'
import {
extractMcpToolDetails,
extractSkillName,
extractToolInputForTelemetry,
getFileExtensionForAnalytics,
getFileExtensionsFromBashCommand,
isToolDetailsLoggingEnabled,
mcpToolDetailsForAnalytics,
sanitizeToolNameForAnalytics,
} from 'src/services/analytics/metadata.js'
import {
addToToolDuration,
getCodeEditToolDecisionCounter,
getStatsStore,
} from '../../bootstrap/state.js'
import {
buildCodeEditToolAttributes,
isCodeEditingTool,
} from '../../hooks/toolPermission/permissionLogging.js'
import type { CanUseToolFn } from '../../hooks/useCanUseTool.js'
import {
findToolByName,
type Tool,
type ToolProgress,
type ToolProgressData,
type ToolUseContext,
} from '../../Tool.js'
import type { BashToolInput } from '../../tools/BashTool/BashTool.js'
import { startSpeculativeClassifierCheck } from '../../tools/BashTool/bashPermissions.js'
import { BASH_TOOL_NAME } from '../../tools/BashTool/toolName.js'
import { FILE_EDIT_TOOL_NAME } from '../../tools/FileEditTool/constants.js'
import { FILE_READ_TOOL_NAME } from '../../tools/FileReadTool/prompt.js'
import { FILE_WRITE_TOOL_NAME } from '../../tools/FileWriteTool/prompt.js'
import { NOTEBOOK_EDIT_TOOL_NAME } from '../../tools/NotebookEditTool/constants.js'
import { POWERSHELL_TOOL_NAME } from '../../tools/PowerShellTool/toolName.js'
import { parseGitCommitId } from '../../tools/shared/gitOperationTracking.js'
import {
isDeferredTool,
TOOL_SEARCH_TOOL_NAME,
} from '../../tools/ToolSearchTool/prompt.js'
import { getAllBaseTools } from '../../tools.js'
import type { HookProgress } from '../../types/hooks.js'
import type {
AssistantMessage,
AttachmentMessage,
Message,
ProgressMessage,
StopHookInfo,
} from '../../types/message.js'
import { count } from '../../utils/array.js'
import { createAttachmentMessage } from '../../utils/attachments.js'
import { logForDebugging } from '../../utils/debug.js'
import {
AbortError,
errorMessage,
getErrnoCode,
ShellError,
TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
} from '../../utils/errors.js'
import { executePermissionDeniedHooks } from '../../utils/hooks.js'
import { logError } from '../../utils/log.js'
import {
CANCEL_MESSAGE,
createProgressMessage,
createStopHookSummaryMessage,
createToolResultStopMessage,
createUserMessage,
withMemoryCorrectionHint,
} from '../../utils/messages.js'
import type {
PermissionDecisionReason,
PermissionResult,
} from '../../utils/permissions/PermissionResult.js'
import {
startSessionActivity,
stopSessionActivity,
} from '../../utils/sessionActivity.js'
import { jsonStringify } from '../../utils/slowOperations.js'
import { Stream } from '../../utils/stream.js'
import { logOTelEvent } from '../../utils/telemetry/events.js'
import {
addToolContentEvent,
endToolBlockedOnUserSpan,
endToolExecutionSpan,
endToolSpan,
isBetaTracingEnabled,
startToolBlockedOnUserSpan,
startToolExecutionSpan,
startToolSpan,
} from '../../utils/telemetry/sessionTracing.js'
import {
formatError,
formatZodValidationError,
} from '../../utils/toolErrors.js'
import {
processPreMappedToolResultBlock,
processToolResultBlock,
} from '../../utils/toolResultStorage.js'
import {
extractDiscoveredToolNames,
isToolSearchEnabledOptimistic,
isToolSearchToolAvailable,
} from '../../utils/toolSearch.js'
import {
McpAuthError,
McpToolCallError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
} from '../mcp/client.js'
import { mcpInfoFromString } from '../mcp/mcpStringUtils.js'
import { normalizeNameForMCP } from '../mcp/normalization.js'
import type { MCPServerConnection } from '../mcp/types.js'
import {
getLoggingSafeMcpBaseUrl,
getMcpServerScopeFromToolName,
isMcpTool,
} from '../mcp/utils.js'
import {
resolveHookPermissionDecision,
runPostToolUseFailureHooks,
runPostToolUseHooks,
runPreToolUseHooks,
} from './toolHooks.js'
/** Minimum total hook duration (ms) to show inline timing summary */
export const HOOK_TIMING_DISPLAY_THRESHOLD_MS = 500
/** Log a debug warning when hooks/permission-decision block for this long. Matches
* BashTool's PROGRESS_THRESHOLD_MS — the collapsed view feels stuck past this. */
const SLOW_PHASE_LOG_THRESHOLD_MS = 2000
/**
* Classify a tool execution error into a telemetry-safe string.
*
* In minified/external builds, `error.constructor.name` is mangled into
* short identifiers like "nJT" or "Chq" — useless for diagnostics.
* This function extracts structured, telemetry-safe information instead:
* - TelemetrySafeError: use its telemetryMessage (already vetted)
* - Node.js fs errors: log the error code (ENOENT, EACCES, etc.)
* - Known error types: use their unminified name
* - Fallback: "Error" (better than a mangled 3-char identifier)
*/
export function classifyToolError(error: unknown): string {
if (
error instanceof TelemetrySafeError_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS
) {
return error.telemetryMessage.slice(0, 200)
}
if (error instanceof Error) {
// Node.js filesystem errors have a `code` property (ENOENT, EACCES, etc.)
// These are safe to log and much more useful than the constructor name.
const errnoCode = getErrnoCode(error)
if (typeof errnoCode === 'string') {
return `Error:${errnoCode}`
}
// ShellError, ImageSizeError, etc. have stable `.name` properties
// that survive minification (they're set in the constructor).
if (error.name && error.name !== 'Error' && error.name.length > 3) {
return error.name.slice(0, 60)
}
return 'Error'
}
return 'UnknownError'
}
/**
* Map a rule's origin to the documented OTel `source` vocabulary, matching
* the interactive path's semantics (permissionLogging.ts:81): session-scoped
* grants are temporary, on-disk grants are permanent, and user-authored
* denies are user_reject regardless of persistence. Everything the user
* didn't write (cliArg, policySettings, projectSettings, flagSettings) is
* config.
*/
function ruleSourceToOTelSource(
ruleSource: string,
behavior: 'allow' | 'deny',
): string {
switch (ruleSource) {
case 'session':
return behavior === 'allow' ? 'user_temporary' : 'user_reject'
case 'localSettings':
case 'userSettings':
return behavior === 'allow' ? 'user_permanent' : 'user_reject'
default:
return 'config'
}
}
/**
* Map a PermissionDecisionReason to the OTel `source` label for the
* non-interactive tool_decision path, staying within the documented
* vocabulary (config, hook, user_permanent, user_temporary, user_reject).
*
* For permissionPromptTool, the SDK host may set decisionClassification on
* the PermissionResult to tell us exactly what happened (once vs always vs
* cache hit — the host knows, we can't tell from {behavior:'allow'} alone).
* Without it, we fall back conservatively: allow → user_temporary,
* deny → user_reject.
*/
function decisionReasonToOTelSource(
reason: PermissionDecisionReason | undefined,
behavior: 'allow' | 'deny',
): string {
if (!reason) {
return 'config'
}
switch (reason.type) {
case 'permissionPromptTool': {
// toolResult is typed `unknown` on PermissionDecisionReason but carries
// the parsed Output from PermissionPromptToolResultSchema. Narrow at
// runtime rather than widen the cross-file type.
const toolResult = reason.toolResult as
| { decisionClassification?: string }
| undefined
const classified = toolResult?.decisionClassification
if (
classified === 'user_temporary' ||
classified === 'user_permanent' ||
classified === 'user_reject'
) {
return classified
}
return behavior === 'allow' ? 'user_temporary' : 'user_reject'
}
case 'rule':
return ruleSourceToOTelSource(reason.rule.source, behavior)
case 'hook':
return 'hook'
case 'mode':
case 'classifier':
case 'subcommandResults':
case 'asyncAgent':
case 'sandboxOverride':
case 'workingDir':
case 'safetyCheck':
case 'other':
return 'config'
default: {
const _exhaustive: never = reason
return 'config'
}
}
}
function getNextImagePasteId(messages: Message[]): number {
let maxId = 0
for (const message of messages) {
if (message.type === 'user' && message.imagePasteIds) {
for (const id of message.imagePasteIds) {
if (id > maxId) maxId = id
}
}
}
return maxId + 1
}
export type MessageUpdateLazy<M extends Message = Message> = {
message: M
contextModifier?: {
toolUseID: string
modifyContext: (context: ToolUseContext) => ToolUseContext
}
}
export type McpServerType =
| 'stdio'
| 'sse'
| 'http'
| 'ws'
| 'sdk'
| 'sse-ide'
| 'ws-ide'
| 'claudeai-proxy'
| undefined
function findMcpServerConnection(
toolName: string,
mcpClients: MCPServerConnection[],
): MCPServerConnection | undefined {
if (!toolName.startsWith('mcp__')) {
return undefined
}
const mcpInfo = mcpInfoFromString(toolName)
if (!mcpInfo) {
return undefined
}
// mcpInfo.serverName is normalized (e.g., "claude_ai_Slack"), but client.name
// is the original name (e.g., "claude.ai Slack"). Normalize both for comparison.
return mcpClients.find(
client => normalizeNameForMCP(client.name) === mcpInfo.serverName,
)
}
/**
* Extracts the MCP server transport type from a tool name.
* Returns the server type (stdio, sse, http, ws, sdk, etc.) for MCP tools,
* or undefined for built-in tools.
*/
function getMcpServerType(
toolName: string,
mcpClients: MCPServerConnection[],
): McpServerType {
const serverConnection = findMcpServerConnection(toolName, mcpClients)
if (serverConnection?.type === 'connected') {
// Handle stdio configs where type field is optional (defaults to 'stdio')
return serverConnection.config.type ?? 'stdio'
}
return undefined
}
/**
* Extracts the MCP server base URL for a tool by looking up its server connection.
* Returns undefined for stdio servers, built-in tools, or if the server is not connected.
*/
function getMcpServerBaseUrlFromToolName(
toolName: string,
mcpClients: MCPServerConnection[],
): string | undefined {
const serverConnection = findMcpServerConnection(toolName, mcpClients)
if (serverConnection?.type !== 'connected') {
return undefined
}
return getLoggingSafeMcpBaseUrl(serverConnection.config)
}
export async function* runToolUse(
toolUse: ToolUseBlock,
assistantMessage: AssistantMessage,
canUseTool: CanUseToolFn,
toolUseContext: ToolUseContext,
): AsyncGenerator<MessageUpdateLazy, void> {
const toolName = toolUse.name
// First try to find in the available tools (what the model sees)
let tool = findToolByName(toolUseContext.options.tools, toolName)
// If not found, check if it's a deprecated tool being called by alias
// (e.g., old transcripts calling "KillShell" which is now an alias for "TaskStop")
// Only fall back for tools where the name matches an alias, not the primary name
if (!tool) {
const fallbackTool = findToolByName(getAllBaseTools(), toolName)
// Only use fallback if the tool was found via alias (deprecated name)
if (fallbackTool && fallbackTool.aliases?.includes(toolName)) {
tool = fallbackTool
}
}
const messageId = assistantMessage.message.id
const requestId = assistantMessage.requestId
const mcpServerType = getMcpServerType(
toolName,
toolUseContext.options.mcpClients,
)
const mcpServerBaseUrl = getMcpServerBaseUrlFromToolName(
toolName,
toolUseContext.options.mcpClients,
)
// Check if the tool exists
if (!tool) {
const sanitizedToolName = sanitizeToolNameForAnalytics(toolName)
logForDebugging(`Unknown tool ${toolName}: ${toolUse.id}`)
logEvent('tengu_tool_use_error', {
error:
`No such tool available: ${sanitizedToolName}` as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizedToolName,
toolUseID:
toolUse.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
isMcp: toolName.startsWith('mcp__'),
queryChainId: toolUseContext.queryTracking
?.chainId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: toolUseContext.queryTracking?.depth,
...(mcpServerType && {
mcpServerType:
mcpServerType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(mcpServerBaseUrl && {
mcpServerBaseUrl:
mcpServerBaseUrl as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(requestId && {
requestId:
requestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...mcpToolDetailsForAnalytics(toolName, mcpServerType, mcpServerBaseUrl),
})
yield {
message: createUserMessage({
content: [
{
type: 'tool_result',
content: `<tool_use_error>Error: No such tool available: ${toolName}</tool_use_error>`,
is_error: true,
tool_use_id: toolUse.id,
},
],
toolUseResult: `Error: No such tool available: ${toolName}`,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
}
return
}
const toolInput = toolUse.input as { [key: string]: string }
try {
if (toolUseContext.abortController.signal.aborted) {
logEvent('tengu_tool_use_cancelled', {
toolName: sanitizeToolNameForAnalytics(tool.name),
toolUseID:
toolUse.id as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
isMcp: tool.isMcp ?? false,
queryChainId: toolUseContext.queryTracking
?.chainId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: toolUseContext.queryTracking?.depth,
...(mcpServerType && {
mcpServerType:
mcpServerType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(mcpServerBaseUrl && {
mcpServerBaseUrl:
mcpServerBaseUrl as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(requestId && {
requestId:
requestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...mcpToolDetailsForAnalytics(
tool.name,
mcpServerType,
mcpServerBaseUrl,
),
})
const content = createToolResultStopMessage(toolUse.id)
content.content = withMemoryCorrectionHint(CANCEL_MESSAGE)
yield {
message: createUserMessage({
content: [content],
toolUseResult: CANCEL_MESSAGE,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
}
return
}
for await (const update of streamedCheckPermissionsAndCallTool(
tool,
toolUse.id,
toolInput,
toolUseContext,
canUseTool,
assistantMessage,
messageId,
requestId,
mcpServerType,
mcpServerBaseUrl,
)) {
yield update
}
} catch (error) {
logError(error)
const errorMessage = error instanceof Error ? error.message : String(error)
const toolInfo = tool ? ` (${tool.name})` : ''
const detailedError = `Error calling tool${toolInfo}: ${errorMessage}`
yield {
message: createUserMessage({
content: [
{
type: 'tool_result',
content: `<tool_use_error>${detailedError}</tool_use_error>`,
is_error: true,
tool_use_id: toolUse.id,
},
],
toolUseResult: detailedError,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
}
}
}
function streamedCheckPermissionsAndCallTool(
tool: Tool,
toolUseID: string,
input: { [key: string]: boolean | string | number },
toolUseContext: ToolUseContext,
canUseTool: CanUseToolFn,
assistantMessage: AssistantMessage,
messageId: string,
requestId: string | undefined,
mcpServerType: McpServerType,
mcpServerBaseUrl: ReturnType<typeof getLoggingSafeMcpBaseUrl>,
): AsyncIterable<MessageUpdateLazy> {
// This is a bit of a hack to get progress events and final results
// into a single async iterable.
//
// Ideally the progress reporting and tool call reporting would
// be via separate mechanisms.
const stream = new Stream<MessageUpdateLazy>()
checkPermissionsAndCallTool(
tool,
toolUseID,
input,
toolUseContext,
canUseTool,
assistantMessage,
messageId,
requestId,
mcpServerType,
mcpServerBaseUrl,
progress => {
logEvent('tengu_tool_use_progress', {
messageID:
messageId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
isMcp: tool.isMcp ?? false,
queryChainId: toolUseContext.queryTracking
?.chainId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: toolUseContext.queryTracking?.depth,
...(mcpServerType && {
mcpServerType:
mcpServerType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(mcpServerBaseUrl && {
mcpServerBaseUrl:
mcpServerBaseUrl as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(requestId && {
requestId:
requestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...mcpToolDetailsForAnalytics(
tool.name,
mcpServerType,
mcpServerBaseUrl,
),
})
stream.enqueue({
message: createProgressMessage({
toolUseID: progress.toolUseID,
parentToolUseID: toolUseID,
data: progress.data,
}),
})
},
)
.then(results => {
for (const result of results) {
stream.enqueue(result)
}
})
.catch(error => {
stream.error(error)
})
.finally(() => {
stream.done()
})
return stream
}
/**
* Appended to Zod errors when a deferred tool wasn't in the discovered-tool
* set — re-runs the claude.ts schema-filter scan dispatch-time to detect the
* mismatch. The raw Zod error ("expected array, got string") doesn't tell the
* model to re-load the tool; this hint does. Null if the schema was sent.
*/
export function buildSchemaNotSentHint(
tool: Tool,
messages: Message[],
tools: readonly { name: string }[],
): string | null {
// Optimistic gating — reconstructing claude.ts's full useToolSearch
// computation is fragile. These two gates prevent pointing at a ToolSearch
// that isn't callable; occasional misfires (Haiku, tst-auto below threshold)
// cost one extra round-trip on an already-failing path.
if (!isToolSearchEnabledOptimistic()) return null
if (!isToolSearchToolAvailable(tools)) return null
if (!isDeferredTool(tool)) return null
const discovered = extractDiscoveredToolNames(messages)
if (discovered.has(tool.name)) return null
return (
`\n\nThis tool's schema was not sent to the API — it was not in the discovered-tool set derived from message history. ` +
`Without the schema in your prompt, typed parameters (arrays, numbers, booleans) get emitted as strings and the client-side parser rejects them. ` +
`Load the tool first: call ${TOOL_SEARCH_TOOL_NAME} with query "select:${tool.name}", then retry this call.`
)
}
async function checkPermissionsAndCallTool(
tool: Tool,
toolUseID: string,
input: { [key: string]: boolean | string | number },
toolUseContext: ToolUseContext,
canUseTool: CanUseToolFn,
assistantMessage: AssistantMessage,
messageId: string,
requestId: string | undefined,
mcpServerType: McpServerType,
mcpServerBaseUrl: ReturnType<typeof getLoggingSafeMcpBaseUrl>,
onToolProgress: (
progress: ToolProgress<ToolProgressData> | ProgressMessage<HookProgress>,
) => void,
): Promise<MessageUpdateLazy[]> {
// Validate input types with zod (surprisingly, the model is not great at generating valid input)
const parsedInput = tool.inputSchema.safeParse(input)
if (!parsedInput.success) {
let errorContent = formatZodValidationError(tool.name, parsedInput.error)
const schemaHint = buildSchemaNotSentHint(
tool,
toolUseContext.messages,
toolUseContext.options.tools,
)
if (schemaHint) {
logEvent('tengu_deferred_tool_schema_not_sent', {
toolName: sanitizeToolNameForAnalytics(tool.name),
isMcp: tool.isMcp ?? false,
})
errorContent += schemaHint
}
logForDebugging(
`${tool.name} tool input error: ${errorContent.slice(0, 200)}`,
)
logEvent('tengu_tool_use_error', {
error:
'InputValidationError' as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
errorDetails: errorContent.slice(
0,
2000,
) as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
messageID:
messageId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
isMcp: tool.isMcp ?? false,
queryChainId: toolUseContext.queryTracking
?.chainId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: toolUseContext.queryTracking?.depth,
...(mcpServerType && {
mcpServerType:
mcpServerType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(mcpServerBaseUrl && {
mcpServerBaseUrl:
mcpServerBaseUrl as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(requestId && {
requestId:
requestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...mcpToolDetailsForAnalytics(tool.name, mcpServerType, mcpServerBaseUrl),
})
return [
{
message: createUserMessage({
content: [
{
type: 'tool_result',
content: `<tool_use_error>InputValidationError: ${errorContent}</tool_use_error>`,
is_error: true,
tool_use_id: toolUseID,
},
],
toolUseResult: `InputValidationError: ${parsedInput.error.message}`,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
},
]
}
// Validate input values. Each tool has its own validation logic
const isValidCall = await tool.validateInput?.(
parsedInput.data,
toolUseContext,
)
if (isValidCall?.result === false) {
logForDebugging(
`${tool.name} tool validation error: ${isValidCall.message?.slice(0, 200)}`,
)
logEvent('tengu_tool_use_error', {
messageID:
messageId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
toolName: sanitizeToolNameForAnalytics(tool.name),
error:
isValidCall.message as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
errorCode: isValidCall.errorCode,
isMcp: tool.isMcp ?? false,
queryChainId: toolUseContext.queryTracking
?.chainId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
queryDepth: toolUseContext.queryTracking?.depth,
...(mcpServerType && {
mcpServerType:
mcpServerType as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(mcpServerBaseUrl && {
mcpServerBaseUrl:
mcpServerBaseUrl as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...(requestId && {
requestId:
requestId as AnalyticsMetadata_I_VERIFIED_THIS_IS_NOT_CODE_OR_FILEPATHS,
}),
...mcpToolDetailsForAnalytics(tool.name, mcpServerType, mcpServerBaseUrl),
})
return [
{
message: createUserMessage({
content: [
{
type: 'tool_result',
content: `<tool_use_error>${isValidCall.message}</tool_use_error>`,
is_error: true,
tool_use_id: toolUseID,
},
],
toolUseResult: `Error: ${isValidCall.message}`,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
},
]
}
// Speculatively start the bash allow classifier check early so it runs in
// parallel with pre-tool hooks, deny/ask classifiers, and permission dialog
// setup. The UI indicator (setClassifierChecking) is NOT set here — it's
// set in interactiveHandler.ts only when the permission check returns `ask`
// with a pendingClassifierCheck. This avoids flashing "classifier running"
// for commands that auto-allow via prefix rules.
if (
tool.name === BASH_TOOL_NAME &&
parsedInput.data &&
'command' in parsedInput.data
) {
const appState = toolUseContext.getAppState()
startSpeculativeClassifierCheck(
(parsedInput.data as BashToolInput).command,
appState.toolPermissionContext,
toolUseContext.abortController.signal,
toolUseContext.options.isNonInteractiveSession,
)
}
const resultingMessages = []
// Defense-in-depth: strip _simulatedSedEdit from model-provided Bash input.
// This field is internal-only — it must only be injected by the permission
// system (SedEditPermissionRequest) after user approval. If the model supplies
// it, the schema's strictObject should already reject it, but we strip here
// as a safeguard against future regressions.
let processedInput = parsedInput.data
if (
tool.name === BASH_TOOL_NAME &&
processedInput &&
typeof processedInput === 'object' &&
'_simulatedSedEdit' in processedInput
) {
const { _simulatedSedEdit: _, ...rest } =
processedInput as typeof processedInput & {
_simulatedSedEdit: unknown
}
processedInput = rest as typeof processedInput
}
// Backfill legacy/derived fields on a shallow clone so hooks/canUseTool see
// them without affecting tool.call(). SendMessageTool adds fields; file
// tools overwrite file_path with expandPath — that mutation must not reach
// call() because tool results embed the input path verbatim (e.g. "File
// created successfully at: {path}"), and changing it alters the serialized
// transcript and VCR fixture hashes. If a hook/permission later returns a
// fresh updatedInput, callInput converges on it below — that replacement
// is intentional and should reach call().
let callInput = processedInput
const backfilledClone =
tool.backfillObservableInput &&
typeof processedInput === 'object' &&
processedInput !== null
? ({ ...processedInput } as typeof processedInput)
: null
if (backfilledClone) {
tool.backfillObservableInput!(backfilledClone as Record<string, unknown>)
processedInput = backfilledClone
}
let shouldPreventContinuation = false
let stopReason: string | undefined
let hookPermissionResult: PermissionResult | undefined
const preToolHookInfos: StopHookInfo[] = []
const preToolHookStart = Date.now()
for await (const result of runPreToolUseHooks(
toolUseContext,
tool,
processedInput,
toolUseID,
assistantMessage.message.id,
requestId,
mcpServerType,
mcpServerBaseUrl,
)) {
switch (result.type) {
case 'message':
if (result.message.message.type === 'progress') {
onToolProgress(result.message.message)
} else {
resultingMessages.push(result.message)
const att = result.message.message.attachment
if (
att &&
'command' in att &&
att.command !== undefined &&
'durationMs' in att &&
att.durationMs !== undefined
) {
preToolHookInfos.push({
command: att.command,
durationMs: att.durationMs,
})
}
}
break
case 'hookPermissionResult':
hookPermissionResult = result.hookPermissionResult
break
case 'hookUpdatedInput':
// Hook provided updatedInput without making a permission decision (passthrough)
// Update processedInput so it's used in the normal permission flow
processedInput = result.updatedInput
break
case 'preventContinuation':
shouldPreventContinuation = result.shouldPreventContinuation
break
case 'stopReason':
stopReason = result.stopReason
break
case 'additionalContext':
resultingMessages.push(result.message)
break
case 'stop':
getStatsStore()?.observe(
'pre_tool_hook_duration_ms',
Date.now() - preToolHookStart,
)
resultingMessages.push({
message: createUserMessage({
content: [createToolResultStopMessage(toolUseID)],
toolUseResult: `Error: ${stopReason}`,
sourceToolAssistantUUID: assistantMessage.uuid,
}),
})
return resultingMessages
}
}
const preToolHookDurationMs = Date.now() - preToolHookStart
getStatsStore()?.observe('pre_tool_hook_duration_ms', preToolHookDurationMs)
if (preToolHookDurationMs >= SLOW_PHASE_LOG_THRESHOLD_MS) {
logForDebugging(
`Slow PreToolUse hooks: ${preToolHookDurationMs}ms for ${tool.name} (${preToolHookInfos.length} hooks)`,
{ level: 'info' },
)
}
// Emit PreToolUse summary immediately so it's visible while the tool executes.
// Use wall-clock time (not sum of individual durations) since hooks run in parallel.
if (process.env.USER_TYPE === 'ant' && preToolHookInfos.length > 0) {
if (preToolHookDurationMs > HOOK_TIMING_DISPLAY_THRESHOLD_MS) {
resultingMessages.push({
message: createStopHookSummaryMessage(
preToolHookInfos.length,
preToolHookInfos,
[],
false,
undefined,
false,
'suggestion',
undefined,
'PreToolUse',
preToolHookDurationMs,
),
})
}
}
const toolAttributes: Record<string, string | number | boolean> = {}
if (processedInput && typeof processedInput === 'object') {
if (tool.name === FILE_READ_TOOL_NAME && 'file_path' in processedInput) {
toolAttributes.file_path = String(processedInput.file_path)
} else if (
(tool.name === FILE_EDIT_TOOL_NAME ||
tool.name === FILE_WRITE_TOOL_NAME) &&
'file_path' in processedInput
) {
toolAttributes.file_path = String(processedInput.file_path)
} else if (tool.name === BASH_TOOL_NAME && 'command' in processedInput) {
const bashInput = processedInput as BashToolInput
toolAttributes.full_command = bashInput.command
}
}
startToolSpan(
tool.name,
toolAttributes,
isBetaTracingEnabled() ? jsonStringify(processedInput) : undefined,
)
startToolBlockedOnUserSpan()
// Check whether we have permission to use the tool,
// and ask the user for permission if we don't
const permissionMode = toolUseContext.getAppState().toolPermissionContext.mode
const permissionStart = Date.now()
const resolved = await resolveHookPermissionDecision(
hookPermissionResult,
tool,
processedInput,
toolUseContext,
canUseTool,
assistantMessage,
toolUseID,
)
const permissionDecision = resolved.decision
processedInput = resolved.input
const permissionDurationMs = Date.now() - permissionStart
// In auto mode, canUseTool awaits the classifier (side_query) — if that's
// slow the collapsed view shows "Running…" with no (Ns) tick since
// bash_progress hasn't started yet. Auto-only: in default mode this timer
// includes interactive-dialog wait (user think time), which is just noise.
if (
permissionDurationMs >= SLOW_PHASE_LOG_THRESHOLD_MS &&
permissionMode === 'auto'
) {
logForDebugging(
`Slow permission decision: ${permissionDurationMs}ms for ${tool.name} ` +
`(mode=${permissionMode}, behavior=${permissionDecision.behavior})`,
{ level: 'info' },
)
}
// Emit tool_decision OTel event and code-edit counter if the interactive
// permission path didn't already log it (headless mode bypasses permission
// logging, so we need to emit both the generic event and the code-edit
// counter here)
if (
permissionDecision.behavior !== 'ask' &&
!toolUseContext.toolDecisions?.has(toolUseID)
) {
const decision =
permissionDecision.behavior === 'allow' ? 'accept' : 'reject'
const source = decisionReasonToOTelSource(
permissionDecision.decisionReason,
permissionDecision.behavior,
)
void logOTelEvent('tool_decision', {
decision,
source,
tool_name: sanitizeToolNameForAnalytics(tool.name),
})
// Increment code-edit tool decision counter for headless mode
if (isCodeEditingTool(tool.name)) {
void buildCodeEditToolAttributes(
tool,
processedInput,
decision,
source,
).then(attributes => getCodeEditToolDecisionCounter()?.add(1, attributes))
}
}
// Add message if permission was granted/denied by PermissionRequest hook
if (
permissionDecision.decisionReason?.type === 'hook' &&
permissionDecision.decisionReason.hookName === 'PermissionRequest' &&
permissionDecision.behavior !== 'ask'
) {
resultingMessages.push({
message: createAttachmentMessage({
type: 'hook_permission_decision',
decision: permissionDecision.behavior,
toolUseID,
hookEvent: 'PermissionRequest',
}),
})
}
if (permissionDecision.behavior !== 'allow') {
logForDebugging(`${tool.name} tool permission denied`)
const decisionInfo = toolUseContext.toolDecisions?.get(toolUseID)
endToolBlockedOnUserSpan('reject', decisionInfo?.source || 'unknown')
endToolSpan()