-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathagent-tools.ts
More file actions
1240 lines (1214 loc) · 50.7 KB
/
Copy pathagent-tools.ts
File metadata and controls
1240 lines (1214 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Builds the effective OpenClaw agent tool surface.
* Assembles core, shell, channel, OpenClaw, plugin, and Tool Search tools, then
* applies sandbox, profile, provider, sender, group, and sub-agent policy.
*/
import path from "node:path";
import {
normalizeLowercaseStringOrEmpty,
normalizeOptionalLowercaseString,
} from "@openclaw/normalization-core/string-coerce";
import type { SourceReplyDeliveryMode } from "../auto-reply/get-reply-options.types.js";
import { HEARTBEAT_RESPONSE_TOOL_NAME } from "../auto-reply/heartbeat-tool-response.js";
import type { InboundEventKind } from "../channels/inbound-event/kind.js";
import { resolveExecCommandHighlighting } from "../config/exec-command-highlighting.js";
import type { ModelCompatConfig } from "../config/types.models.js";
import type { OpenClawConfig } from "../config/types.openclaw.js";
import type { DiagnosticTraceContext } from "../infra/diagnostic-trace-context.js";
import { resolveEventSessionRoutingPolicy } from "../infra/event-session-routing.js";
import { applyExecPolicyLayer } from "../infra/exec-policy.js";
import { resolveMergedSafeBinProfileFixtures } from "../infra/exec-safe-bin-runtime-policy.js";
import { logWarn } from "../logger.js";
import type { PluginHookChannelContext } from "../plugins/hook-types.js";
import { getPluginToolMeta } from "../plugins/tools.js";
import { createLazyImportLoader } from "../shared/lazy-promise.js";
import type { SkillSnapshot } from "../skills/types.js";
import { resolveGatewayMessageChannel } from "../utils/message-channel.js";
import { resolveAgentConfig } from "./agent-scope.js";
import { wrapToolWithAbortSignal } from "./agent-tools.abort.js";
import {
isToolWrappedWithBeforeToolCallHook,
rewrapToolWithBeforeToolCallHook,
type ToolOutcomeObserver,
wrapToolWithBeforeToolCallHook,
} from "./agent-tools.before-tool-call.js";
import { applyDeferredFollowupToolDescriptions } from "./agent-tools.deferred-followup.js";
import { filterToolsByMessageProvider } from "./agent-tools.message-provider-policy.js";
import {
resolveEffectiveToolPolicy,
resolveGroupToolPolicy,
resolveInheritedToolPolicyForSession,
resolveSubagentToolPolicyForSession,
} from "./agent-tools.policy.js";
import {
assertRequiredParams,
createHostWorkspaceEditTool,
createHostWorkspaceWriteTool,
createOpenClawReadTool,
createSandboxedEditTool,
createSandboxedReadTool,
createSandboxedWriteTool,
getToolParamsRecord,
wrapToolMemoryFlushAppendOnlyWrite,
wrapToolWorkspaceRootGuard,
wrapToolWorkspaceRootGuardWithOptions,
wrapToolParamValidation,
} from "./agent-tools.read.js";
import { normalizeToolParameters } from "./agent-tools.schema.js";
import type { AnyAgentTool } from "./agent-tools.types.js";
import { createApplyPatchTool } from "./apply-patch.js";
import type { AuthProfileStore } from "./auth-profiles/types.js";
import { describeExecTool, describeProcessTool } from "./bash-tools.descriptions.js";
import type { ExecToolDefaults } from "./bash-tools.exec-types.js";
import type { ProcessToolDefaults } from "./bash-tools.process.js";
import { execSchema, processSchema } from "./bash-tools.schemas.js";
import { listChannelAgentTools } from "./channel-tools.js";
import { shouldSuppressManagedWebSearchTool } from "./codex-native-web-search.js";
import { resolveImageSanitizationLimits } from "./image-sanitization.js";
import {
filterLocalModelLeanTools,
resolveLocalModelLeanPreserveToolNames,
} from "./local-model-lean.js";
import type { ModelAuthMode } from "./model-auth.js";
import { resolveOpenClawPluginToolsForOptions } from "./openclaw-plugin-tools.js";
import { createOpenClawTools } from "./openclaw-tools.js";
import type { SandboxContext } from "./sandbox.js";
import { SANDBOX_AGENT_WORKSPACE_MOUNT } from "./sandbox/constants.js";
import { resolveReadOnlyWorkspaceSkillMounts } from "./sandbox/workspace-mounts.js";
import { resolveSenderToolPolicy } from "./sender-tool-policy.js";
import { createCodingTools, createReadTool } from "./sessions/index.js";
import {
isSubagentEnvelopeSession,
resolveSubagentCapabilityStore,
} from "./subagent-capabilities.js";
import {
EXEC_TOOL_DISPLAY_SUMMARY,
PROCESS_TOOL_DISPLAY_SUMMARY,
} from "./tool-description-presets.js";
import { createToolFsPolicy, resolveToolFsConfig } from "./tool-fs-policy.js";
import { resolveToolLoopDetectionConfig } from "./tool-loop-detection-config.js";
import { buildDeclaredToolAllowlistContext } from "./tool-policy-declared-context.js";
import { isToolAllowedByPolicies } from "./tool-policy-match.js";
import {
applyToolPolicyPipeline,
buildDefaultToolPolicyPipelineSteps,
} from "./tool-policy-pipeline.js";
import {
collectExplicitAllowlist,
collectExplicitDenylist,
expandToolGroups,
hasRestrictiveAllowPolicy,
mergeAlsoAllowPolicy,
normalizeToolName,
replaceWithEffectiveToolAllowlist,
resolveToolProfilePolicy,
} from "./tool-policy.js";
import {
createToolSearchTools,
resolveToolSearchConfig,
TOOL_CALL_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_SEARCH_CODE_MODE_TOOL_NAME,
TOOL_SEARCH_RAW_TOOL_NAME,
type ToolSearchCatalogRef,
type ToolSearchCatalogToolExecutor,
} from "./tool-search.js";
import {
replaceWithEffectiveCronCreatorToolAllowlist,
type CronCreatorToolAllowlistEntry,
} from "./tools/cron-tool.js";
import { resolveWorkspaceRoot } from "./workspace-dir.js";
const MEMORY_FLUSH_ALLOWED_TOOL_NAMES = new Set(["read", "write"]);
function hasExplicitDenyPolicy(policy?: { deny?: string[] }): boolean {
return (
Array.isArray(policy?.deny) &&
policy.deny.some((entry) => typeof entry === "string" && entry.trim())
);
}
type GuardContainerMount = {
containerRoot: string;
hostRoot: string;
};
function readOnlySandboxReadMounts(
sandbox: SandboxContext | null | undefined,
): GuardContainerMount[] | undefined {
if (!sandbox) {
return undefined;
}
const mounts: GuardContainerMount[] = [];
if (sandbox.workspaceAccess === "ro" && sandbox.agentWorkspaceDir !== sandbox.workspaceDir) {
mounts.push({
containerRoot: SANDBOX_AGENT_WORKSPACE_MOUNT,
hostRoot: sandbox.agentWorkspaceDir,
});
}
if (sandbox.workspaceAccess === "rw") {
mounts.push(
...resolveReadOnlyWorkspaceSkillMounts({
workspaceDir: sandbox.workspaceDir,
agentWorkspaceDir: sandbox.agentWorkspaceDir,
skillsWorkspaceDir: sandbox.skillsWorkspaceDir,
workdir: sandbox.containerWorkdir,
workspaceAccess: sandbox.workspaceAccess,
}).map((mount) => ({
containerRoot: mount.containerPath,
hostRoot: mount.hostPath,
})),
);
}
return mounts.length > 0 ? mounts : undefined;
}
function resolveSkillReadRoots(skillsSnapshot?: SkillSnapshot): string[] | undefined {
const roots = new Set<string>();
for (const skill of skillsSnapshot?.resolvedSkills ?? []) {
const baseDir = typeof skill.baseDir === "string" ? skill.baseDir.trim() : "";
const filePath = typeof skill.filePath === "string" ? skill.filePath.trim() : "";
const root = baseDir || (filePath ? path.dirname(filePath) : "");
if (!root || !path.isAbsolute(root)) {
continue;
}
roots.add(path.resolve(root));
}
if (roots.size === 0) {
return undefined;
}
return Array.from(roots);
}
type BashToolsModule = typeof import("./bash-tools.js");
const bashToolsModuleLoader = createLazyImportLoader<BashToolsModule>(
() => import("./bash-tools.js"),
);
function loadBashToolsModule(): Promise<BashToolsModule> {
return bashToolsModuleLoader.load();
}
function createLazyExecTool(defaults?: ExecToolDefaults): AnyAgentTool {
let loadedTool: AnyAgentTool | undefined;
const loadTool = async () => {
if (!loadedTool) {
const { createExecTool } = await loadBashToolsModule();
loadedTool = createExecTool(defaults) as unknown as AnyAgentTool;
}
return loadedTool;
};
return {
name: "exec",
label: "exec",
displaySummary: EXEC_TOOL_DISPLAY_SUMMARY,
get description() {
return describeExecTool({
agentId: defaults?.agentId,
hasCronTool: defaults?.hasCronTool === true,
});
},
parameters: execSchema,
prepareBeforeToolCallParams: async (...args) =>
(await loadTool()).prepareBeforeToolCallParams?.(...args) ?? args[0],
finalizeBeforeToolCallParams: (params, preparedParams) =>
loadedTool?.finalizeBeforeToolCallParams?.(params, preparedParams) ?? params,
execute: async (...args: Parameters<AnyAgentTool["execute"]>) =>
(await loadTool()).execute(...args),
} as AnyAgentTool;
}
function createLazyProcessTool(defaults?: ProcessToolDefaults): AnyAgentTool {
let loadedTool: AnyAgentTool | undefined;
const loadTool = async () => {
if (!loadedTool) {
const { createProcessTool } = await loadBashToolsModule();
loadedTool = createProcessTool(defaults) as unknown as AnyAgentTool;
}
return loadedTool;
};
return {
name: "process",
label: "process",
displaySummary: PROCESS_TOOL_DISPLAY_SUMMARY,
description: describeProcessTool({ hasCronTool: defaults?.hasCronTool === true }),
parameters: processSchema,
execute: async (...args: Parameters<AnyAgentTool["execute"]>) =>
(await loadTool()).execute(...args),
} as AnyAgentTool;
}
/** Resolve the process-tool isolation key for exec/process session state. */
export function resolveProcessToolScopeKey(params: {
scopeKey?: string;
sessionKey?: string;
sessionId?: string;
agentId?: string;
}): string | undefined {
const explicitScopeKey = params.scopeKey?.trim();
if (explicitScopeKey) {
return explicitScopeKey;
}
const sessionKey = params.sessionKey?.trim();
if (sessionKey) {
return sessionKey;
}
const sessionId = params.sessionId?.trim();
if (sessionId) {
return sessionId;
}
const agentId = params.agentId?.trim();
return agentId ? `agent:${agentId}` : undefined;
}
function applyModelProviderToolPolicy(
toolsInput: AnyAgentTool[],
params?: {
config?: OpenClawConfig;
modelProvider?: string;
modelApi?: string;
modelId?: string;
agentId?: string;
sessionKey?: string;
agentDir?: string;
modelCompat?: ModelCompatConfig;
suppressManagedWebSearch?: boolean;
runtimeToolAllowlist?: string[];
localModelLeanPreserveToolNames?: string[];
},
): AnyAgentTool[] {
let tools = toolsInput;
tools = filterLocalModelLeanTools({
tools,
config: params?.config,
agentId: params?.agentId,
sessionKey: params?.sessionKey,
preserveToolNames: params?.localModelLeanPreserveToolNames ?? params?.runtimeToolAllowlist,
});
if (
params?.suppressManagedWebSearch !== false &&
shouldSuppressManagedWebSearchTool({
config: params?.config,
modelProvider: params?.modelProvider,
modelApi: params?.modelApi,
modelId: params?.modelId,
agentId: params?.agentId,
sessionKey: params?.sessionKey,
agentDir: params?.agentDir,
})
) {
return tools.filter((tool) => tool.name !== "web_search");
}
return tools;
}
function isApplyPatchAllowedForModel(params: {
modelProvider?: string;
modelId?: string;
allowModels?: string[];
}) {
const allowModels = Array.isArray(params.allowModels) ? params.allowModels : [];
if (allowModels.length === 0) {
return true;
}
const modelId = params.modelId?.trim();
if (!modelId) {
return false;
}
const normalizedModelId = normalizeLowercaseStringOrEmpty(modelId);
const provider = normalizeOptionalLowercaseString(params.modelProvider);
const normalizedFull =
provider && !normalizedModelId.includes("/")
? `${provider}/${normalizedModelId}`
: normalizedModelId;
return allowModels.some((entry) => {
const normalized = normalizeOptionalLowercaseString(entry);
if (!normalized) {
return false;
}
return normalized === normalizedModelId || normalized === normalizedFull;
});
}
function resolveExecConfig(params: { cfg?: OpenClawConfig; agentId?: string }) {
const cfg = params.cfg;
const globalExec = cfg?.tools?.exec;
const agentExec =
cfg && params.agentId ? resolveAgentConfig(cfg, params.agentId)?.tools?.exec : undefined;
const layeredPolicy = applyExecPolicyLayer(applyExecPolicyLayer({}, globalExec), agentExec);
return {
host: agentExec?.host ?? globalExec?.host,
mode: layeredPolicy.mode,
security: layeredPolicy.security,
ask: layeredPolicy.ask,
node: agentExec?.node ?? globalExec?.node,
pathPrepend: agentExec?.pathPrepend ?? globalExec?.pathPrepend,
safeBins: agentExec?.safeBins ?? globalExec?.safeBins,
strictInlineEval: agentExec?.strictInlineEval ?? globalExec?.strictInlineEval,
commandHighlighting: resolveExecCommandHighlighting({
config: cfg,
agentId: params.agentId,
}),
safeBinTrustedDirs: agentExec?.safeBinTrustedDirs ?? globalExec?.safeBinTrustedDirs,
safeBinProfiles: resolveMergedSafeBinProfileFixtures({
global: globalExec,
local: agentExec,
}),
reviewer: agentExec?.reviewer ?? globalExec?.reviewer,
backgroundMs: agentExec?.backgroundMs ?? globalExec?.backgroundMs,
timeoutSec: agentExec?.timeoutSec ?? globalExec?.timeoutSec,
approvalRunningNoticeMs:
agentExec?.approvalRunningNoticeMs ?? globalExec?.approvalRunningNoticeMs,
cleanupMs: agentExec?.cleanupMs ?? globalExec?.cleanupMs,
notifyOnExit: agentExec?.notifyOnExit ?? globalExec?.notifyOnExit,
notifyOnExitEmptySuccess:
agentExec?.notifyOnExitEmptySuccess ?? globalExec?.notifyOnExitEmptySuccess,
applyPatch: agentExec?.applyPatch ?? globalExec?.applyPatch,
};
}
export { resolveToolLoopDetectionConfig } from "./tool-loop-detection-config.js";
/** Test-only access to internal tool assembly helpers. */
export const testing = {
getToolParamsRecord,
wrapToolParamValidation,
assertRequiredParams,
applyModelProviderToolPolicy,
} as const;
export type OpenClawCodingToolConstructionPlan = {
includeBaseCodingTools: boolean;
includeShellTools: boolean;
includeChannelTools: boolean;
includeOpenClawTools: boolean;
includePluginTools: boolean;
};
/** Build the runtime tool list for one agent run. */
export function createOpenClawCodingTools(options?: {
agentId?: string;
exec?: ExecToolDefaults & ProcessToolDefaults;
messageProvider?: string;
/** Canonical transport channel when tool-policy provider differs from delivery channel. */
messageChannel?: string;
/** Specific ingress provider used only for transport tool availability. */
toolPolicyMessageProvider?: string;
agentAccountId?: string;
messageTo?: string;
messageThreadId?: string | number;
sandbox?: SandboxContext | null;
sessionKey?: string;
/**
* The actual live run session key. When the tool set is constructed with a
* sandbox/policy session key, this allows `session_status({sessionKey:"current"})`
* to resolve to the live run session instead of the stale sandbox key.
*/
runSessionKey?: string;
/** Ephemeral session UUID — regenerated on /new and /reset. */
sessionId?: string;
/**
* Explicit one-shot local CLI runs should not keep plugin-owned process
* resources alive after emitting their result.
*/
oneShotCliRun?: boolean;
/** Stable run identifier for this agent invocation. */
runId?: string;
/** Device-scoped operator session allowed to review approvals initiated by this run. */
approvalReviewerDeviceId?: string;
/** Diagnostic trace context for hook/log correlation during this run. */
trace?: DiagnosticTraceContext;
/** What initiated this run (for trigger-specific tool restrictions). */
trigger?: string;
/** Stable cron job identifier populated for cron-triggered runs. */
jobId?: string;
/** Relative workspace path that memory-triggered writes may append to. */
memoryFlushWritePath?: string;
agentDir?: string;
/** Task working directory for coding tools. Defaults to workspaceDir. */
cwd?: string;
workspaceDir?: string;
/**
* Workspace directory that spawned subagents should inherit.
* When sandboxing uses a copied workspace (`ro` or `none`), workspaceDir is the
* sandbox copy but subagents should inherit the real agent workspace instead.
* Defaults to workspaceDir when not set.
*/
spawnWorkspaceDir?: string;
config?: OpenClawConfig;
abortSignal?: AbortSignal;
/** Disable hook-owned diagnostics when an outer runtime owns tool diagnostics. */
emitBeforeToolCallDiagnostics?: boolean;
/**
* Provider of the currently selected model (used for provider-specific tool quirks).
* Example: "anthropic", "openai", "google", "openai".
*/
modelProvider?: string;
/** Model id for the current provider (used for model-specific tool gating). */
modelId?: string;
/** Model API for the current provider (used for provider-native tool arbitration). */
modelApi?: string;
/** Model context window in tokens (used to scale read-tool output budget). */
modelContextWindowTokens?: number;
/** Resolved runtime model compatibility hints. */
modelCompat?: ModelCompatConfig;
/** If false, keep OpenClaw web_search even when a provider-native search tool is active. */
suppressManagedWebSearch?: boolean;
/**
* Auth mode for the current provider. We only need this for Anthropic OAuth
* tool-name blocking quirks.
*/
modelAuthMode?: ModelAuthMode;
/** Current channel ID for auto-threading (Slack). */
currentChannelId?: string;
/** Routable target for the current conversation when it differs from the native channel ID. */
currentMessagingTarget?: string;
/** Normalized conversation id exposed to tool hooks. Defaults to currentChannelId. */
hookChannelId?: string;
/** Channel-owned sender/chat metadata exposed to subprocess environments. */
channelContext?: PluginHookChannelContext;
/** Current thread timestamp for auto-threading (Slack). */
currentThreadTs?: string;
/** Current inbound message id for action fallbacks (e.g. Telegram react). */
currentMessageId?: string | number;
/** True when the current inbound turn carried audio media. */
currentInboundAudio?: boolean;
/** Group id for channel-level tool policy resolution. */
groupId?: string | null;
/** Group channel label (e.g. #general) for channel-level tool policy resolution. */
groupChannel?: string | null;
/** Group space label (e.g. guild/team id) for channel-level tool policy resolution. */
groupSpace?: string | null;
/** Trusted provider role ids for the requester in this group turn. */
memberRoleIds?: string[];
/** Parent session key for subagent group policy inheritance. */
spawnedBy?: string | null;
senderId?: string | null;
senderName?: string | null;
senderUsername?: string | null;
senderE164?: string | null;
/** Reply-to mode for Slack auto-threading. */
replyToMode?: "off" | "first" | "all" | "batched";
/** Mutable ref to track if a reply was sent (for "first" mode). */
hasRepliedRef?: { value: boolean };
/** Allow plugin tools for this run to late-bind the gateway subagent. */
allowGatewaySubagentBinding?: boolean;
/** Runtime-scoped explicit allowlist used to materialize matching plugin tools. */
runtimeToolAllowlist?: string[];
/** Mutable cron creator cap ref for callers that append final runtime tools later. */
cronCreatorToolAllowlistRef?: CronCreatorToolAllowlistEntry[];
/** If true, the model has native vision capability */
modelHasVision?: boolean;
/** Require explicit message targets (no implicit last-route sends). */
requireExplicitMessageTarget?: boolean;
/** Visible source replies must be sent through the message tool when set to message_tool_only. */
sourceReplyDeliveryMode?: SourceReplyDeliveryMode;
inboundEventKind?: InboundEventKind;
/** If true, omit the message tool from the tool list. */
disableMessageTool?: boolean;
/** Keep the message tool available even when the selected profile omits it. */
forceMessageTool?: boolean;
/** Include the heartbeat response tool for structured heartbeat outcomes. */
enableHeartbeatTool?: boolean;
/** Keep the heartbeat response tool available even when the selected profile omits it. */
forceHeartbeatTool?: boolean;
/** If false, build plugin tools only while preserving the shared policy pipeline. */
includeCoreTools?: boolean;
/** Include Tool Search control tools when enabled for this run. */
includeToolSearchControls?: boolean;
/** Executes cataloged tools through the active agent run lifecycle. */
toolSearchCatalogExecutor?: ToolSearchCatalogToolExecutor;
/** Runtime-local Tool Search catalog ref shared with attempt compaction. */
toolSearchCatalogRef?: ToolSearchCatalogRef;
/** Limits which tool families are materialized before the shared policy pipeline runs. */
toolConstructionPlan?: OpenClawCodingToolConstructionPlan;
/** Trusted sender identity bit for command/channel-action auth; does not filter model tools. */
senderIsOwner?: boolean;
/** Auth profiles already loaded for this run; used for prompt-time tool availability. */
authProfileStore?: AuthProfileStore;
/** Callback invoked when sessions_yield tool is called. */
onYield?: (message: string) => Promise<void> | void;
/** Optional instrumentation callback for tool preparation stage timing. */
recordToolPrepStage?: (name: string) => void;
/** Lower routine policy-removal audits for diagnostic-only tool probes. */
toolPolicyAuditLogLevel?: "info" | "debug";
/** Live observer called after wrapped tool outcomes are recorded. */
onToolOutcome?: ToolOutcomeObserver;
/** Supplies run-global model-call ordering for parallel tool outcomes. */
allocateToolOutcomeOrdinal?: (toolCallId?: string) => number;
/** Runtime-only resolved skill paths that the read tool may load under workspaceOnly. */
skillsSnapshot?: SkillSnapshot;
}): AnyAgentTool[] {
const execToolName = "exec";
const sandbox = options?.sandbox?.enabled ? options.sandbox : undefined;
const isMemoryFlushRun = options?.trigger === "memory";
if (isMemoryFlushRun && !options?.memoryFlushWritePath) {
throw new Error("memoryFlushWritePath required for memory-triggered tool runs");
}
const memoryFlushWritePath = isMemoryFlushRun ? options.memoryFlushWritePath : undefined;
const cronSelfRemoveOnlyJobId =
options?.trigger === "cron" && options.jobId?.trim() ? options.jobId.trim() : undefined;
const {
agentId,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
profile,
providerProfile,
profileAlsoAllow,
providerProfileAlsoAllow,
} = resolveEffectiveToolPolicy({
config: options?.config,
sessionKey: options?.sessionKey,
agentId: options?.agentId,
modelProvider: options?.modelProvider,
modelId: options?.modelId,
});
// Prefer the already-resolved sandbox context policy. Recomputing from
// sessionKey/config can lose the real sandbox agent when callers pass a
// legacy alias like `main` instead of an agent session key.
const sandboxToolPolicy = sandbox?.tools;
const groupPolicy = resolveGroupToolPolicy({
config: options?.config,
sessionKey: options?.sessionKey,
spawnedBy: options?.spawnedBy,
messageProvider: options?.messageProvider,
groupId: options?.groupId,
groupChannel: options?.groupChannel,
groupSpace: options?.groupSpace,
accountId: options?.agentAccountId,
senderId: options?.senderId,
senderName: options?.senderName,
senderUsername: options?.senderUsername,
senderE164: options?.senderE164,
});
const senderPolicy = resolveSenderToolPolicy({
config: options?.config,
agentId,
messageProvider: options?.messageProvider,
senderId: options?.senderId,
senderName: options?.senderName,
senderUsername: options?.senderUsername,
senderE164: options?.senderE164,
});
const profilePolicy = resolveToolProfilePolicy(profile);
const providerProfilePolicy = resolveToolProfilePolicy(providerProfile);
const enableHeartbeatTool =
options?.enableHeartbeatTool === true ||
(options?.trigger === "heartbeat" &&
options?.config?.messages?.visibleReplies === "message_tool");
const forceHeartbeatTool = options?.forceHeartbeatTool === true || enableHeartbeatTool;
const toolSearchConfig = resolveToolSearchConfig(options?.config);
const toolSearchControlsEnabled =
options?.includeToolSearchControls === true && toolSearchConfig.enabled;
const toolSearchControlAllowlist = toolSearchControlsEnabled
? [
TOOL_SEARCH_CODE_MODE_TOOL_NAME,
TOOL_SEARCH_RAW_TOOL_NAME,
TOOL_DESCRIBE_RAW_TOOL_NAME,
TOOL_CALL_RAW_TOOL_NAME,
]
: [];
const mergeToolSearchControlAllowlist = <TPolicy extends { allow?: string[] }>(
policy: TPolicy | undefined,
) => mergeAlsoAllowPolicy(policy, toolSearchControlAllowlist);
const runtimeToolAllowlistIncludesMessage = expandToolGroups(
options?.runtimeToolAllowlist ?? [],
).some((toolName) => {
const normalized = normalizeToolName(toolName);
return normalized === "*" || normalized === "message";
});
const localModelLeanPreserveToolNames = resolveLocalModelLeanPreserveToolNames({
toolNames: options?.runtimeToolAllowlist,
forceMessageTool: options?.forceMessageTool,
sourceReplyDeliveryMode: options?.sourceReplyDeliveryMode,
});
const runtimeProfileAlsoAllow = [
...(options?.forceMessageTool || options?.sourceReplyDeliveryMode === "message_tool_only"
? ["message"]
: []),
...(runtimeToolAllowlistIncludesMessage ? ["message"] : []),
...(forceHeartbeatTool ? [HEARTBEAT_RESPONSE_TOOL_NAME] : []),
...toolSearchControlAllowlist,
];
const profilePolicyWithAlsoAllow = mergeAlsoAllowPolicy(profilePolicy, [
...(profileAlsoAllow ?? []),
...runtimeProfileAlsoAllow,
]);
const providerProfilePolicyWithAlsoAllow = mergeAlsoAllowPolicy(providerProfilePolicy, [
...(providerProfileAlsoAllow ?? []),
...runtimeProfileAlsoAllow,
]);
// Prefer sessionKey for process isolation scope to prevent cross-session process visibility/killing.
// Fallback to agentId if no sessionKey is available (e.g. legacy or global contexts).
const scopeKey = resolveProcessToolScopeKey({
scopeKey: options?.exec?.scopeKey,
sessionKey: options?.sessionKey,
sessionId: options?.sessionId,
agentId,
});
const subagentStore = resolveSubagentCapabilityStore(options?.sessionKey, {
cfg: options?.config,
});
const subagentPolicy =
options?.sessionKey &&
isSubagentEnvelopeSession(options.sessionKey, {
cfg: options.config,
store: subagentStore,
})
? resolveSubagentToolPolicyForSession(options.config, options.sessionKey, {
store: subagentStore,
})
: undefined;
const inheritedToolPolicy = resolveInheritedToolPolicyForSession(
options?.config,
options?.sessionKey,
{
store: subagentStore,
},
);
const globalPolicyWithToolSearchControls = mergeToolSearchControlAllowlist(globalPolicy);
const globalProviderPolicyWithToolSearchControls =
mergeToolSearchControlAllowlist(globalProviderPolicy);
const agentPolicyWithToolSearchControls = mergeToolSearchControlAllowlist(agentPolicy);
const agentProviderPolicyWithToolSearchControls =
mergeToolSearchControlAllowlist(agentProviderPolicy);
const groupPolicyWithToolSearchControls = mergeToolSearchControlAllowlist(groupPolicy);
const senderPolicyWithToolSearchControls = mergeToolSearchControlAllowlist(senderPolicy);
const sandboxToolPolicyWithToolSearchControls =
mergeToolSearchControlAllowlist(sandboxToolPolicy);
const subagentPolicyWithToolSearchControls = mergeToolSearchControlAllowlist(subagentPolicy);
const allowBackground = isToolAllowedByPolicies("process", [
profilePolicyWithAlsoAllow,
providerProfilePolicyWithAlsoAllow,
globalPolicyWithToolSearchControls,
globalProviderPolicyWithToolSearchControls,
agentPolicyWithToolSearchControls,
agentProviderPolicyWithToolSearchControls,
groupPolicyWithToolSearchControls,
senderPolicyWithToolSearchControls,
sandboxToolPolicyWithToolSearchControls,
subagentPolicyWithToolSearchControls,
inheritedToolPolicy,
]);
options?.recordToolPrepStage?.("tool-policy");
const execConfig = resolveExecConfig({ cfg: options?.config, agentId });
const fsConfig = resolveToolFsConfig({ cfg: options?.config, agentId });
const fsPolicy = createToolFsPolicy({
workspaceOnly: isMemoryFlushRun || fsConfig.workspaceOnly,
});
const sandboxRoot = sandbox?.workspaceDir;
const sandboxFsBridge = sandbox?.fsBridge;
const allowWorkspaceWrites = sandbox?.workspaceAccess !== "ro";
const workspaceRoot = resolveWorkspaceRoot(options?.workspaceDir);
const runtimeRoot = resolveWorkspaceRoot(options?.cwd ?? options?.workspaceDir);
const codingRoot = sandboxRoot ?? runtimeRoot;
const memoryFlushWriteRoot = sandboxRoot ?? workspaceRoot;
const includeCoreTools = options?.includeCoreTools !== false;
const toolConstructionPlan = options?.toolConstructionPlan ?? {
includeBaseCodingTools: includeCoreTools,
includeShellTools: includeCoreTools,
includeChannelTools: includeCoreTools,
includeOpenClawTools: includeCoreTools,
includePluginTools: true,
};
const includeBaseCodingTools = includeCoreTools && toolConstructionPlan.includeBaseCodingTools;
const includeShellTools = includeCoreTools && toolConstructionPlan.includeShellTools;
const includeOpenClawTools = includeCoreTools && toolConstructionPlan.includeOpenClawTools;
const includeChannelTools = toolConstructionPlan.includeChannelTools;
const includePluginTools = toolConstructionPlan.includePluginTools;
const workspaceOnly = fsPolicy.workspaceOnly;
const skillReadRoots = sandboxRoot ? undefined : resolveSkillReadRoots(options?.skillsSnapshot);
const applyPatchConfig = execConfig.applyPatch;
// Secure by default: apply_patch is workspace-contained unless explicitly disabled.
// (tools.fs.workspaceOnly is a separate umbrella flag for read/write/edit/apply_patch.)
const applyPatchWorkspaceOnly = workspaceOnly || applyPatchConfig?.workspaceOnly !== false;
const applyPatchEnabled =
applyPatchConfig?.enabled !== false &&
isApplyPatchAllowedForModel({
modelProvider: options?.modelProvider,
modelId: options?.modelId,
allowModels: applyPatchConfig?.allowModels,
});
if (sandboxRoot && !sandboxFsBridge) {
throw new Error("Sandbox filesystem bridge is unavailable.");
}
const imageSanitization = resolveImageSanitizationLimits(options?.config);
options?.recordToolPrepStage?.("workspace-policy");
const base: AnyAgentTool[] = [];
if (includeBaseCodingTools) {
for (const tool of createCodingTools(codingRoot) as unknown as AnyAgentTool[]) {
if (tool.name === "read") {
if (sandboxRoot) {
const sandboxed = createSandboxedReadTool({
root: sandboxRoot,
bridge: sandboxFsBridge!,
modelContextWindowTokens: options?.modelContextWindowTokens,
imageSanitization,
});
base.push(
workspaceOnly
? wrapToolWorkspaceRootGuardWithOptions(sandboxed, sandboxRoot, {
additionalContainerMounts: readOnlySandboxReadMounts(sandbox),
containerWorkdir: sandbox.containerWorkdir,
})
: sandboxed,
);
continue;
}
const freshReadTool = createReadTool(codingRoot);
const wrapped = createOpenClawReadTool(freshReadTool, {
modelContextWindowTokens: options?.modelContextWindowTokens,
imageSanitization,
});
base.push(
workspaceOnly
? wrapToolWorkspaceRootGuardWithOptions(wrapped, codingRoot, {
additionalRoots: skillReadRoots,
})
: wrapped,
);
continue;
}
if (tool.name === "bash" || tool.name === execToolName) {
continue;
}
if (tool.name === "write") {
if (sandboxRoot) {
continue;
}
const wrapped = createHostWorkspaceWriteTool(codingRoot, { workspaceOnly });
base.push(workspaceOnly ? wrapToolWorkspaceRootGuard(wrapped, codingRoot) : wrapped);
continue;
}
if (tool.name === "edit") {
if (sandboxRoot) {
continue;
}
const wrapped = createHostWorkspaceEditTool(codingRoot, { workspaceOnly });
base.push(workspaceOnly ? wrapToolWorkspaceRootGuard(wrapped, codingRoot) : wrapped);
continue;
}
base.push(tool);
}
}
options?.recordToolPrepStage?.("base-coding-tools");
const { cleanupMs: cleanupMsOverride, ...execDefaults } = options?.exec ?? {};
const effectiveExecPolicy = applyExecPolicyLayer(execConfig, options?.exec);
const execTool = includeShellTools
? createLazyExecTool({
...execDefaults,
host: options?.exec?.host ?? execConfig.host,
mode: effectiveExecPolicy.mode,
security: effectiveExecPolicy.security,
ask: effectiveExecPolicy.ask,
config: options?.exec?.config ?? options?.config,
reviewer: options?.exec?.reviewer ?? execConfig.reviewer,
trigger: options?.trigger,
node: options?.exec?.node ?? execConfig.node,
pathPrepend: options?.exec?.pathPrepend ?? execConfig.pathPrepend,
safeBins: options?.exec?.safeBins ?? execConfig.safeBins,
strictInlineEval: options?.exec?.strictInlineEval ?? execConfig.strictInlineEval,
commandHighlighting: options?.exec?.commandHighlighting ?? execConfig.commandHighlighting,
safeBinTrustedDirs: options?.exec?.safeBinTrustedDirs ?? execConfig.safeBinTrustedDirs,
safeBinProfiles: options?.exec?.safeBinProfiles ?? execConfig.safeBinProfiles,
agentId,
cwd: codingRoot,
allowBackground,
scopeKey,
sessionKey: options?.sessionKey,
sessionId: options?.sessionId,
sessionStore: options?.config?.session?.store,
mainKey: options?.config?.session?.mainKey,
sessionScope: options?.config?.session?.scope,
eventRouting: resolveEventSessionRoutingPolicy({
cfg: options?.config,
sessionKey: options?.sessionKey,
channel: options?.messageProvider,
accountId: options?.agentAccountId,
}),
messageProvider: options?.messageProvider,
currentChannelId: options?.currentChannelId,
currentThreadTs: options?.currentThreadTs,
channelContext: options?.channelContext,
accountId: options?.agentAccountId,
approvalReviewerDeviceId: options?.approvalReviewerDeviceId,
backgroundMs: options?.exec?.backgroundMs ?? execConfig.backgroundMs,
timeoutSec: options?.exec?.timeoutSec ?? execConfig.timeoutSec,
approvalRunningNoticeMs:
options?.exec?.approvalRunningNoticeMs ?? execConfig.approvalRunningNoticeMs,
notifyOnExit: options?.exec?.notifyOnExit ?? execConfig.notifyOnExit,
notifyOnExitEmptySuccess:
options?.exec?.notifyOnExitEmptySuccess ?? execConfig.notifyOnExitEmptySuccess,
sandbox: sandbox
? {
containerName: sandbox.containerName,
workspaceDir: sandbox.workspaceDir,
containerWorkdir: sandbox.containerWorkdir,
workdirValidation: sandbox.backend?.workdirValidation,
validateWorkdir: sandbox.backend?.validateWorkdir?.bind(sandbox.backend),
discardPreparedWorkdir: sandbox.backend?.discardPreparedWorkdir?.bind(
sandbox.backend,
),
workdirRoots: sandbox.backend?.workdirRoots,
env: sandbox.backend?.env ?? sandbox.docker.env,
buildExecSpec: sandbox.backend?.buildExecSpec.bind(sandbox.backend),
finalizeExec: sandbox.backend?.finalizeExec?.bind(sandbox.backend),
}
: undefined,
})
: null;
const processTool = includeShellTools
? createLazyProcessTool({
cleanupMs: cleanupMsOverride ?? execConfig.cleanupMs,
scopeKey,
})
: null;
const applyPatchTool =
!includeShellTools || !applyPatchEnabled || (sandboxRoot && !allowWorkspaceWrites)
? null
: createApplyPatchTool({
cwd: codingRoot,
sandbox:
sandboxRoot && allowWorkspaceWrites
? { root: sandboxRoot, bridge: sandboxFsBridge! }
: undefined,
workspaceOnly: applyPatchWorkspaceOnly,
});
options?.recordToolPrepStage?.("shell-tools");
const pluginToolAllowlist = collectExplicitAllowlist([
profilePolicy,
providerProfilePolicy,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
groupPolicy,
senderPolicy,
sandboxToolPolicy,
subagentPolicy,
inheritedToolPolicy,
options?.runtimeToolAllowlist ? { allow: options.runtimeToolAllowlist } : undefined,
]);
const pluginToolDenylist = collectExplicitDenylist([
profilePolicy,
providerProfilePolicy,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
groupPolicy,
senderPolicy,
sandboxToolPolicy,
subagentPolicy,
inheritedToolPolicy,
]);
const inheritedToolDenylist = [...pluginToolDenylist];
// Passed by reference to sessions_spawn and populated after the final policy
// pass so child sessions inherit the actual parent tool surface.
const inheritedToolAllowlist: string[] = [];
const toolPolicyInheritanceSources = [
profilePolicy,
providerProfilePolicy,
globalPolicy,
globalProviderPolicy,
agentPolicy,
agentProviderPolicy,
groupPolicy,
senderPolicy,
sandboxToolPolicy,
subagentPolicy,
inheritedToolPolicy,
options?.runtimeToolAllowlist ? { allow: options.runtimeToolAllowlist } : undefined,
];
const shouldInheritEffectiveToolAllowlist =
toolPolicyInheritanceSources.some(hasRestrictiveAllowPolicy);
const cronCreatorToolAllowlist = options?.cronCreatorToolAllowlistRef ?? [];
const shouldCaptureCronCreatorToolAllowlist = toolPolicyInheritanceSources.some(
(policy) => hasRestrictiveAllowPolicy(policy) || hasExplicitDenyPolicy(policy),
);
const pluginToolsOnly =
includeOpenClawTools || !includePluginTools
? []
: resolveOpenClawPluginToolsForOptions({
options: {
agentSessionKey: options?.sessionKey,
agentChannel: resolveGatewayMessageChannel(options?.messageProvider),
agentAccountId: options?.agentAccountId,
agentTo: options?.messageTo,
agentThreadId: options?.messageThreadId,
agentDir: options?.agentDir,
workspaceDir: workspaceRoot,
config: options?.config,
fsPolicy,
requesterSenderId: options?.senderId,
sessionId: options?.sessionId,
oneShotCliRun: options?.oneShotCliRun,
sandboxBrowserBridgeUrl: sandbox?.browser?.bridgeUrl,
allowHostBrowserControl: sandbox ? sandbox.browserAllowHostControl : true,
sandboxed: Boolean(sandbox),
pluginToolAllowlist,
pluginToolDenylist,
currentChannelId: options?.currentChannelId,
currentMessagingTarget: options?.currentMessagingTarget,
currentThreadTs: options?.currentThreadTs,
currentMessageId: options?.currentMessageId,
modelProvider: options?.modelProvider,
modelId: options?.modelId,
modelHasVision: options?.modelHasVision,
requireExplicitMessageTarget: options?.requireExplicitMessageTarget,
disableMessageTool: options?.disableMessageTool,
requesterAgentIdOverride: agentId,
allowGatewaySubagentBinding: options?.allowGatewaySubagentBinding,
authProfileStore: options?.authProfileStore,
},
resolvedConfig: options?.config,
});
const toolSearchTools = toolSearchControlsEnabled
? createToolSearchTools({
config: options?.config,
runtimeConfig: options?.config,
agentId,
sessionKey: options?.sessionKey,
sessionId: options?.sessionId,
runId: options?.runId,
catalogRef: options?.toolSearchCatalogRef,
abortSignal: options?.abortSignal,
executeTool: options?.toolSearchCatalogExecutor,
})
: [];
const tools: AnyAgentTool[] = [
...base,
...(includeBaseCodingTools && sandboxRoot
? allowWorkspaceWrites
? [
workspaceOnly
? wrapToolWorkspaceRootGuardWithOptions(
createSandboxedEditTool({ root: sandboxRoot, bridge: sandboxFsBridge! }),
sandboxRoot,
{
containerWorkdir: sandbox.containerWorkdir,
},