-
Notifications
You must be signed in to change notification settings - Fork 648
Expand file tree
/
Copy pathagentToolManager.ts
More file actions
1774 lines (1628 loc) · 57.1 KB
/
agentToolManager.ts
File metadata and controls
1774 lines (1628 loc) · 57.1 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 type { IConfigPresenter, MCPToolDefinition } from '@shared/presenter'
import type { AgentToolProgressUpdate } from '@shared/types/presenters/tool.presenter'
import { zodToJsonSchema } from 'zod-to-json-schema'
import { z } from 'zod'
import fs from 'fs'
import path from 'path'
import { app, nativeImage } from 'electron'
import logger from '@shared/logger'
import type { ChatMessage } from '@shared/types/core/chat-message'
import { buildBinaryReadGuidance, shouldRejectAgentBinaryRead } from '@/lib/binaryReadGuard'
import { AgentFileSystemHandler } from './agentFileSystemHandler'
import { AgentBashHandler } from './agentBashHandler'
import { SkillTools } from '../../skillPresenter/skillTools'
import { SkillExecutionService } from '../../skillPresenter/skillExecutionService'
import { questionToolSchema, QUESTION_TOOL_NAME } from '@/lib/agentRuntime/questionTool'
import {
ChatSettingsToolHandler,
buildChatSettingsToolDefinitions,
CHAT_SETTINGS_SKILL_NAME,
CHAT_SETTINGS_TOOL_NAMES
} from './chatSettingsTools'
import type { AgentToolRuntimePort } from '../runtimePorts'
import { YO_BROWSER_TOOL_NAMES } from '../../browser/YoBrowserToolDefinitions'
import { resolveSessionVisionTarget } from '../../vision/sessionVisionResolver'
import {
SUBAGENT_ORCHESTRATOR_TOOL_NAME,
SubagentOrchestratorTool
} from './subagentOrchestratorTool'
// Consider moving to a shared handlers location in future refactoring
import {
CommandPermissionRequiredError,
CommandPermissionService
} from '../../permission/commandPermissionService'
import { FilePermissionRequiredError } from '../../permission/filePermissionService'
export interface AgentToolCallResult {
content: string
rawData?: {
content?: string
isError?: boolean
toolResult?: unknown
rtkApplied?: boolean
rtkMode?: 'rewrite' | 'direct' | 'bypass'
rtkFallbackReason?: string
requiresPermission?: boolean
permissionRequest?: {
toolName: string
serverName: string
permissionType: 'read' | 'write' | 'all' | 'command'
description: string
command?: string
commandSignature?: string
paths?: string[]
commandInfo?: {
command: string
riskLevel: 'low' | 'medium' | 'high' | 'critical'
suggestion: string
signature?: string
baseCommand?: string
}
conversationId?: string
rememberable?: boolean
}
}
}
interface AgentToolManagerOptions {
agentWorkspacePath: string | null
configPresenter: IConfigPresenter
commandPermissionHandler?: CommandPermissionService
runtimePort: AgentToolRuntimePort
}
export class AgentToolManager {
private static readonly YO_BROWSER_TOOL_NAME_SET = new Set<string>(YO_BROWSER_TOOL_NAMES)
private agentWorkspacePath: string | null
private fileSystemHandler: AgentFileSystemHandler | null = null
private bashHandler: AgentBashHandler | null = null
private readonly commandPermissionHandler?: CommandPermissionService
private readonly configPresenter: IConfigPresenter
private readonly runtimePort: AgentToolRuntimePort
private skillTools: SkillTools | null = null
private skillExecutionService: SkillExecutionService | null = null
private chatSettingsHandler: ChatSettingsToolHandler | null = null
private subagentOrchestratorTool: SubagentOrchestratorTool | null = null
private static readonly READ_FILE_AUTO_TRUNCATE_THRESHOLD = 4500
private readonly fileSystemSchemas = {
read: z.object({
path: z.string(),
offset: z.number().int().min(0).optional().describe('Starting character offset (0-based)'),
limit: z
.number()
.int()
.positive()
.optional()
.describe('Maximum characters to read. Large files are auto-truncated if not specified'),
base_directory: z
.string()
.optional()
.describe(
"Base directory for resolving relative paths. Required when using skills with relative paths. For skill-based operations, provide the skill's root directory path."
)
}),
write: z.object({
path: z.string(),
content: z.string(),
base_directory: z
.string()
.optional()
.describe(
'Base directory for resolving relative paths. Required when using skills with relative paths.'
)
}),
ls: z.object({
path: z.string(),
depth: z.number().int().min(0).max(3).default(1),
base_directory: z.string().optional().describe('Base directory for resolving relative paths.')
}),
edit: z.object({
path: z.string(),
oldText: z
.string()
.max(10000)
.describe('The exact text to find and replace (case-sensitive)'),
newText: z.string().max(10000).describe('The replacement text'),
replaceAll: z.boolean().default(true),
base_directory: z.string().optional().describe('Base directory for resolving relative paths.')
}),
find: z.object({
pattern: z.string().describe('Glob pattern (e.g., **/*.ts, src/**/*.js)'),
path: z
.string()
.optional()
.describe('Root directory for search (defaults to workspace root)'),
exclude: z
.array(z.string())
.optional()
.default([])
.describe('Patterns to exclude (e.g., ["node_modules", ".git"])'),
maxResults: z.number().default(1000).describe('Maximum number of results to return'),
base_directory: z.string().optional().describe('Base directory for resolving relative paths.')
}),
grep: z.object({
pattern: z
.string()
.max(1000)
.describe(
'Regular expression pattern (max 1000 characters, must be safe and not cause ReDoS)'
),
path: z.string().optional().default('.'),
filePattern: z.string().optional(),
recursive: z.boolean().default(true),
caseSensitive: z.boolean().default(false),
contextLines: z.number().default(0),
maxResults: z.number().default(100),
base_directory: z.string().optional().describe('Base directory for resolving relative paths.')
}),
exec: z.object({
command: z.string().min(1).describe('The shell command to execute'),
timeoutMs: z
.number()
.min(100)
.max(600000)
.optional()
.describe('Optional timeout in milliseconds'),
description: z
.string()
.min(5)
.max(100)
.optional()
.describe(
'Brief description of what the command does (e.g., "Install dependencies", "Start dev server")'
),
cwd: z.string().optional().describe('Optional working directory for command execution.'),
background: z
.boolean()
.optional()
.describe(
'Run the command in the background (recommended for commands taking >10s). Returns immediately with sessionId for use with process tool.'
),
yieldMs: z
.number()
.min(100)
.optional()
.describe(
'Foreground grace window in milliseconds before auto-backgrounding the command and returning a sessionId (defaults to PI_BASH_YIELD_MS or 10000). Ignored when background is true.'
)
}),
process: z.object({
action: z
.enum(['list', 'poll', 'log', 'write', 'kill', 'clear', 'remove'])
.describe(
'Action to perform: list (all sessions), poll (recent output), log (full output with pagination), write (send to stdin), kill (terminate), clear (empty buffer), remove (cleanup)'
),
sessionId: z
.string()
.optional()
.describe('Session ID (required for most actions except list)'),
offset: z.number().int().min(0).optional().describe('Starting offset for log action'),
limit: z
.number()
.int()
.min(1)
.optional()
.describe('Maximum characters to return for log action'),
data: z.string().optional().describe('Data to write to stdin (write action only)'),
eof: z.boolean().optional().describe('Send EOF after writing data (write action only)')
})
}
private readonly skillSchemas = {
skill_list: z.object({}),
skill_run: z.object({
skill: z.string().min(1).describe('Active skill name that owns the script'),
script: z
.string()
.min(1)
.describe('Script path under the skill root, usually scripts/<name>.<ext>'),
args: z.array(z.string()).optional().default([]).describe('Arguments passed to the script'),
stdin: z.string().optional().describe('Optional stdin payload sent to the script'),
background: z
.boolean()
.optional()
.default(false)
.describe('Run the script in the background and manage it with process tool'),
timeoutMs: z
.number()
.min(100)
.max(600000)
.optional()
.describe('Optional timeout in milliseconds for the script run')
}),
skill_control: z
.object({
action: z.enum(['activate', 'deactivate']).describe('The action to perform'),
skill_name: z.string().min(1).optional().describe('Skill name to activate or deactivate'),
skills: z
.array(z.string())
.min(1)
.optional()
.describe('List of skill names to activate or deactivate')
})
.refine((data) => Boolean(data.skill_name || (data.skills && data.skills.length > 0)), {
message: 'Either skill_name or skills must be provided'
})
}
constructor(options: AgentToolManagerOptions) {
this.agentWorkspacePath = options.agentWorkspacePath
this.configPresenter = options.configPresenter
this.commandPermissionHandler = options.commandPermissionHandler
this.runtimePort = options.runtimePort
this.subagentOrchestratorTool = new SubagentOrchestratorTool(this.runtimePort)
if (this.agentWorkspacePath) {
this.fileSystemHandler = new AgentFileSystemHandler([this.agentWorkspacePath])
this.bashHandler = new AgentBashHandler(
[this.agentWorkspacePath],
this.commandPermissionHandler,
this.configPresenter
)
}
}
/**
* Get all Agent tool definitions in MCP format
*/
async getAllToolDefinitions(context: {
chatMode: 'agent' | 'acp agent'
supportsVision: boolean
agentWorkspacePath: string | null
conversationId?: string
}): Promise<MCPToolDefinition[]> {
const defs: MCPToolDefinition[] = []
const isAgentMode = context.chatMode === 'agent'
const effectiveWorkspacePath = isAgentMode
? context.agentWorkspacePath?.trim() || this.getDefaultAgentWorkspacePath()
: null
// Update filesystem handler if workspace path changed
if (effectiveWorkspacePath !== this.agentWorkspacePath) {
if (effectiveWorkspacePath) {
this.fileSystemHandler = new AgentFileSystemHandler([effectiveWorkspacePath])
this.bashHandler = new AgentBashHandler(
[effectiveWorkspacePath],
this.commandPermissionHandler,
this.configPresenter
)
} else {
this.fileSystemHandler = null
this.bashHandler = null
}
this.agentWorkspacePath = effectiveWorkspacePath
}
// 1. FileSystem tools (agent mode only)
if (isAgentMode && this.fileSystemHandler) {
const fsDefs = this.getFileSystemToolDefinitions()
defs.push(...fsDefs)
}
// 2. Built-in question tool (all modes)
defs.push(...this.getQuestionToolDefinitions())
// 2.5. Subagent orchestration tool (deepchat regular sessions only)
if (isAgentMode && context.conversationId && this.subagentOrchestratorTool) {
try {
const subagentToolDefinition = await this.subagentOrchestratorTool.getToolDefinition(
context.conversationId
)
if (subagentToolDefinition) {
defs.push(subagentToolDefinition)
}
} catch (error) {
logger.warn('[AgentToolManager] Failed to resolve subagent tool availability', { error })
}
}
// 3. Skill tools (agent mode only)
if (isAgentMode && this.isSkillsEnabled()) {
const skillDefs = this.getSkillToolDefinitions()
defs.push(...skillDefs)
if (context.conversationId && (await this.hasRunnableSkillScripts(context.conversationId))) {
defs.push(this.getSkillRunToolDefinition())
}
}
// 4. DeepChat settings tools (agent mode only, skill gated)
if (isAgentMode && this.isSkillsEnabled() && context.conversationId) {
try {
const activeSkills = await this.getSkillPresenter().getActiveSkills(context.conversationId)
if (activeSkills.includes(CHAT_SETTINGS_SKILL_NAME)) {
const allowedTools = await this.getSkillPresenter().getActiveSkillsAllowedTools(
context.conversationId
)
const requiredSettingsTools = Object.values(CHAT_SETTINGS_TOOL_NAMES)
const nonOpenSettingsTools = requiredSettingsTools.filter(
(tool) => tool !== CHAT_SETTINGS_TOOL_NAMES.open
)
const hasNonOpenSettingsTool = nonOpenSettingsTools.some((tool) =>
allowedTools.includes(tool)
)
const effectiveAllowedTools = hasNonOpenSettingsTool
? allowedTools
: Array.from(new Set([...allowedTools, ...requiredSettingsTools]))
const settingsDefs = buildChatSettingsToolDefinitions(effectiveAllowedTools)
defs.push(...settingsDefs)
}
} catch (error) {
logger.warn('[AgentToolManager] Failed to load DeepChat settings tools', { error })
}
}
// 5. YoBrowser CDP tools (agent mode only)
if (isAgentMode) {
try {
defs.push(...this.getYoBrowserToolHandler().getToolDefinitions())
} catch (error) {
logger.warn('[AgentToolManager] Failed to load YoBrowser tools', { error })
}
}
return defs
}
/**
* Call an Agent tool
*/
async callTool(
toolName: string,
args: Record<string, unknown>,
conversationId?: string,
options?: {
toolCallId?: string
onProgress?: (update: AgentToolProgressUpdate) => void
signal?: AbortSignal
}
): Promise<AgentToolCallResult | string> {
if (toolName === QUESTION_TOOL_NAME) {
const validationResult = questionToolSchema.safeParse(args)
if (!validationResult.success) {
throw new Error(
`Invalid arguments for ${QUESTION_TOOL_NAME}. Use a single object with \`header?\`, \`question\`, \`options\`, \`multiple?\`, and \`custom?\`. Ask exactly one question per tool call. Do not use \`questions\` or \`allowOther\`, and do not pass stringified \`options\` JSON. Validation details: ${validationResult.error.message}`
)
}
return {
content: 'question_requested',
rawData: {
content: 'question_requested',
isError: false,
toolResult: validationResult.data
}
}
}
if (toolName === SUBAGENT_ORCHESTRATOR_TOOL_NAME) {
if (!this.subagentOrchestratorTool) {
throw new Error('Subagent orchestrator is not available.')
}
return await this.subagentOrchestratorTool.call(args, conversationId, options)
}
// Route to process tool
if (this.isProcessTool(toolName)) {
return await this.callProcessTool(toolName, args, conversationId)
}
// Route to FileSystem tools
if (this.isFileSystemTool(toolName)) {
if (!this.fileSystemHandler) {
throw new Error(`FileSystem handler not initialized for tool: ${toolName}`)
}
return await this.callFileSystemTool(toolName, args, conversationId)
}
// Route to Skill tools
if (this.isSkillTool(toolName)) {
return await this.callSkillTool(toolName, args, conversationId)
}
if (this.isSkillExecutionTool(toolName)) {
return await this.callSkillExecutionTool(toolName, args, conversationId)
}
// Route to DeepChat settings tools
if (this.isChatSettingsTool(toolName)) {
return await this.callChatSettingsTool(toolName, args, conversationId)
}
// Route to YoBrowser CDP tools
if (AgentToolManager.YO_BROWSER_TOOL_NAME_SET.has(toolName)) {
const response = await this.getYoBrowserToolHandler().callTool(toolName, args, conversationId)
return {
content: response
}
}
throw new Error(`Unknown Agent tool: ${toolName}`)
}
private async getWorkdirForConversation(conversationId: string): Promise<string | null> {
try {
return await this.runtimePort.resolveConversationWorkdir(conversationId)
} catch (error) {
if (!this.isConversationNotFoundError(error)) {
logger.warn('[AgentToolManager] Failed to resolve conversation workdir:', {
conversationId,
error
})
}
}
return null
}
private isConversationNotFoundError(error: unknown): boolean {
if (!(error instanceof Error)) return false
return /Conversation\s+.+\s+not found/i.test(error.message)
}
private getFileSystemToolDefinitions(): MCPToolDefinition[] {
const schemas = this.fileSystemSchemas
const defs: MCPToolDefinition[] = [
{
type: 'function',
function: {
name: 'read',
description:
"Read the contents of a file. Supports pagination via offset/limit for large files (auto-truncated at 4500 chars if not specified). For image files, returns an English description of visible content instead of raw pixels. When invoked from a skill context with relative paths, provide base_directory as the skill's root directory.",
parameters: zodToJsonSchema(schemas.read) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-filesystem',
icons: '📁',
description: 'Agent FileSystem tools'
}
},
{
type: 'function',
function: {
name: 'write',
description:
"Write content to a file. For skill files, provide base_directory as the skill's root directory.",
parameters: zodToJsonSchema(schemas.write) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-filesystem',
icons: '📁',
description: 'Agent FileSystem tools'
}
},
{
type: 'function',
function: {
name: 'edit',
description:
'Make precise text or line replacements in a file by matching exact text strings. Set replaceAll=false to replace only the first match.',
parameters: zodToJsonSchema(schemas.edit) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-filesystem',
icons: '📁',
description: 'Agent FileSystem tools'
}
},
{
type: 'function',
function: {
name: 'exec',
description:
'Execute a shell command in the workspace directory. Use background: true when you know the command should detach immediately. Otherwise foreground exec waits briefly, and long-running commands may auto-background and return a session ID for use with the process tool.',
parameters: zodToJsonSchema(schemas.exec) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-filesystem',
icons: '📁',
description: 'Agent FileSystem tools'
}
},
{
type: 'function',
function: {
name: 'process',
description:
'Manage background exec sessions created by explicit background exec calls or by long-running foreground exec calls that yielded a sessionId. Use poll to check output and status, log to get full output with pagination, write to send input to stdin, kill to terminate, and remove to clean up completed sessions.',
parameters: zodToJsonSchema(schemas.process) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-filesystem',
icons: '⚙️',
description: 'Agent FileSystem tools'
}
}
]
return defs
}
private getQuestionToolDefinitions(): MCPToolDefinition[] {
return [
{
type: 'function',
function: {
name: QUESTION_TOOL_NAME,
description:
'Pause the agent loop and ask the user one structured clarification question when missing user preferences, implementation direction, output shape, or risk decisions would materially change the result. Do not use this for casual conversation or for facts you can discover from the repo, tools, or existing context. The loop resumes only after the user responds.',
parameters: zodToJsonSchema(questionToolSchema) as {
type: string
properties: Record<string, unknown>
required?: string[]
}
},
server: {
name: 'agent-core',
icons: '❓',
description: 'Agent core tools'
}
}
]
}
private isFileSystemTool(toolName: string): boolean {
const filesystemTools = ['read', 'write', 'ls', 'edit', 'find', 'grep', 'exec', 'process']
return filesystemTools.includes(toolName)
}
private isProcessTool(toolName: string): boolean {
return toolName === 'process'
}
private async callProcessTool(
_toolName: string,
args: Record<string, unknown>,
conversationId?: string
): Promise<AgentToolCallResult> {
if (!conversationId) {
throw new Error('process tool requires a conversation ID')
}
const { backgroundExecSessionManager } =
await import('@/lib/agentRuntime/backgroundExecSessionManager')
const validationResult = this.fileSystemSchemas.process.safeParse(args)
if (!validationResult.success) {
throw new Error(`Invalid arguments for process: ${validationResult.error.message}`)
}
const { action, sessionId, offset, limit, data, eof } = validationResult.data
switch (action) {
case 'list': {
const sessions = backgroundExecSessionManager.list(conversationId)
return {
content: JSON.stringify({ status: 'ok', sessions }, null, 2)
}
}
case 'poll': {
if (!sessionId) {
throw new Error('sessionId is required for poll action')
}
const result = await backgroundExecSessionManager.poll(conversationId, sessionId)
return {
content: JSON.stringify(result, null, 2)
}
}
case 'log': {
if (!sessionId) {
throw new Error('sessionId is required for log action')
}
const result = await backgroundExecSessionManager.log(
conversationId,
sessionId,
offset,
limit
)
return {
content: JSON.stringify(result, null, 2)
}
}
case 'write': {
if (!sessionId) {
throw new Error('sessionId is required for write action')
}
backgroundExecSessionManager.write(conversationId, sessionId, data ?? '', eof)
return {
content: JSON.stringify({ status: 'ok', sessionId })
}
}
case 'kill': {
if (!sessionId) {
throw new Error('sessionId is required for kill action')
}
await backgroundExecSessionManager.kill(conversationId, sessionId)
return {
content: JSON.stringify({ status: 'ok', sessionId })
}
}
case 'clear': {
if (!sessionId) {
throw new Error('sessionId is required for clear action')
}
backgroundExecSessionManager.clear(conversationId, sessionId)
return {
content: JSON.stringify({ status: 'ok', sessionId })
}
}
case 'remove': {
if (!sessionId) {
throw new Error('sessionId is required for remove action')
}
await backgroundExecSessionManager.remove(conversationId, sessionId)
return {
content: JSON.stringify({ status: 'ok', sessionId })
}
}
default:
throw new Error(`Unknown process action: ${action}`)
}
}
private async callFileSystemTool(
toolName: string,
args: Record<string, unknown>,
conversationId?: string
): Promise<AgentToolCallResult> {
// Handle process tool separately
if (this.isProcessTool(toolName)) {
return this.callProcessTool(toolName, args, conversationId)
}
const schema = this.fileSystemSchemas[toolName as keyof typeof this.fileSystemSchemas]
if (!schema) {
throw new Error(`No schema found for FileSystem tool: ${toolName}`)
}
const validationResult = schema.safeParse(args)
if (!validationResult.success) {
throw new Error(`Invalid arguments for ${toolName}: ${validationResult.error.message}`)
}
const parsedArgs = validationResult.data
if (toolName === 'exec') {
if (!this.bashHandler) {
throw new Error('Bash handler not initialized for exec tool')
}
const execArgs = parsedArgs as {
command: string
timeoutMs?: number
description?: string
cwd?: string
background?: boolean
yieldMs?: number
}
const commandResult = await this.bashHandler.executeCommand(
{
command: execArgs.command,
timeout: execArgs.timeoutMs,
description: execArgs.description ?? 'Execute command',
cwd: execArgs.cwd,
background: execArgs.background,
yieldMs: execArgs.yieldMs
},
{
conversationId
}
)
const content =
typeof commandResult.output === 'string'
? commandResult.output
: JSON.stringify(commandResult.output)
return {
content,
rawData: {
content,
rtkApplied: commandResult.rtkApplied,
rtkMode: commandResult.rtkMode,
rtkFallbackReason: commandResult.rtkFallbackReason
}
}
}
if (!this.fileSystemHandler) {
throw new Error('FileSystem handler not initialized')
}
// Get dynamic workdir from conversation settings
let dynamicWorkdir: string | null = null
if (conversationId) {
try {
dynamicWorkdir = await this.getWorkdirForConversation(conversationId)
} catch (error) {
logger.warn('[AgentToolManager] Failed to get workdir for conversation:', {
conversationId,
error
})
}
}
// Priority: explicit base_directory → conversation workdir → default
const explicitBaseDirectory = (parsedArgs as any).base_directory
const baseDirectory = explicitBaseDirectory ?? dynamicWorkdir ?? undefined
const workspaceRoot =
dynamicWorkdir ?? this.agentWorkspacePath ?? this.getDefaultAgentWorkspacePath()
const allowedDirectories = await this.buildAllowedDirectories(workspaceRoot, conversationId)
const fileSystemHandler = new AgentFileSystemHandler(allowedDirectories, { conversationId })
try {
switch (toolName) {
case 'read': {
const readArgs = parsedArgs as {
path: string
offset?: number
limit?: number
}
const validPath = await this.resolveValidatedReadPath(
fileSystemHandler,
readArgs.path,
baseDirectory
)
const mimeType = await this.getFilePresenter().getMimeType(validPath)
if (await shouldRejectAgentBinaryRead(validPath, mimeType)) {
return {
content: buildBinaryReadGuidance(validPath, mimeType, 'agent')
}
}
if (this.isImageMimeType(mimeType)) {
return {
content: await this.readImageWithVisionFallback(validPath, mimeType, conversationId)
}
}
if (this.shouldUseRawTextRead(mimeType)) {
return {
content: await fileSystemHandler.readFile(
{
paths: [readArgs.path],
offset: readArgs.offset,
limit: readArgs.limit
},
baseDirectory
)
}
}
const prepared = await this.getFilePresenter().prepareFileCompletely(
validPath,
mimeType,
'llm-friendly'
)
return {
content: this.paginateReadContent(
readArgs.path,
prepared.content || '',
readArgs.offset,
readArgs.limit
)
}
}
case 'write':
this.assertWritePermission(
toolName,
parsedArgs,
baseDirectory,
fileSystemHandler,
conversationId
)
return { content: await fileSystemHandler.writeFile(parsedArgs, baseDirectory) }
case 'ls': {
const lsArgs = parsedArgs as {
path: string
depth?: number
}
if ((lsArgs.depth ?? 1) > 1) {
return {
content: await fileSystemHandler.directoryTree(
{ path: lsArgs.path, depth: lsArgs.depth },
baseDirectory
)
}
}
return {
content: await fileSystemHandler.listDirectory(
{ path: lsArgs.path, showDetails: false, sortBy: 'name' },
baseDirectory
)
}
}
case 'edit': {
this.assertWritePermission(
toolName,
parsedArgs,
baseDirectory,
fileSystemHandler,
conversationId
)
const editArgs = parsedArgs as {
path: string
oldText: string
newText: string
replaceAll?: boolean
}
if (editArgs.replaceAll === false) {
return {
content: await fileSystemHandler.editText(
{
path: editArgs.path,
operation: 'edit_lines',
edits: [{ oldText: editArgs.oldText, newText: editArgs.newText }],
dryRun: false
},
baseDirectory
)
}
}
return {
content: await fileSystemHandler.editFile(
{
path: editArgs.path,
oldText: editArgs.oldText,
newText: editArgs.newText
},
baseDirectory
)
}
}
case 'find': {
const findArgs = parsedArgs as {
pattern: string
path?: string
exclude?: string[]
maxResults?: number
}
return {
content: await fileSystemHandler.globSearch(
{
pattern: findArgs.pattern,
root: findArgs.path,
excludePatterns: findArgs.exclude,
maxResults: findArgs.maxResults,
sortBy: 'name'
},
baseDirectory
)
}
}
case 'grep': {
const grepArgs = parsedArgs as {
pattern: string
path?: string
filePattern?: string
recursive?: boolean
caseSensitive?: boolean
contextLines?: number
maxResults?: number
}
return {
content: await fileSystemHandler.grepSearch(
{
path: grepArgs.path ?? '.',
pattern: grepArgs.pattern,
filePattern: grepArgs.filePattern,
recursive: grepArgs.recursive ?? true,
caseSensitive: grepArgs.caseSensitive ?? false,
includeLineNumbers: true,
contextLines: grepArgs.contextLines ?? 0,
maxResults: grepArgs.maxResults ?? 100
},
baseDirectory
)
}
}
default:
throw new Error(`Unknown FileSystem tool: ${toolName}`)
}
} catch (error) {
if (error instanceof CommandPermissionRequiredError) {
return {
content: error.responseContent,
rawData: {
content: error.responseContent,
isError: false,
requiresPermission: true,
permissionRequest: error.permissionRequest
}
}
}
if (error instanceof FilePermissionRequiredError) {
return {
content: error.responseContent,
rawData: {
content: error.responseContent,
isError: false,
requiresPermission: true,
permissionRequest: error.permissionRequest
}
}
}
throw error
}
}
private async buildAllowedDirectories(
workspacePath: string,
conversationId?: string
): Promise<string[]> {
const ordered: string[] = []
const seen = new Set<string>()
const addPath = (value?: string | null) => {
if (!value) return
const resolved = path.resolve(value)
const normalized = process.platform === 'win32' ? resolved.toLowerCase() : resolved
if (seen.has(normalized)) return
seen.add(normalized)
ordered.push(resolved)
}
addPath(workspacePath)
addPath(this.agentWorkspacePath)
if (conversationId) {
const activeSkillRoots = await this.resolveActiveSkillRoots(conversationId)
for (const skillRoot of activeSkillRoots) {
addPath(skillRoot)
}
}
addPath(path.join(app.getPath('home'), '.deepchat'))