chainlesschain 0.45.70 → 0.45.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/assets/web-panel/.build-hash +1 -1
- package/src/assets/web-panel/assets/Analytics-B4OM8S8X.css +1 -0
- package/src/assets/web-panel/assets/Analytics-sBrYoc3A.js +3 -0
- package/src/assets/web-panel/assets/AppLayout-2RCrdXxl.js +1 -0
- package/src/assets/web-panel/assets/AppLayout-D9pBLPC3.css +1 -0
- package/src/assets/web-panel/assets/Backup-D68fenbD.js +1 -0
- package/src/assets/web-panel/assets/Backup-fZqtfC1m.css +1 -0
- package/src/assets/web-panel/assets/{Chat-DXtvKoM0.js → Chat-B2nB8o_F.js} +1 -1
- package/src/assets/web-panel/assets/{Cron-BJ4ODHOy.js → Cron-CNs03iHJ.js} +2 -2
- package/src/assets/web-panel/assets/{Dashboard-BZd4wDPQ.js → Dashboard-DanoHPSI.js} +2 -2
- package/src/assets/web-panel/assets/Git-CCMVr3Y8.js +2 -0
- package/src/assets/web-panel/assets/Git-DGcuBXST.css +1 -0
- package/src/assets/web-panel/assets/{Logs-CSeKZEG_.js → Logs-BY6A0UNG.js} +2 -2
- package/src/assets/web-panel/assets/{McpTools-BYQAK11r.js → McpTools-CrBVYlg6.js} +2 -2
- package/src/assets/web-panel/assets/{Memory-gkUAPyuZ.js → Memory-CWx3SpUt.js} +2 -2
- package/src/assets/web-panel/assets/{Notes-bjNrQgAo.js → Notes-1LcGD49x.js} +2 -2
- package/src/assets/web-panel/assets/Organization-DdOOM4ic.css +1 -0
- package/src/assets/web-panel/assets/Organization-Dx2DhbkM.js +4 -0
- package/src/assets/web-panel/assets/P2P-B16fjqfJ.js +2 -0
- package/src/assets/web-panel/assets/P2P-OEzOeMZX.css +1 -0
- package/src/assets/web-panel/assets/Permissions-BQbC9FzG.js +4 -0
- package/src/assets/web-panel/assets/Permissions-C9WlkGl-.css +1 -0
- package/src/assets/web-panel/assets/Projects-CjhZbNYm.js +2 -0
- package/src/assets/web-panel/assets/Projects-DxKelI5h.css +1 -0
- package/src/assets/web-panel/assets/Providers-BEakqcO5.css +1 -0
- package/src/assets/web-panel/assets/Providers-ivOAQtHM.js +2 -0
- package/src/assets/web-panel/assets/RssFeed-BlFC20eg.css +1 -0
- package/src/assets/web-panel/assets/RssFeed-BrsErdrU.js +3 -0
- package/src/assets/web-panel/assets/Security-DnEvJU5h.js +4 -0
- package/src/assets/web-panel/assets/Security-Dwxw7rfP.css +1 -0
- package/src/assets/web-panel/assets/{Services-CS0oMdxh.js → Services-7jQywNbl.js} +2 -2
- package/src/assets/web-panel/assets/Skills-CLlblJcG.js +1 -0
- package/src/assets/web-panel/assets/{Tasks-qULws8pc.js → Tasks-CmJBC1cf.js} +1 -1
- package/src/assets/web-panel/assets/Templates-DOY_oZnm.css +1 -0
- package/src/assets/web-panel/assets/Templates-RXT8-DNk.js +1 -0
- package/src/assets/web-panel/assets/Wallet-3iYASEx_.js +4 -0
- package/src/assets/web-panel/assets/Wallet-DnIumafl.css +1 -0
- package/src/assets/web-panel/assets/WebAuthn-CNPl2VQR.css +1 -0
- package/src/assets/web-panel/assets/WebAuthn-s3Hzd9db.js +5 -0
- package/src/assets/web-panel/assets/{antd-CJSBocer.js → antd-gZyc63Qr.js} +114 -114
- package/src/assets/web-panel/assets/chat-DWBA4-cl.js +1 -0
- package/src/assets/web-panel/assets/index-CyGtHm63.js +2 -0
- package/src/assets/web-panel/assets/{markdown-Bo5cVN4u.js → markdown-Bv7nG63L.js} +1 -1
- package/src/assets/web-panel/assets/ws-CU7Gvoom.js +1 -0
- package/src/assets/web-panel/index.html +2 -2
- package/src/commands/doctor.js +33 -151
- package/src/commands/mcp.js +1 -1
- package/src/commands/plugin.js +1 -1
- package/src/commands/session.js +106 -7
- package/src/commands/status.js +39 -69
- package/src/gateways/ws/session-protocol.js +1 -1
- package/src/gateways/ws/ws-agent-handler.js +484 -0
- package/src/gateways/ws/ws-server.js +758 -4
- package/src/gateways/ws/ws-session-gateway.js +1432 -1
- package/src/harness/mcp-client.js +417 -0
- package/src/harness/mock-llm-provider.js +167 -0
- package/src/harness/plugin-manager.js +434 -0
- package/src/lib/agent-core.js +25 -1902
- package/src/lib/hashline.js +208 -0
- package/src/lib/jsonl-session-store.js +11 -0
- package/src/lib/mcp-client.js +14 -412
- package/src/lib/plugin-manager.js +29 -428
- package/src/lib/prompt-compressor.js +11 -0
- package/src/lib/session-hooks.js +61 -0
- package/src/lib/skill-loader.js +4 -0
- package/src/lib/skill-mcp.js +190 -0
- package/src/lib/workflow-state-reader.js +94 -0
- package/src/lib/ws-agent-handler.js +8 -472
- package/src/lib/ws-server.js +12 -756
- package/src/lib/ws-session-manager.js +8 -1417
- package/src/repl/agent-repl.js +27 -3
- package/src/runtime/agent-core.js +1760 -0
- package/src/runtime/agent-runtime.js +3 -1
- package/src/runtime/coding-agent-contract-shared.cjs +496 -0
- package/src/runtime/coding-agent-contract.js +49 -229
- package/src/runtime/coding-agent-policy.cjs +54 -5
- package/src/runtime/diagnostics.js +317 -0
- package/src/runtime/index.js +3 -0
- package/src/tools/index.js +3 -0
- package/src/tools/legacy-agent-tools.js +5 -0
- package/src/assets/web-panel/assets/AppLayout-B_tkw3Pn.js +0 -1
- package/src/assets/web-panel/assets/AppLayout-CFP4dGIJ.css +0 -1
- package/src/assets/web-panel/assets/Providers-Brm-S_hS.css +0 -1
- package/src/assets/web-panel/assets/Providers-Dbf57Tbv.js +0 -1
- package/src/assets/web-panel/assets/Skills-B2fgruv8.js +0 -1
- package/src/assets/web-panel/assets/chat-DnH09sSR.js +0 -1
- package/src/assets/web-panel/assets/index-IK-oro0g.js +0 -2
- package/src/assets/web-panel/assets/ws-DjelKkD6.js +0 -1
|
@@ -0,0 +1,1760 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent Core — transport-independent agentic logic
|
|
3
|
+
*
|
|
4
|
+
* Canonical location (Phase 6b of the CLI Runtime Convergence roadmap,
|
|
5
|
+
* 2026-04-09). Previously lived at `../lib/agent-core.js`; that path is
|
|
6
|
+
* retained as an `@deprecated` re-export shim for backwards compatibility.
|
|
7
|
+
*
|
|
8
|
+
* Key exports:
|
|
9
|
+
* - AGENT_TOOLS — OpenAI function-calling tool definitions
|
|
10
|
+
* - getBaseSystemPrompt — system prompt generator
|
|
11
|
+
* - executeTool — tool execution with plan-mode + hook pipeline
|
|
12
|
+
* - chatWithTools — LLM call with tool definitions injected
|
|
13
|
+
* - agentLoop — async generator yielding structured events
|
|
14
|
+
* - formatToolArgs — human-readable tool argument formatting
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import fs from "fs";
|
|
18
|
+
import path from "path";
|
|
19
|
+
import { execSync } from "child_process";
|
|
20
|
+
import os from "os";
|
|
21
|
+
import sharedCodingAgentPolicy from "./coding-agent-policy.cjs";
|
|
22
|
+
import sharedShellPolicy from "./coding-agent-shell-policy.cjs";
|
|
23
|
+
import { getPlanModeManager } from "../lib/plan-mode.js";
|
|
24
|
+
import { CLISkillLoader } from "../lib/skill-loader.js";
|
|
25
|
+
import { executeHooks, HookEvents } from "../lib/hook-manager.js";
|
|
26
|
+
import { detectPython } from "../lib/cli-anything-bridge.js";
|
|
27
|
+
import { findProjectRoot, loadProjectConfig } from "../lib/project-detector.js";
|
|
28
|
+
import { SubAgentContext } from "../lib/sub-agent-context.js";
|
|
29
|
+
import {
|
|
30
|
+
createLegacyAgentToolRegistry,
|
|
31
|
+
getRuntimeToolDescriptorByCommand,
|
|
32
|
+
getRuntimeToolDescriptor,
|
|
33
|
+
} from "../tools/legacy-agent-tools.js";
|
|
34
|
+
import {
|
|
35
|
+
getCodingAgentFunctionToolDefinitions,
|
|
36
|
+
listCodingAgentToolNames,
|
|
37
|
+
} from "./coding-agent-contract.js";
|
|
38
|
+
import { createToolContext } from "../tools/tool-context.js";
|
|
39
|
+
import { createToolTelemetryRecord } from "../tools/tool-telemetry.js";
|
|
40
|
+
import { isAbortError, throwIfAborted } from "../lib/abort-utils.js";
|
|
41
|
+
import {
|
|
42
|
+
annotateLines,
|
|
43
|
+
replaceByHash,
|
|
44
|
+
snippetAround,
|
|
45
|
+
} from "../lib/hashline.js";
|
|
46
|
+
import {
|
|
47
|
+
mountSkillMcpServers,
|
|
48
|
+
unmountSkillMcpServers,
|
|
49
|
+
} from "../lib/skill-mcp.js";
|
|
50
|
+
|
|
51
|
+
const { isReadOnlyGitCommand, normalizeGitCommand } = sharedCodingAgentPolicy;
|
|
52
|
+
const { evaluateShellCommandPolicy } = sharedShellPolicy;
|
|
53
|
+
|
|
54
|
+
// ─── Tool definitions ────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
export const AGENT_TOOLS = getCodingAgentFunctionToolDefinitions();
|
|
57
|
+
|
|
58
|
+
const STATIC_AGENT_TOOL_NAMES = new Set(listCodingAgentToolNames());
|
|
59
|
+
|
|
60
|
+
export const AGENT_TOOL_REGISTRY = createLegacyAgentToolRegistry(AGENT_TOOLS);
|
|
61
|
+
|
|
62
|
+
function mergeToolDefinitions(baseTools = [], extraTools = []) {
|
|
63
|
+
const merged = new Map();
|
|
64
|
+
|
|
65
|
+
for (const tool of [...baseTools, ...extraTools]) {
|
|
66
|
+
const name = tool?.function?.name;
|
|
67
|
+
if (!name) continue;
|
|
68
|
+
merged.set(name, tool);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
return Array.from(merged.values());
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function getAgentToolDefinitions({
|
|
75
|
+
names = null,
|
|
76
|
+
disabledTools = [],
|
|
77
|
+
extraTools = [],
|
|
78
|
+
} = {}) {
|
|
79
|
+
const allowedNames =
|
|
80
|
+
Array.isArray(names) && names.length > 0 ? new Set(names) : null;
|
|
81
|
+
const disabledNames = new Set(
|
|
82
|
+
Array.isArray(disabledTools) ? disabledTools : [],
|
|
83
|
+
);
|
|
84
|
+
const extraToolNames = new Set(
|
|
85
|
+
(Array.isArray(extraTools) ? extraTools : [])
|
|
86
|
+
.map((tool) => tool?.function?.name)
|
|
87
|
+
.filter(Boolean),
|
|
88
|
+
);
|
|
89
|
+
const allTools = mergeToolDefinitions(
|
|
90
|
+
AGENT_TOOLS,
|
|
91
|
+
Array.isArray(extraTools) ? extraTools : [],
|
|
92
|
+
);
|
|
93
|
+
|
|
94
|
+
return allTools.filter((tool) => {
|
|
95
|
+
const name = tool?.function?.name;
|
|
96
|
+
if (!name) return false;
|
|
97
|
+
if (allowedNames && !allowedNames.has(name) && !extraToolNames.has(name)) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
if (disabledNames.has(name)) return false;
|
|
101
|
+
return true;
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function getAgentToolDescriptors(options = {}) {
|
|
106
|
+
const allowedNames = new Set(
|
|
107
|
+
getAgentToolDefinitions(options).map((tool) => tool.function.name),
|
|
108
|
+
);
|
|
109
|
+
return AGENT_TOOL_REGISTRY.list({ enabledOnly: options.enabledOnly }).filter(
|
|
110
|
+
(descriptor) => allowedNames.has(descriptor.name),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// ─── Shared skill loader ──────────────────────────────────────────────────
|
|
115
|
+
|
|
116
|
+
const _defaultSkillLoader = new CLISkillLoader();
|
|
117
|
+
|
|
118
|
+
// ─── Cached environment detection ────────────────────────────────────────
|
|
119
|
+
|
|
120
|
+
let _cachedPython = null;
|
|
121
|
+
let _cachedEnvInfo = null;
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Get cached Python interpreter info (reuses cli-anything-bridge detection).
|
|
125
|
+
* @returns {{ found: boolean, command?: string, version?: string }}
|
|
126
|
+
*/
|
|
127
|
+
export function getCachedPython() {
|
|
128
|
+
if (!_cachedPython) {
|
|
129
|
+
_cachedPython = detectPython();
|
|
130
|
+
}
|
|
131
|
+
return _cachedPython;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Gather environment info (cached once per process).
|
|
136
|
+
* @returns {{ os: string, arch: string, python: string|null, pip: boolean, node: string|null, git: boolean }}
|
|
137
|
+
*/
|
|
138
|
+
export function getEnvironmentInfo() {
|
|
139
|
+
if (_cachedEnvInfo) return _cachedEnvInfo;
|
|
140
|
+
|
|
141
|
+
const py = getCachedPython();
|
|
142
|
+
|
|
143
|
+
let pipAvailable = false;
|
|
144
|
+
if (py.found) {
|
|
145
|
+
try {
|
|
146
|
+
execSync(`${py.command} -m pip --version`, {
|
|
147
|
+
encoding: "utf-8",
|
|
148
|
+
timeout: 10000,
|
|
149
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
150
|
+
});
|
|
151
|
+
pipAvailable = true;
|
|
152
|
+
} catch {
|
|
153
|
+
// pip not available
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
let nodeVersion = null;
|
|
158
|
+
try {
|
|
159
|
+
nodeVersion = execSync("node --version", {
|
|
160
|
+
encoding: "utf-8",
|
|
161
|
+
timeout: 5000,
|
|
162
|
+
}).trim();
|
|
163
|
+
} catch {
|
|
164
|
+
// Node not available (unlikely since we're running in Node)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
let gitAvailable = false;
|
|
168
|
+
try {
|
|
169
|
+
execSync("git --version", {
|
|
170
|
+
encoding: "utf-8",
|
|
171
|
+
timeout: 5000,
|
|
172
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
173
|
+
});
|
|
174
|
+
gitAvailable = true;
|
|
175
|
+
} catch {
|
|
176
|
+
// git not available
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
_cachedEnvInfo = {
|
|
180
|
+
os: process.platform,
|
|
181
|
+
arch: process.arch,
|
|
182
|
+
python: py.found ? `${py.command} (${py.version})` : null,
|
|
183
|
+
pip: pipAvailable,
|
|
184
|
+
node: nodeVersion,
|
|
185
|
+
git: gitAvailable,
|
|
186
|
+
};
|
|
187
|
+
return _cachedEnvInfo;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// ─── System prompt ────────────────────────────────────────────────────────
|
|
191
|
+
|
|
192
|
+
export function getBaseSystemPrompt(cwd) {
|
|
193
|
+
const env = getEnvironmentInfo();
|
|
194
|
+
const envLines = [
|
|
195
|
+
`OS: ${env.os} (${env.arch})`,
|
|
196
|
+
env.python
|
|
197
|
+
? `Python: ${env.python}${env.pip ? " + pip" : ""}`
|
|
198
|
+
: "Python: not found",
|
|
199
|
+
env.node ? `Node.js: ${env.node}` : "Node.js: not found",
|
|
200
|
+
`Git: ${env.git ? "available" : "not found"}`,
|
|
201
|
+
];
|
|
202
|
+
|
|
203
|
+
return `You are ChainlessChain AI Assistant, a powerful agentic coding assistant running in the terminal.
|
|
204
|
+
|
|
205
|
+
You have access to tools that let you read files, write files, edit files, run shell commands, and search the codebase. When the user asks you to do something, USE THE TOOLS to actually do it — don't just describe what should be done.
|
|
206
|
+
|
|
207
|
+
Key behaviors:
|
|
208
|
+
- When asked to modify code, read the file first, then edit it
|
|
209
|
+
- When asked to create something, use write_file to create it
|
|
210
|
+
- When asked to run/test something, use run_shell to execute it
|
|
211
|
+
- When asked about git status, diff, log, or other repository operations, use the git tool instead of run_shell
|
|
212
|
+
- When asked about files or code, use read_file and search_files to find information
|
|
213
|
+
- You have multi-layer skills (built-in, marketplace, global, project-level) — use list_skills to discover them and run_skill to execute them
|
|
214
|
+
- Always explain what you're doing and show results
|
|
215
|
+
- Be concise but thorough
|
|
216
|
+
|
|
217
|
+
When the user's problem involves data processing, calculations, file operations, text parsing, API calls, web scraping, or any task that can be solved programmatically:
|
|
218
|
+
- Proactively write and execute code using run_code tool
|
|
219
|
+
- Choose the best language: Python for data/math/scraping, Node.js for JSON/API, Bash for system tasks
|
|
220
|
+
- Missing Python packages are auto-installed via pip when import errors are detected
|
|
221
|
+
- Scripts are persisted in .chainlesschain/agent-scripts/ for reference
|
|
222
|
+
- Show the results and explain them clearly
|
|
223
|
+
- If the first attempt fails, debug and retry with a different approach
|
|
224
|
+
|
|
225
|
+
You are not just a chatbot — you are a capable coding agent. Think step by step, write code when needed, and deliver real results.
|
|
226
|
+
|
|
227
|
+
## Sub-Agent Isolation
|
|
228
|
+
When a task involves multiple distinct roles (e.g. code review + code generation), or when you need
|
|
229
|
+
focused analysis without polluting your current context, use the spawn_sub_agent tool. Examples:
|
|
230
|
+
- Code review as a separate perspective while you're implementing
|
|
231
|
+
- Summarizing a large file before incorporating it into your response
|
|
232
|
+
- Running a focused analysis (security, performance) on specific code
|
|
233
|
+
- Translating or reformatting content independently
|
|
234
|
+
The sub-agent has its own message history and only returns a summary — your context stays clean.
|
|
235
|
+
Do NOT spawn sub-agents for trivial tasks that you can handle directly.
|
|
236
|
+
|
|
237
|
+
## Environment
|
|
238
|
+
${envLines.join("\n")}
|
|
239
|
+
|
|
240
|
+
Current working directory: ${cwd || process.cwd()}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ─── Persona support ─────────────────────────────────────────────────────
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Load persona configuration from project config.json
|
|
247
|
+
* @param {string} cwd - working directory
|
|
248
|
+
* @returns {object|null} persona object or null
|
|
249
|
+
*/
|
|
250
|
+
function _loadProjectPersona(cwd) {
|
|
251
|
+
try {
|
|
252
|
+
const projectRoot = findProjectRoot(cwd || process.cwd());
|
|
253
|
+
if (!projectRoot) return null;
|
|
254
|
+
const config = loadProjectConfig(projectRoot);
|
|
255
|
+
return config?.persona || null;
|
|
256
|
+
} catch {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Build a persona-specific system prompt
|
|
263
|
+
* @param {object} persona - persona configuration
|
|
264
|
+
* @param {string[]} envLines - environment info lines
|
|
265
|
+
* @param {string} cwd - working directory
|
|
266
|
+
* @returns {string}
|
|
267
|
+
*/
|
|
268
|
+
function _buildPersonaPrompt(persona, envLines, cwd) {
|
|
269
|
+
const lines = [];
|
|
270
|
+
lines.push(`You are ${persona.name || "AI Assistant"}.`);
|
|
271
|
+
if (persona.role) {
|
|
272
|
+
lines.push("");
|
|
273
|
+
lines.push(persona.role);
|
|
274
|
+
}
|
|
275
|
+
if (persona.behaviors?.length > 0) {
|
|
276
|
+
lines.push("");
|
|
277
|
+
lines.push("Key behaviors:");
|
|
278
|
+
for (const b of persona.behaviors) {
|
|
279
|
+
lines.push(`- ${b}`);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
lines.push("");
|
|
283
|
+
lines.push(
|
|
284
|
+
"You have access to tools that let you read files, write files, edit files, run shell commands, and search the codebase. When the user asks you to do something, USE THE TOOLS to actually do it.",
|
|
285
|
+
);
|
|
286
|
+
if (persona.toolsPriority?.length > 0) {
|
|
287
|
+
lines.push(`\nPreferred tools: ${persona.toolsPriority.join(", ")}`);
|
|
288
|
+
}
|
|
289
|
+
lines.push(`\n## Environment\n${envLines.join("\n")}`);
|
|
290
|
+
lines.push(`\nCurrent working directory: ${cwd || process.cwd()}`);
|
|
291
|
+
return lines.join("\n");
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Build the full system prompt with persona, rules.md, and auto-activated persona skills.
|
|
296
|
+
* Single entry point used by both agent-repl and ws-session-manager.
|
|
297
|
+
*
|
|
298
|
+
* Priority order:
|
|
299
|
+
* 1. config.json persona → replaces base system prompt
|
|
300
|
+
* 2. Auto-activated persona skills → appended
|
|
301
|
+
* 3. rules.md → appended
|
|
302
|
+
* 4. Default hardcoded prompt → fallback when no persona
|
|
303
|
+
*
|
|
304
|
+
* @param {string} [cwd] - working directory
|
|
305
|
+
* @returns {string} complete system prompt
|
|
306
|
+
*/
|
|
307
|
+
export function buildSystemPrompt(cwd) {
|
|
308
|
+
const dir = cwd || process.cwd();
|
|
309
|
+
|
|
310
|
+
// Check for project persona
|
|
311
|
+
const persona = _loadProjectPersona(dir);
|
|
312
|
+
let prompt;
|
|
313
|
+
if (persona) {
|
|
314
|
+
const env = getEnvironmentInfo();
|
|
315
|
+
const envLines = [
|
|
316
|
+
`OS: ${env.os} (${env.arch})`,
|
|
317
|
+
env.python
|
|
318
|
+
? `Python: ${env.python}${env.pip ? " + pip" : ""}`
|
|
319
|
+
: "Python: not found",
|
|
320
|
+
env.node ? `Node.js: ${env.node}` : "Node.js: not found",
|
|
321
|
+
`Git: ${env.git ? "available" : "not found"}`,
|
|
322
|
+
];
|
|
323
|
+
prompt = _buildPersonaPrompt(persona, envLines, dir);
|
|
324
|
+
} else {
|
|
325
|
+
prompt = getBaseSystemPrompt(dir);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Append auto-activated persona skills
|
|
329
|
+
try {
|
|
330
|
+
const loader = new CLISkillLoader();
|
|
331
|
+
const allSkills = loader.getResolvedSkills();
|
|
332
|
+
const personaSkills = allSkills.filter(
|
|
333
|
+
(s) => s.category === "persona" && s.activation === "auto",
|
|
334
|
+
);
|
|
335
|
+
for (const p of personaSkills) {
|
|
336
|
+
if (p.body?.trim()) {
|
|
337
|
+
prompt += `\n\n## Persona: ${p.displayName}\n${p.body}`;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
} catch {
|
|
341
|
+
// Non-critical — skill loader may not be available
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// Append rules.md
|
|
345
|
+
try {
|
|
346
|
+
const projectRoot = findProjectRoot(dir);
|
|
347
|
+
if (projectRoot) {
|
|
348
|
+
const rulesPath = path.join(projectRoot, ".chainlesschain", "rules.md");
|
|
349
|
+
if (fs.existsSync(rulesPath)) {
|
|
350
|
+
const content = fs.readFileSync(rulesPath, "utf-8");
|
|
351
|
+
if (content.trim()) {
|
|
352
|
+
prompt += `\n\n## Project Rules\n${content}`;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
} catch {
|
|
357
|
+
// Non-critical
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return prompt;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// ─── Tool execution ──────────────────────────────────────────────────────
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Execute a single tool call with plan-mode filtering and hook pipeline.
|
|
367
|
+
*
|
|
368
|
+
* @param {string} name - tool name
|
|
369
|
+
* @param {object} args - tool arguments
|
|
370
|
+
* @param {object} [context] - optional context
|
|
371
|
+
* @param {object} [context.hookDb] - DB for hooks
|
|
372
|
+
* @param {CLISkillLoader} [context.skillLoader] - skill loader instance
|
|
373
|
+
* @param {string} [context.cwd] - working directory override
|
|
374
|
+
* @returns {Promise<object>} tool result
|
|
375
|
+
*/
|
|
376
|
+
export async function executeTool(name, args, context = {}) {
|
|
377
|
+
const hookDb = context.hookDb || null;
|
|
378
|
+
const skillLoader = context.skillLoader || _defaultSkillLoader;
|
|
379
|
+
const cwd = context.cwd || process.cwd();
|
|
380
|
+
const planManager = context.planManager || getPlanModeManager();
|
|
381
|
+
const localToolDescriptor =
|
|
382
|
+
context.externalToolDescriptors &&
|
|
383
|
+
typeof context.externalToolDescriptors === "object"
|
|
384
|
+
? context.externalToolDescriptors[name] || null
|
|
385
|
+
: null;
|
|
386
|
+
const runtimeDescriptor =
|
|
387
|
+
getRuntimeToolDescriptor(name) || localToolDescriptor;
|
|
388
|
+
const toolContext = createToolContext({
|
|
389
|
+
toolName: runtimeDescriptor?.name || name,
|
|
390
|
+
cwd,
|
|
391
|
+
metadata: { descriptor: runtimeDescriptor },
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
// Persona toolsDisabled guard
|
|
395
|
+
const persona = _loadProjectPersona(cwd);
|
|
396
|
+
if (persona?.toolsDisabled?.includes(name)) {
|
|
397
|
+
return {
|
|
398
|
+
error: `Tool "${name}" is disabled by project persona configuration.`,
|
|
399
|
+
};
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const toolPolicies =
|
|
403
|
+
context.hostManagedToolPolicy?.tools ||
|
|
404
|
+
context.hostManagedToolPolicy?.toolPolicies ||
|
|
405
|
+
null;
|
|
406
|
+
const hostToolPolicy =
|
|
407
|
+
toolPolicies && typeof toolPolicies === "object"
|
|
408
|
+
? toolPolicies[name]
|
|
409
|
+
: null;
|
|
410
|
+
const isExternalHostTool =
|
|
411
|
+
hostToolPolicy && !STATIC_AGENT_TOOL_NAMES.has(name);
|
|
412
|
+
const isExternalLocalTool =
|
|
413
|
+
localToolDescriptor && !STATIC_AGENT_TOOL_NAMES.has(name);
|
|
414
|
+
const hostPolicyAllowsReadOnlyGit =
|
|
415
|
+
name === "git" &&
|
|
416
|
+
hostToolPolicy?.planModeBehavior === "readonly-conditional" &&
|
|
417
|
+
isReadOnlyGitCommand(args.command);
|
|
418
|
+
const localReadOnlyAllowedInPlanMode =
|
|
419
|
+
isExternalLocalTool &&
|
|
420
|
+
planManager.isActive() &&
|
|
421
|
+
localToolDescriptor?.isReadOnly === true;
|
|
422
|
+
if (
|
|
423
|
+
hostToolPolicy &&
|
|
424
|
+
hostToolPolicy.allowed === false &&
|
|
425
|
+
!hostPolicyAllowsReadOnlyGit
|
|
426
|
+
) {
|
|
427
|
+
return {
|
|
428
|
+
error: `[Host Policy] Tool "${name}" is blocked by desktop host policy. ${hostToolPolicy.reason || "Desktop approval has not been synchronized yet."}`,
|
|
429
|
+
policy: {
|
|
430
|
+
decision: hostToolPolicy.decision || "blocked",
|
|
431
|
+
requiresPlanApproval: hostToolPolicy.requiresPlanApproval === true,
|
|
432
|
+
requiresConfirmation: hostToolPolicy.requiresConfirmation === true,
|
|
433
|
+
riskLevel: hostToolPolicy.riskLevel || null,
|
|
434
|
+
},
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// Plan mode: check if tool is allowed
|
|
439
|
+
if (
|
|
440
|
+
planManager.isActive() &&
|
|
441
|
+
!(name === "git" && isReadOnlyGitCommand(args.command)) &&
|
|
442
|
+
!planManager.isToolAllowed(name) &&
|
|
443
|
+
!(isExternalHostTool && hostToolPolicy?.allowed === true) &&
|
|
444
|
+
!localReadOnlyAllowedInPlanMode
|
|
445
|
+
) {
|
|
446
|
+
planManager.addPlanItem({
|
|
447
|
+
title: `${name}: ${formatToolArgs(name, args)}`,
|
|
448
|
+
tool: name,
|
|
449
|
+
params: args,
|
|
450
|
+
estimatedImpact:
|
|
451
|
+
name === "run_shell" ||
|
|
452
|
+
name === "run_code" ||
|
|
453
|
+
name === "git" ||
|
|
454
|
+
localToolDescriptor?.riskLevel === "high"
|
|
455
|
+
? "high"
|
|
456
|
+
: name === "write_file" || localToolDescriptor?.riskLevel === "medium"
|
|
457
|
+
? "medium"
|
|
458
|
+
: "low",
|
|
459
|
+
});
|
|
460
|
+
return {
|
|
461
|
+
error: `[Plan Mode] Tool "${name}" is blocked during planning. It has been added to the plan. Use /plan approve to execute.`,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// PreToolUse hook
|
|
466
|
+
if (hookDb) {
|
|
467
|
+
try {
|
|
468
|
+
await executeHooks(hookDb, HookEvents.PreToolUse, {
|
|
469
|
+
tool: name,
|
|
470
|
+
args,
|
|
471
|
+
timestamp: new Date().toISOString(),
|
|
472
|
+
descriptor: runtimeDescriptor,
|
|
473
|
+
context: toolContext,
|
|
474
|
+
});
|
|
475
|
+
} catch (_err) {
|
|
476
|
+
// Hook failure should not block tool execution
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const startTime = Date.now();
|
|
481
|
+
let toolResult;
|
|
482
|
+
try {
|
|
483
|
+
toolResult = await executeToolInner(name, args, {
|
|
484
|
+
skillLoader,
|
|
485
|
+
cwd,
|
|
486
|
+
parentMessages: context.parentMessages,
|
|
487
|
+
interaction: context.interaction,
|
|
488
|
+
sessionId: context.sessionId || null,
|
|
489
|
+
hostManagedToolPolicy: context.hostManagedToolPolicy || null,
|
|
490
|
+
externalToolDescriptors: context.externalToolDescriptors || null,
|
|
491
|
+
externalToolExecutors: context.externalToolExecutors || null,
|
|
492
|
+
mcpClient: context.mcpClient || null,
|
|
493
|
+
});
|
|
494
|
+
} catch (err) {
|
|
495
|
+
if (hookDb) {
|
|
496
|
+
try {
|
|
497
|
+
await executeHooks(hookDb, HookEvents.ToolError, {
|
|
498
|
+
tool: name,
|
|
499
|
+
args,
|
|
500
|
+
error: err.message,
|
|
501
|
+
});
|
|
502
|
+
} catch (_err) {
|
|
503
|
+
// Non-critical
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
throw err;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const durationMs = Date.now() - startTime;
|
|
510
|
+
const status = toolResult?.error ? "error" : "completed";
|
|
511
|
+
const telemetryRecord = createToolTelemetryRecord({
|
|
512
|
+
descriptor: runtimeDescriptor,
|
|
513
|
+
status,
|
|
514
|
+
durationMs,
|
|
515
|
+
sessionId: context.sessionId || null,
|
|
516
|
+
metadata: { args },
|
|
517
|
+
});
|
|
518
|
+
if (toolResult && typeof toolResult === "object") {
|
|
519
|
+
toolResult.toolTelemetryRecord = telemetryRecord;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// PostToolUse hook
|
|
523
|
+
if (hookDb) {
|
|
524
|
+
try {
|
|
525
|
+
await executeHooks(hookDb, HookEvents.PostToolUse, {
|
|
526
|
+
tool: name,
|
|
527
|
+
args,
|
|
528
|
+
result:
|
|
529
|
+
typeof toolResult === "object"
|
|
530
|
+
? JSON.stringify(toolResult).substring(0, 500)
|
|
531
|
+
: String(toolResult).substring(0, 500),
|
|
532
|
+
descriptor: runtimeDescriptor,
|
|
533
|
+
context: toolContext,
|
|
534
|
+
});
|
|
535
|
+
} catch (_err) {
|
|
536
|
+
// Non-critical
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return toolResult;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Inner tool execution — no hooks, no plan-mode checks.
|
|
545
|
+
*/
|
|
546
|
+
async function executeToolInner(
|
|
547
|
+
name,
|
|
548
|
+
args,
|
|
549
|
+
{
|
|
550
|
+
skillLoader,
|
|
551
|
+
cwd,
|
|
552
|
+
parentMessages,
|
|
553
|
+
interaction,
|
|
554
|
+
sessionId,
|
|
555
|
+
hostManagedToolPolicy,
|
|
556
|
+
externalToolDescriptors,
|
|
557
|
+
externalToolExecutors,
|
|
558
|
+
mcpClient,
|
|
559
|
+
},
|
|
560
|
+
) {
|
|
561
|
+
const localToolDescriptor =
|
|
562
|
+
externalToolDescriptors && typeof externalToolDescriptors === "object"
|
|
563
|
+
? externalToolDescriptors[name] || null
|
|
564
|
+
: null;
|
|
565
|
+
const runtimeDescriptor =
|
|
566
|
+
getRuntimeToolDescriptor(name) || localToolDescriptor;
|
|
567
|
+
const hostToolPolicies =
|
|
568
|
+
hostManagedToolPolicy?.tools || hostManagedToolPolicy?.toolPolicies || null;
|
|
569
|
+
const hostToolPolicy =
|
|
570
|
+
hostToolPolicies && typeof hostToolPolicies === "object"
|
|
571
|
+
? hostToolPolicies[name]
|
|
572
|
+
: null;
|
|
573
|
+
const hostToolDefinition = Array.isArray(
|
|
574
|
+
hostManagedToolPolicy?.toolDefinitions,
|
|
575
|
+
)
|
|
576
|
+
? hostManagedToolPolicy.toolDefinitions.find(
|
|
577
|
+
(tool) => tool?.function?.name === name,
|
|
578
|
+
) || null
|
|
579
|
+
: null;
|
|
580
|
+
const buildPayload = (descriptor) =>
|
|
581
|
+
descriptor
|
|
582
|
+
? {
|
|
583
|
+
name: descriptor.name,
|
|
584
|
+
kind: descriptor.kind || descriptor.category || descriptor.source,
|
|
585
|
+
category: descriptor.category,
|
|
586
|
+
}
|
|
587
|
+
: null;
|
|
588
|
+
const descriptorPayload = buildPayload(runtimeDescriptor);
|
|
589
|
+
const attachDescriptor = (payload, overrideDescriptor = null) => {
|
|
590
|
+
const descriptor = buildPayload(overrideDescriptor || runtimeDescriptor);
|
|
591
|
+
return descriptor ? { ...payload, toolDescriptor: descriptor } : payload;
|
|
592
|
+
};
|
|
593
|
+
const localToolExecutor =
|
|
594
|
+
externalToolExecutors && typeof externalToolExecutors === "object"
|
|
595
|
+
? externalToolExecutors[name] || null
|
|
596
|
+
: null;
|
|
597
|
+
switch (name) {
|
|
598
|
+
case "read_file": {
|
|
599
|
+
const filePath = path.resolve(cwd, args.path);
|
|
600
|
+
if (!fs.existsSync(filePath)) {
|
|
601
|
+
return attachDescriptor({ error: `File not found: ${filePath}` });
|
|
602
|
+
}
|
|
603
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
604
|
+
// Hashline mode: prefix each line with a 6-char content hash tag
|
|
605
|
+
// so downstream edit_file_hashed calls can anchor by hash.
|
|
606
|
+
const rendered = args.hashed === true ? annotateLines(content) : content;
|
|
607
|
+
if (rendered.length > 50000) {
|
|
608
|
+
return attachDescriptor({
|
|
609
|
+
content: rendered.substring(0, 50000) + "\n...(truncated)",
|
|
610
|
+
size: rendered.length,
|
|
611
|
+
hashed: args.hashed === true,
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
return attachDescriptor({
|
|
615
|
+
content: rendered,
|
|
616
|
+
hashed: args.hashed === true,
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
case "write_file": {
|
|
621
|
+
const filePath = path.resolve(cwd, args.path);
|
|
622
|
+
const dir = path.dirname(filePath);
|
|
623
|
+
if (!fs.existsSync(dir)) {
|
|
624
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
625
|
+
}
|
|
626
|
+
fs.writeFileSync(filePath, args.content, "utf8");
|
|
627
|
+
return attachDescriptor({
|
|
628
|
+
success: true,
|
|
629
|
+
path: filePath,
|
|
630
|
+
size: args.content.length,
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
case "edit_file": {
|
|
635
|
+
const filePath = path.resolve(cwd, args.path);
|
|
636
|
+
if (!fs.existsSync(filePath)) {
|
|
637
|
+
return attachDescriptor({ error: `File not found: ${filePath}` });
|
|
638
|
+
}
|
|
639
|
+
const content = fs.readFileSync(filePath, "utf8");
|
|
640
|
+
if (!content.includes(args.old_string)) {
|
|
641
|
+
return attachDescriptor({ error: "old_string not found in file" });
|
|
642
|
+
}
|
|
643
|
+
const newContent = content.replace(args.old_string, args.new_string);
|
|
644
|
+
fs.writeFileSync(filePath, newContent, "utf8");
|
|
645
|
+
return attachDescriptor({ success: true, path: filePath });
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
case "edit_file_hashed": {
|
|
649
|
+
// Hash-anchored edit (v5.0.2.9, inspired by oh-my-openagent).
|
|
650
|
+
// Reference a line by its content hash rather than line number or
|
|
651
|
+
// exact string — robust against whitespace drift and concurrent edits.
|
|
652
|
+
const filePath = path.resolve(cwd, args.path);
|
|
653
|
+
if (!fs.existsSync(filePath)) {
|
|
654
|
+
return attachDescriptor({ error: `File not found: ${filePath}` });
|
|
655
|
+
}
|
|
656
|
+
if (!args.anchor_hash || typeof args.anchor_hash !== "string") {
|
|
657
|
+
return attachDescriptor({
|
|
658
|
+
error: "anchor_hash is required",
|
|
659
|
+
hint: "Read the file with hashed:true to get line hashes",
|
|
660
|
+
});
|
|
661
|
+
}
|
|
662
|
+
if (typeof args.new_line !== "string") {
|
|
663
|
+
return attachDescriptor({ error: "new_line must be a string" });
|
|
664
|
+
}
|
|
665
|
+
const original = fs.readFileSync(filePath, "utf8");
|
|
666
|
+
const result = replaceByHash(original, {
|
|
667
|
+
anchorHash: args.anchor_hash,
|
|
668
|
+
expectedLine: args.expected_line,
|
|
669
|
+
newLine: args.new_line,
|
|
670
|
+
});
|
|
671
|
+
if (!result.success) {
|
|
672
|
+
// Self-healing hint: include a fresh annotated snippet when possible
|
|
673
|
+
const snippet =
|
|
674
|
+
result.error === "ambiguous_anchor" && result.matches?.[0]
|
|
675
|
+
? snippetAround(original, result.matches[0].lineNumber - 1)
|
|
676
|
+
: null;
|
|
677
|
+
return attachDescriptor({
|
|
678
|
+
error: result.error,
|
|
679
|
+
message: result.message,
|
|
680
|
+
hint: result.hint,
|
|
681
|
+
...(result.matches && { matches: result.matches }),
|
|
682
|
+
...(result.current && { current: result.current }),
|
|
683
|
+
...(result.expected && { expected: result.expected }),
|
|
684
|
+
...(snippet && { current_snippet: snippet }),
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
fs.writeFileSync(filePath, result.content, "utf8");
|
|
688
|
+
return attachDescriptor({
|
|
689
|
+
success: true,
|
|
690
|
+
path: filePath,
|
|
691
|
+
lineNumber: result.lineNumber,
|
|
692
|
+
previousContent: result.previousContent,
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
case "run_shell": {
|
|
697
|
+
const shellPolicy = evaluateShellCommandPolicy(args.command);
|
|
698
|
+
const override = getRuntimeToolDescriptorByCommand(args.command);
|
|
699
|
+
if (!shellPolicy.allowed) {
|
|
700
|
+
return attachDescriptor(
|
|
701
|
+
{
|
|
702
|
+
error: `[Shell Policy] ${shellPolicy.reason}`,
|
|
703
|
+
shellCommandPolicy: shellPolicy,
|
|
704
|
+
},
|
|
705
|
+
override || runtimeDescriptor,
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
try {
|
|
710
|
+
const output = execSync(args.command, {
|
|
711
|
+
cwd: args.cwd || cwd,
|
|
712
|
+
encoding: "utf8",
|
|
713
|
+
timeout: 60000,
|
|
714
|
+
maxBuffer: 1024 * 1024,
|
|
715
|
+
});
|
|
716
|
+
return attachDescriptor(
|
|
717
|
+
{
|
|
718
|
+
stdout: output.substring(0, 30000),
|
|
719
|
+
shellCommandPolicy: shellPolicy,
|
|
720
|
+
},
|
|
721
|
+
override || runtimeDescriptor,
|
|
722
|
+
);
|
|
723
|
+
} catch (err) {
|
|
724
|
+
return attachDescriptor(
|
|
725
|
+
{
|
|
726
|
+
error: err.message.substring(0, 2000),
|
|
727
|
+
stderr: (err.stderr || "").substring(0, 2000),
|
|
728
|
+
exitCode: err.status,
|
|
729
|
+
shellCommandPolicy: shellPolicy,
|
|
730
|
+
},
|
|
731
|
+
override || runtimeDescriptor,
|
|
732
|
+
);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
case "git": {
|
|
737
|
+
const normalizedCommand = normalizeGitCommand(args.command);
|
|
738
|
+
if (!normalizedCommand) {
|
|
739
|
+
return attachDescriptor({
|
|
740
|
+
error: "Git command is required.",
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
try {
|
|
745
|
+
const output = execSync(`git ${normalizedCommand}`, {
|
|
746
|
+
cwd: args.cwd || cwd,
|
|
747
|
+
encoding: "utf8",
|
|
748
|
+
timeout: 60000,
|
|
749
|
+
maxBuffer: 1024 * 1024,
|
|
750
|
+
});
|
|
751
|
+
return attachDescriptor({
|
|
752
|
+
stdout: output.substring(0, 30000),
|
|
753
|
+
command: normalizedCommand,
|
|
754
|
+
readOnly: isReadOnlyGitCommand(normalizedCommand),
|
|
755
|
+
});
|
|
756
|
+
} catch (err) {
|
|
757
|
+
return attachDescriptor({
|
|
758
|
+
error: err.message.substring(0, 2000),
|
|
759
|
+
stderr: (err.stderr || "").substring(0, 2000),
|
|
760
|
+
exitCode: err.status,
|
|
761
|
+
command: normalizedCommand,
|
|
762
|
+
readOnly: isReadOnlyGitCommand(normalizedCommand),
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
case "run_code": {
|
|
768
|
+
return attachDescriptor(await _executeRunCode(args, cwd));
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
case "spawn_sub_agent": {
|
|
772
|
+
return attachDescriptor(
|
|
773
|
+
await _executeSpawnSubAgent(args, {
|
|
774
|
+
skillLoader,
|
|
775
|
+
cwd,
|
|
776
|
+
parentMessages,
|
|
777
|
+
interaction,
|
|
778
|
+
sessionId,
|
|
779
|
+
}),
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
case "search_files": {
|
|
784
|
+
const dir = args.directory ? path.resolve(cwd, args.directory) : cwd;
|
|
785
|
+
try {
|
|
786
|
+
if (args.content_search) {
|
|
787
|
+
const cmd =
|
|
788
|
+
process.platform === "win32"
|
|
789
|
+
? `findstr /s /i /n "${args.pattern}" *`
|
|
790
|
+
: `grep -r -l -i "${args.pattern}" . --include="*" 2>/dev/null | head -20`;
|
|
791
|
+
const output = execSync(cmd, {
|
|
792
|
+
cwd: dir,
|
|
793
|
+
encoding: "utf8",
|
|
794
|
+
timeout: 10000,
|
|
795
|
+
});
|
|
796
|
+
return attachDescriptor({
|
|
797
|
+
matches: output.trim().split("\n").slice(0, 20),
|
|
798
|
+
});
|
|
799
|
+
} else {
|
|
800
|
+
const cmd =
|
|
801
|
+
process.platform === "win32"
|
|
802
|
+
? `dir /s /b *${args.pattern}* 2>NUL`
|
|
803
|
+
: `find . -name "*${args.pattern}*" -type f 2>/dev/null | head -20`;
|
|
804
|
+
const output = execSync(cmd, {
|
|
805
|
+
cwd: dir,
|
|
806
|
+
encoding: "utf8",
|
|
807
|
+
timeout: 10000,
|
|
808
|
+
});
|
|
809
|
+
return attachDescriptor({
|
|
810
|
+
files: output.trim().split("\n").filter(Boolean).slice(0, 20),
|
|
811
|
+
});
|
|
812
|
+
}
|
|
813
|
+
} catch {
|
|
814
|
+
return attachDescriptor({
|
|
815
|
+
files: [],
|
|
816
|
+
message: "No matches found",
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
case "list_dir": {
|
|
822
|
+
const dirPath = args.path ? path.resolve(cwd, args.path) : cwd;
|
|
823
|
+
if (!fs.existsSync(dirPath)) {
|
|
824
|
+
return attachDescriptor({ error: `Directory not found: ${dirPath}` });
|
|
825
|
+
}
|
|
826
|
+
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
|
827
|
+
return attachDescriptor({
|
|
828
|
+
entries: entries.map((e) => ({
|
|
829
|
+
name: e.name,
|
|
830
|
+
type: e.isDirectory() ? "dir" : "file",
|
|
831
|
+
})),
|
|
832
|
+
});
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
case "run_skill": {
|
|
836
|
+
const allSkills = skillLoader.getResolvedSkills();
|
|
837
|
+
if (allSkills.length === 0) {
|
|
838
|
+
return attachDescriptor({
|
|
839
|
+
error:
|
|
840
|
+
"No skills found. Make sure you're in the ChainlessChain project root or have skills installed.",
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
const match = allSkills.find(
|
|
844
|
+
(s) => s.id === args.skill_name || s.dirName === args.skill_name,
|
|
845
|
+
);
|
|
846
|
+
if (!match || !match.hasHandler) {
|
|
847
|
+
return attachDescriptor({
|
|
848
|
+
error: `Skill "${args.skill_name}" not found or has no handler. Use list_skills to see available skills.`,
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// Check if skill requests isolation (via SKILL.md frontmatter)
|
|
853
|
+
const skillIsolation = match.isolation === true;
|
|
854
|
+
if (skillIsolation) {
|
|
855
|
+
// Run skill through isolated sub-agent context
|
|
856
|
+
const subCtx = SubAgentContext.create({
|
|
857
|
+
role: `skill-${args.skill_name}`,
|
|
858
|
+
task: `Execute the "${args.skill_name}" skill with input: ${(args.input || "").substring(0, 200)}`,
|
|
859
|
+
allowedTools: ["read_file", "search_files", "list_dir"],
|
|
860
|
+
cwd,
|
|
861
|
+
});
|
|
862
|
+
try {
|
|
863
|
+
const result = await subCtx.run(args.input);
|
|
864
|
+
return attachDescriptor({
|
|
865
|
+
success: true,
|
|
866
|
+
isolated: true,
|
|
867
|
+
skill: args.skill_name,
|
|
868
|
+
summary: result.summary,
|
|
869
|
+
toolsUsed: result.toolsUsed,
|
|
870
|
+
});
|
|
871
|
+
} catch (err) {
|
|
872
|
+
return attachDescriptor({
|
|
873
|
+
error: `Isolated skill execution failed: ${err.message}`,
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// Skill-Embedded MCP: mount the skill's declared MCP servers for
|
|
879
|
+
// the duration of handler.execute, then unmount in finally. The
|
|
880
|
+
// handler may use them via taskContext.mcpClient. If mcpClient is
|
|
881
|
+
// null (no MCP set up for this session), skip silently.
|
|
882
|
+
let mountedMcpServers = [];
|
|
883
|
+
const hasSkillMcps =
|
|
884
|
+
Array.isArray(match.mcpServers) && match.mcpServers.length > 0;
|
|
885
|
+
if (hasSkillMcps && mcpClient) {
|
|
886
|
+
try {
|
|
887
|
+
const mountResult = await mountSkillMcpServers(mcpClient, match, {
|
|
888
|
+
onWarn: (msg) => {
|
|
889
|
+
// Non-fatal — logged as warning, skipped servers captured
|
|
890
|
+
// in mountResult.skipped.
|
|
891
|
+
// eslint-disable-next-line no-console
|
|
892
|
+
console.warn(msg);
|
|
893
|
+
},
|
|
894
|
+
});
|
|
895
|
+
mountedMcpServers = mountResult.mounted;
|
|
896
|
+
} catch (err) {
|
|
897
|
+
return attachDescriptor({
|
|
898
|
+
error: `Skill MCP mount failed: ${err.message}`,
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
try {
|
|
904
|
+
const handlerPath = path.join(match.skillDir, "handler.js");
|
|
905
|
+
const imported = await import(
|
|
906
|
+
`file://${handlerPath.replace(/\\/g, "/")}`
|
|
907
|
+
);
|
|
908
|
+
const handler = imported.default || imported;
|
|
909
|
+
if (handler.init) await handler.init(match);
|
|
910
|
+
const task = {
|
|
911
|
+
params: { input: args.input },
|
|
912
|
+
input: args.input,
|
|
913
|
+
action: args.input,
|
|
914
|
+
};
|
|
915
|
+
const taskContext = {
|
|
916
|
+
projectRoot: cwd,
|
|
917
|
+
workspacePath: cwd,
|
|
918
|
+
// Expose the MCP client + mounted servers so the skill handler
|
|
919
|
+
// can call MCP tools directly without going through the agent
|
|
920
|
+
// loop. Handlers that don't need MCP can ignore these.
|
|
921
|
+
mcpClient: mcpClient || null,
|
|
922
|
+
mountedMcpServers,
|
|
923
|
+
};
|
|
924
|
+
const result = await handler.execute(task, taskContext, match);
|
|
925
|
+
return attachDescriptor(result);
|
|
926
|
+
} catch (err) {
|
|
927
|
+
return attachDescriptor({
|
|
928
|
+
error: `Skill execution failed: ${err.message}`,
|
|
929
|
+
});
|
|
930
|
+
} finally {
|
|
931
|
+
if (mountedMcpServers.length > 0 && mcpClient) {
|
|
932
|
+
try {
|
|
933
|
+
await unmountSkillMcpServers(mcpClient, mountedMcpServers);
|
|
934
|
+
} catch (_err) {
|
|
935
|
+
// Non-critical — mount/unmount errors don't fail the skill
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
case "list_skills": {
|
|
942
|
+
let skills = skillLoader.getResolvedSkills();
|
|
943
|
+
if (skills.length === 0) {
|
|
944
|
+
return attachDescriptor({ error: "No skills found." });
|
|
945
|
+
}
|
|
946
|
+
if (args.category) {
|
|
947
|
+
skills = skills.filter(
|
|
948
|
+
(s) => s.category.toLowerCase() === args.category.toLowerCase(),
|
|
949
|
+
);
|
|
950
|
+
}
|
|
951
|
+
if (args.query) {
|
|
952
|
+
const q = args.query.toLowerCase();
|
|
953
|
+
skills = skills.filter(
|
|
954
|
+
(s) =>
|
|
955
|
+
s.id.includes(q) ||
|
|
956
|
+
s.description.toLowerCase().includes(q) ||
|
|
957
|
+
s.category.toLowerCase().includes(q),
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
return attachDescriptor({
|
|
961
|
+
count: skills.length,
|
|
962
|
+
skills: skills.map((s) => ({
|
|
963
|
+
id: s.id,
|
|
964
|
+
category: s.category,
|
|
965
|
+
source: s.source,
|
|
966
|
+
hasHandler: s.hasHandler,
|
|
967
|
+
description: (s.description || "").substring(0, 80),
|
|
968
|
+
})),
|
|
969
|
+
});
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
default:
|
|
973
|
+
if (localToolExecutor?.kind === "mcp") {
|
|
974
|
+
if (!mcpClient || typeof mcpClient.callTool !== "function") {
|
|
975
|
+
return attachDescriptor({
|
|
976
|
+
error: `MCP client is unavailable for tool: ${name}`,
|
|
977
|
+
});
|
|
978
|
+
}
|
|
979
|
+
|
|
980
|
+
try {
|
|
981
|
+
const result = await mcpClient.callTool(
|
|
982
|
+
localToolExecutor.serverName,
|
|
983
|
+
localToolExecutor.toolName,
|
|
984
|
+
args || {},
|
|
985
|
+
);
|
|
986
|
+
if (result && typeof result === "object") {
|
|
987
|
+
return attachDescriptor(result);
|
|
988
|
+
}
|
|
989
|
+
return attachDescriptor({ result });
|
|
990
|
+
} catch (err) {
|
|
991
|
+
return attachDescriptor({
|
|
992
|
+
error: `MCP tool execution failed: ${err.message}`,
|
|
993
|
+
});
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
if (
|
|
998
|
+
hostToolDefinition &&
|
|
999
|
+
interaction &&
|
|
1000
|
+
typeof interaction.requestHostTool === "function"
|
|
1001
|
+
) {
|
|
1002
|
+
const hostedResult = await interaction.requestHostTool(name, args);
|
|
1003
|
+
if (hostedResult?.success === false) {
|
|
1004
|
+
return attachDescriptor({
|
|
1005
|
+
error:
|
|
1006
|
+
hostedResult.error || `Hosted tool execution failed: ${name}`,
|
|
1007
|
+
policy: hostToolPolicy || null,
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
if (hostedResult?.result && typeof hostedResult.result === "object") {
|
|
1012
|
+
return hostedResult.result;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
return attachDescriptor({
|
|
1016
|
+
result:
|
|
1017
|
+
hostedResult &&
|
|
1018
|
+
Object.prototype.hasOwnProperty.call(hostedResult, "result")
|
|
1019
|
+
? hostedResult.result
|
|
1020
|
+
: hostedResult,
|
|
1021
|
+
});
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
return attachDescriptor({ error: `Unknown tool: ${name}` });
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
// ─── run_code implementation ──────────────────────────────────────────────
|
|
1029
|
+
|
|
1030
|
+
/**
|
|
1031
|
+
* Classify an error from code execution into a structured type with hints.
|
|
1032
|
+
* @param {string} stderr - stderr output
|
|
1033
|
+
* @param {string} message - error message
|
|
1034
|
+
* @param {number|null} exitCode - process exit code
|
|
1035
|
+
* @param {string} lang - language (python, node, bash)
|
|
1036
|
+
* @returns {{ errorType: string, hint: string }}
|
|
1037
|
+
*/
|
|
1038
|
+
export function classifyError(stderr, message, exitCode, lang) {
|
|
1039
|
+
const text = stderr || message || "";
|
|
1040
|
+
|
|
1041
|
+
// Import / module errors
|
|
1042
|
+
if (/ModuleNotFoundError|ImportError|No module named/i.test(text)) {
|
|
1043
|
+
const modMatch = text.match(/No module named ['"]([^'"]+)['"]/);
|
|
1044
|
+
return {
|
|
1045
|
+
errorType: "import_error",
|
|
1046
|
+
hint: modMatch
|
|
1047
|
+
? `Missing Python module "${modMatch[1]}". Will attempt auto-install.`
|
|
1048
|
+
: "Missing module. Check your imports.",
|
|
1049
|
+
};
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
// Syntax errors
|
|
1053
|
+
if (/SyntaxError|IndentationError|TabError/i.test(text)) {
|
|
1054
|
+
const lineMatch = text.match(/line (\d+)/i);
|
|
1055
|
+
return {
|
|
1056
|
+
errorType: "syntax_error",
|
|
1057
|
+
hint: lineMatch
|
|
1058
|
+
? `Syntax error on line ${lineMatch[1]}. Check for typos, missing colons, or indentation.`
|
|
1059
|
+
: "Syntax error in code. Check for typos or missing brackets.",
|
|
1060
|
+
};
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
// Timeout
|
|
1064
|
+
if (/ETIMEDOUT|timed?\s*out/i.test(text) || exitCode === null) {
|
|
1065
|
+
return {
|
|
1066
|
+
errorType: "timeout",
|
|
1067
|
+
hint: "Script timed out. Consider increasing timeout or optimizing the code.",
|
|
1068
|
+
};
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// Permission errors
|
|
1072
|
+
if (/EACCES|Permission denied|PermissionError/i.test(text)) {
|
|
1073
|
+
return {
|
|
1074
|
+
errorType: "permission_error",
|
|
1075
|
+
hint: "Permission denied. Try a different directory or run with appropriate permissions.",
|
|
1076
|
+
};
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
// Generic runtime error
|
|
1080
|
+
const lineMatch = text.match(/(?:line |:)(\d+)/);
|
|
1081
|
+
return {
|
|
1082
|
+
errorType: "runtime_error",
|
|
1083
|
+
hint: lineMatch
|
|
1084
|
+
? `Runtime error near line ${lineMatch[1]}. Check the traceback above.`
|
|
1085
|
+
: "Runtime error. Check stderr for details.",
|
|
1086
|
+
};
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
/**
|
|
1090
|
+
* Validate a package name for pip install (reject shell metacharacters).
|
|
1091
|
+
* @param {string} name
|
|
1092
|
+
* @returns {boolean}
|
|
1093
|
+
*/
|
|
1094
|
+
export function isValidPackageName(name) {
|
|
1095
|
+
return /^[a-zA-Z0-9_][a-zA-Z0-9._-]*$/.test(name) && name.length <= 100;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
/**
|
|
1099
|
+
* Execute code with auto pip-install, script persistence, and error classification.
|
|
1100
|
+
*/
|
|
1101
|
+
async function _executeRunCode(args, cwd) {
|
|
1102
|
+
const lang = args.language;
|
|
1103
|
+
const code = args.code;
|
|
1104
|
+
const timeoutSec = Math.min(Math.max(args.timeout || 60, 1), 300);
|
|
1105
|
+
const persist = args.persist !== false; // default true
|
|
1106
|
+
|
|
1107
|
+
const extMap = { python: ".py", node: ".js", bash: ".sh" };
|
|
1108
|
+
const ext = extMap[lang];
|
|
1109
|
+
if (!ext) {
|
|
1110
|
+
return {
|
|
1111
|
+
error: `Unsupported language: ${lang}. Use python, node, or bash.`,
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
// Determine script path
|
|
1116
|
+
let scriptPath;
|
|
1117
|
+
if (persist) {
|
|
1118
|
+
const scriptsDir = path.join(cwd, ".chainlesschain", "agent-scripts");
|
|
1119
|
+
if (!fs.existsSync(scriptsDir)) {
|
|
1120
|
+
fs.mkdirSync(scriptsDir, { recursive: true });
|
|
1121
|
+
}
|
|
1122
|
+
const timestamp = new Date()
|
|
1123
|
+
.toISOString()
|
|
1124
|
+
.replace(/[T:]/g, "-")
|
|
1125
|
+
.replace(/\.\d+Z$/, "");
|
|
1126
|
+
scriptPath = path.join(scriptsDir, `${timestamp}-${lang}${ext}`);
|
|
1127
|
+
} else {
|
|
1128
|
+
scriptPath = path.join(os.tmpdir(), `cc-agent-${Date.now()}${ext}`);
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
try {
|
|
1132
|
+
fs.writeFileSync(scriptPath, code, "utf8");
|
|
1133
|
+
|
|
1134
|
+
// Determine interpreter
|
|
1135
|
+
let interpreter;
|
|
1136
|
+
if (lang === "python") {
|
|
1137
|
+
const py = getCachedPython();
|
|
1138
|
+
interpreter = py.found ? py.command : "python";
|
|
1139
|
+
} else if (lang === "node") {
|
|
1140
|
+
interpreter = "node";
|
|
1141
|
+
} else {
|
|
1142
|
+
interpreter = "bash";
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
const start = Date.now();
|
|
1146
|
+
let output;
|
|
1147
|
+
try {
|
|
1148
|
+
output = execSync(`${interpreter} "${scriptPath}"`, {
|
|
1149
|
+
cwd,
|
|
1150
|
+
encoding: "utf8",
|
|
1151
|
+
timeout: timeoutSec * 1000,
|
|
1152
|
+
maxBuffer: 5 * 1024 * 1024,
|
|
1153
|
+
});
|
|
1154
|
+
} catch (err) {
|
|
1155
|
+
const stderr = (err.stderr || "").toString();
|
|
1156
|
+
const message = err.message || "";
|
|
1157
|
+
const classified = classifyError(stderr, message, err.status, lang);
|
|
1158
|
+
|
|
1159
|
+
// Auto-install missing Python packages
|
|
1160
|
+
if (lang === "python" && classified.errorType === "import_error") {
|
|
1161
|
+
const modMatch = stderr.match(/No module named ['"]([^'"]+)['"]/);
|
|
1162
|
+
if (modMatch) {
|
|
1163
|
+
// Use top-level package name (e.g. "foo.bar" → "foo")
|
|
1164
|
+
const packageName = modMatch[1].split(".")[0];
|
|
1165
|
+
|
|
1166
|
+
if (!isValidPackageName(packageName)) {
|
|
1167
|
+
return {
|
|
1168
|
+
error: `Invalid package name: "${packageName}"`,
|
|
1169
|
+
...classified,
|
|
1170
|
+
language: lang,
|
|
1171
|
+
scriptPath: persist ? scriptPath : undefined,
|
|
1172
|
+
};
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
// Attempt pip install
|
|
1176
|
+
try {
|
|
1177
|
+
execSync(`${interpreter} -m pip install ${packageName}`, {
|
|
1178
|
+
encoding: "utf-8",
|
|
1179
|
+
timeout: 120000,
|
|
1180
|
+
maxBuffer: 2 * 1024 * 1024,
|
|
1181
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
1182
|
+
});
|
|
1183
|
+
|
|
1184
|
+
// Retry execution
|
|
1185
|
+
const retryStart = Date.now();
|
|
1186
|
+
const retryOutput = execSync(`${interpreter} "${scriptPath}"`, {
|
|
1187
|
+
cwd,
|
|
1188
|
+
encoding: "utf8",
|
|
1189
|
+
timeout: timeoutSec * 1000,
|
|
1190
|
+
maxBuffer: 5 * 1024 * 1024,
|
|
1191
|
+
});
|
|
1192
|
+
const retryDuration = Date.now() - retryStart;
|
|
1193
|
+
|
|
1194
|
+
return {
|
|
1195
|
+
success: true,
|
|
1196
|
+
output: retryOutput.substring(0, 50000),
|
|
1197
|
+
language: lang,
|
|
1198
|
+
duration: `${retryDuration}ms`,
|
|
1199
|
+
autoInstalled: [packageName],
|
|
1200
|
+
scriptPath: persist ? scriptPath : undefined,
|
|
1201
|
+
};
|
|
1202
|
+
} catch (pipErr) {
|
|
1203
|
+
return {
|
|
1204
|
+
error: (stderr || message).substring(0, 5000),
|
|
1205
|
+
stderr: stderr.substring(0, 5000),
|
|
1206
|
+
exitCode: err.status,
|
|
1207
|
+
language: lang,
|
|
1208
|
+
...classified,
|
|
1209
|
+
hint: `Failed to auto-install "${packageName}". ${(pipErr.stderr || pipErr.message || "").substring(0, 500)}`,
|
|
1210
|
+
scriptPath: persist ? scriptPath : undefined,
|
|
1211
|
+
};
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
return {
|
|
1217
|
+
error: (stderr || message).substring(0, 5000),
|
|
1218
|
+
stderr: stderr.substring(0, 5000),
|
|
1219
|
+
exitCode: err.status,
|
|
1220
|
+
language: lang,
|
|
1221
|
+
...classified,
|
|
1222
|
+
scriptPath: persist ? scriptPath : undefined,
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
const duration = Date.now() - start;
|
|
1227
|
+
return {
|
|
1228
|
+
success: true,
|
|
1229
|
+
output: output.substring(0, 50000),
|
|
1230
|
+
language: lang,
|
|
1231
|
+
duration: `${duration}ms`,
|
|
1232
|
+
scriptPath: persist ? scriptPath : undefined,
|
|
1233
|
+
};
|
|
1234
|
+
} finally {
|
|
1235
|
+
// Only clean up if not persisting
|
|
1236
|
+
if (!persist) {
|
|
1237
|
+
try {
|
|
1238
|
+
fs.unlinkSync(scriptPath);
|
|
1239
|
+
} catch {
|
|
1240
|
+
// Cleanup best-effort
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
|
|
1246
|
+
// ─── spawn_sub_agent implementation ──────────────────────────────────────
|
|
1247
|
+
|
|
1248
|
+
/**
|
|
1249
|
+
* Execute a spawn_sub_agent tool call.
|
|
1250
|
+
* Creates an isolated SubAgentContext, runs it, and returns only the summary.
|
|
1251
|
+
*
|
|
1252
|
+
* @param {object} args - { role, task, context?, tools? }
|
|
1253
|
+
* @param {object} ctx - { skillLoader, cwd, parentMessages, interaction, sessionId }
|
|
1254
|
+
* @returns {Promise<object>}
|
|
1255
|
+
*/
|
|
1256
|
+
async function _executeSpawnSubAgent(args, ctx) {
|
|
1257
|
+
const { role, task, context: inheritedContext, tools: allowedTools } = args;
|
|
1258
|
+
|
|
1259
|
+
if (!role || !task) {
|
|
1260
|
+
return { error: "Both 'role' and 'task' are required for spawn_sub_agent" };
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
// Auto-condense parent context if caller didn't provide explicit context
|
|
1264
|
+
let resolvedContext = inheritedContext || null;
|
|
1265
|
+
if (!resolvedContext && Array.isArray(ctx.parentMessages)) {
|
|
1266
|
+
const recentMsgs = ctx.parentMessages
|
|
1267
|
+
.filter((m) => m.role === "assistant" && typeof m.content === "string")
|
|
1268
|
+
.slice(-3)
|
|
1269
|
+
.map((m) => m.content.substring(0, 200));
|
|
1270
|
+
if (recentMsgs.length > 0) {
|
|
1271
|
+
resolvedContext = recentMsgs.join("\n---\n");
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
|
|
1275
|
+
// Link child to parent session so registry-scoped queries and
|
|
1276
|
+
// session-close cascade cleanup can find it.
|
|
1277
|
+
const parentSessionId = ctx.sessionId || null;
|
|
1278
|
+
const interaction = ctx.interaction || null;
|
|
1279
|
+
|
|
1280
|
+
const subCtx = SubAgentContext.create({
|
|
1281
|
+
role,
|
|
1282
|
+
task,
|
|
1283
|
+
parentId: parentSessionId,
|
|
1284
|
+
inheritedContext: resolvedContext,
|
|
1285
|
+
allowedTools: allowedTools || null,
|
|
1286
|
+
cwd: ctx.cwd,
|
|
1287
|
+
});
|
|
1288
|
+
|
|
1289
|
+
const emit = (type, payload) => {
|
|
1290
|
+
if (!interaction || typeof interaction.emit !== "function") return;
|
|
1291
|
+
try {
|
|
1292
|
+
interaction.emit(type, {
|
|
1293
|
+
sessionId: parentSessionId,
|
|
1294
|
+
subAgentId: subCtx.id,
|
|
1295
|
+
parentSessionId,
|
|
1296
|
+
role: subCtx.role,
|
|
1297
|
+
...payload,
|
|
1298
|
+
});
|
|
1299
|
+
} catch (_err) {
|
|
1300
|
+
// Event emission is best-effort — never break the tool call
|
|
1301
|
+
}
|
|
1302
|
+
};
|
|
1303
|
+
|
|
1304
|
+
try {
|
|
1305
|
+
// Notify registry if available
|
|
1306
|
+
const { SubAgentRegistry } =
|
|
1307
|
+
await import("../lib/sub-agent-registry.js").catch(() => ({
|
|
1308
|
+
SubAgentRegistry: null,
|
|
1309
|
+
}));
|
|
1310
|
+
if (SubAgentRegistry) {
|
|
1311
|
+
try {
|
|
1312
|
+
SubAgentRegistry.getInstance().register(subCtx);
|
|
1313
|
+
} catch (_err) {
|
|
1314
|
+
// Registry not available — non-critical
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
emit("sub-agent.started", {
|
|
1319
|
+
task: subCtx.task,
|
|
1320
|
+
allowedTools: allowedTools || null,
|
|
1321
|
+
maxIterations: subCtx.maxIterations,
|
|
1322
|
+
createdAt: subCtx.createdAt,
|
|
1323
|
+
});
|
|
1324
|
+
|
|
1325
|
+
const result = await subCtx.run(task);
|
|
1326
|
+
|
|
1327
|
+
// Complete in registry
|
|
1328
|
+
if (SubAgentRegistry) {
|
|
1329
|
+
try {
|
|
1330
|
+
SubAgentRegistry.getInstance().complete(subCtx.id, result);
|
|
1331
|
+
} catch (_err) {
|
|
1332
|
+
// Non-critical
|
|
1333
|
+
}
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
emit("sub-agent.completed", {
|
|
1337
|
+
status: subCtx.status,
|
|
1338
|
+
summary: result.summary,
|
|
1339
|
+
toolsUsed: result.toolsUsed,
|
|
1340
|
+
iterationCount: result.iterationCount,
|
|
1341
|
+
tokenCount: result.tokenCount,
|
|
1342
|
+
artifactCount: result.artifacts.length,
|
|
1343
|
+
completedAt: subCtx.completedAt,
|
|
1344
|
+
});
|
|
1345
|
+
|
|
1346
|
+
return {
|
|
1347
|
+
success: true,
|
|
1348
|
+
subAgentId: subCtx.id,
|
|
1349
|
+
role: subCtx.role,
|
|
1350
|
+
parentSessionId,
|
|
1351
|
+
summary: result.summary,
|
|
1352
|
+
toolsUsed: result.toolsUsed,
|
|
1353
|
+
iterationCount: result.iterationCount,
|
|
1354
|
+
artifactCount: result.artifacts.length,
|
|
1355
|
+
};
|
|
1356
|
+
} catch (err) {
|
|
1357
|
+
subCtx.forceComplete(err.message);
|
|
1358
|
+
|
|
1359
|
+
emit("sub-agent.failed", {
|
|
1360
|
+
status: subCtx.status,
|
|
1361
|
+
error: err.message,
|
|
1362
|
+
completedAt: subCtx.completedAt,
|
|
1363
|
+
});
|
|
1364
|
+
|
|
1365
|
+
return {
|
|
1366
|
+
error: `Sub-agent failed: ${err.message}`,
|
|
1367
|
+
subAgentId: subCtx.id,
|
|
1368
|
+
role: subCtx.role,
|
|
1369
|
+
parentSessionId,
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
// ─── LLM chat with tools ─────────────────────────────────────────────────
|
|
1375
|
+
|
|
1376
|
+
/**
|
|
1377
|
+
* Send a chat completion request with tool definitions.
|
|
1378
|
+
* Supports 8 providers: ollama, anthropic, openai, deepseek, dashscope, gemini, mistral, volcengine
|
|
1379
|
+
*
|
|
1380
|
+
* @param {Array} rawMessages
|
|
1381
|
+
* @param {object} options
|
|
1382
|
+
* @returns {Promise<object>} response with .message
|
|
1383
|
+
*/
|
|
1384
|
+
export async function chatWithTools(rawMessages, options) {
|
|
1385
|
+
const {
|
|
1386
|
+
provider,
|
|
1387
|
+
model,
|
|
1388
|
+
baseUrl,
|
|
1389
|
+
apiKey,
|
|
1390
|
+
contextEngine: ce,
|
|
1391
|
+
signal,
|
|
1392
|
+
} = options;
|
|
1393
|
+
|
|
1394
|
+
const persona = _loadProjectPersona(options.cwd);
|
|
1395
|
+
const tools = getAgentToolDefinitions({
|
|
1396
|
+
names: options.enabledToolNames,
|
|
1397
|
+
disabledTools: persona?.toolsDisabled,
|
|
1398
|
+
extraTools: [
|
|
1399
|
+
...(options.hostManagedToolPolicy?.toolDefinitions || []),
|
|
1400
|
+
...(options.extraToolDefinitions || []),
|
|
1401
|
+
],
|
|
1402
|
+
});
|
|
1403
|
+
|
|
1404
|
+
const lastUserMsg = [...rawMessages].reverse().find((m) => m.role === "user");
|
|
1405
|
+
const messages = ce
|
|
1406
|
+
? ce.buildOptimizedMessages(rawMessages, {
|
|
1407
|
+
userQuery: lastUserMsg?.content,
|
|
1408
|
+
})
|
|
1409
|
+
: rawMessages;
|
|
1410
|
+
|
|
1411
|
+
throwIfAborted(signal);
|
|
1412
|
+
|
|
1413
|
+
if (provider === "ollama") {
|
|
1414
|
+
const response = await fetch(`${baseUrl}/api/chat`, {
|
|
1415
|
+
method: "POST",
|
|
1416
|
+
headers: { "Content-Type": "application/json" },
|
|
1417
|
+
signal,
|
|
1418
|
+
body: JSON.stringify({
|
|
1419
|
+
model,
|
|
1420
|
+
messages,
|
|
1421
|
+
tools,
|
|
1422
|
+
stream: false,
|
|
1423
|
+
}),
|
|
1424
|
+
});
|
|
1425
|
+
if (!response.ok) {
|
|
1426
|
+
throw new Error(`Ollama error: ${response.status}`);
|
|
1427
|
+
}
|
|
1428
|
+
return await response.json();
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
if (provider === "anthropic") {
|
|
1432
|
+
const key = apiKey || process.env.ANTHROPIC_API_KEY;
|
|
1433
|
+
if (!key) throw new Error("ANTHROPIC_API_KEY required");
|
|
1434
|
+
|
|
1435
|
+
const systemMsgs = messages.filter((m) => m.role === "system");
|
|
1436
|
+
const otherMsgs = messages.filter((m) => m.role !== "system");
|
|
1437
|
+
|
|
1438
|
+
const anthropicTools = tools.map((t) => ({
|
|
1439
|
+
name: t.function.name,
|
|
1440
|
+
description: t.function.description,
|
|
1441
|
+
input_schema: t.function.parameters,
|
|
1442
|
+
}));
|
|
1443
|
+
|
|
1444
|
+
const body = {
|
|
1445
|
+
model: model || "claude-sonnet-4-20250514",
|
|
1446
|
+
max_tokens: 8192,
|
|
1447
|
+
messages: otherMsgs,
|
|
1448
|
+
tools: anthropicTools,
|
|
1449
|
+
};
|
|
1450
|
+
if (systemMsgs.length > 0) {
|
|
1451
|
+
body.system = systemMsgs.map((m) => m.content).join("\n");
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
const url =
|
|
1455
|
+
baseUrl && baseUrl !== "http://localhost:11434"
|
|
1456
|
+
? baseUrl
|
|
1457
|
+
: "https://api.anthropic.com/v1";
|
|
1458
|
+
|
|
1459
|
+
const response = await fetch(`${url}/messages`, {
|
|
1460
|
+
method: "POST",
|
|
1461
|
+
headers: {
|
|
1462
|
+
"Content-Type": "application/json",
|
|
1463
|
+
"x-api-key": key,
|
|
1464
|
+
"anthropic-version": "2023-06-01",
|
|
1465
|
+
},
|
|
1466
|
+
signal,
|
|
1467
|
+
body: JSON.stringify(body),
|
|
1468
|
+
});
|
|
1469
|
+
|
|
1470
|
+
if (!response.ok) {
|
|
1471
|
+
throw new Error(`Anthropic error: ${response.status}`);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
const data = await response.json();
|
|
1475
|
+
return _normalizeAnthropicResponse(data);
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
// OpenAI-compatible providers
|
|
1479
|
+
const providerUrls = {
|
|
1480
|
+
openai: "https://api.openai.com/v1",
|
|
1481
|
+
deepseek: "https://api.deepseek.com/v1",
|
|
1482
|
+
dashscope: "https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
1483
|
+
mistral: "https://api.mistral.ai/v1",
|
|
1484
|
+
gemini: "https://generativelanguage.googleapis.com/v1beta/openai",
|
|
1485
|
+
volcengine: "https://ark.cn-beijing.volces.com/api/v3",
|
|
1486
|
+
};
|
|
1487
|
+
|
|
1488
|
+
const providerApiKeyEnvs = {
|
|
1489
|
+
openai: "OPENAI_API_KEY",
|
|
1490
|
+
deepseek: "DEEPSEEK_API_KEY",
|
|
1491
|
+
dashscope: "DASHSCOPE_API_KEY",
|
|
1492
|
+
mistral: "MISTRAL_API_KEY",
|
|
1493
|
+
gemini: "GEMINI_API_KEY",
|
|
1494
|
+
volcengine: "VOLCENGINE_API_KEY",
|
|
1495
|
+
};
|
|
1496
|
+
|
|
1497
|
+
const url =
|
|
1498
|
+
baseUrl && baseUrl !== "http://localhost:11434"
|
|
1499
|
+
? baseUrl
|
|
1500
|
+
: providerUrls[provider];
|
|
1501
|
+
|
|
1502
|
+
if (!url) {
|
|
1503
|
+
throw new Error(
|
|
1504
|
+
`Unsupported provider: ${provider}. Supported: ollama, anthropic, openai, deepseek, dashscope, mistral, gemini, volcengine`,
|
|
1505
|
+
);
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
const envKey = providerApiKeyEnvs[provider] || "OPENAI_API_KEY";
|
|
1509
|
+
const key = apiKey || process.env[envKey];
|
|
1510
|
+
if (!key) throw new Error(`${envKey} required for provider ${provider}`);
|
|
1511
|
+
|
|
1512
|
+
const defaultModels = {
|
|
1513
|
+
openai: "gpt-4o",
|
|
1514
|
+
deepseek: "deepseek-chat",
|
|
1515
|
+
dashscope: "qwen-turbo",
|
|
1516
|
+
mistral: "mistral-large-latest",
|
|
1517
|
+
gemini: "gemini-2.0-flash",
|
|
1518
|
+
volcengine: "doubao-seed-1-6-251015",
|
|
1519
|
+
};
|
|
1520
|
+
|
|
1521
|
+
const response = await fetch(`${url}/chat/completions`, {
|
|
1522
|
+
method: "POST",
|
|
1523
|
+
headers: {
|
|
1524
|
+
"Content-Type": "application/json",
|
|
1525
|
+
Authorization: `Bearer ${key}`,
|
|
1526
|
+
},
|
|
1527
|
+
signal,
|
|
1528
|
+
body: JSON.stringify({
|
|
1529
|
+
model: model || defaultModels[provider] || "gpt-4o-mini",
|
|
1530
|
+
messages,
|
|
1531
|
+
tools,
|
|
1532
|
+
}),
|
|
1533
|
+
});
|
|
1534
|
+
|
|
1535
|
+
if (!response.ok) {
|
|
1536
|
+
throw new Error(`${provider} API error: ${response.status}`);
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
const data = await response.json();
|
|
1540
|
+
if (!data.choices || !data.choices[0]) {
|
|
1541
|
+
throw new Error("Invalid API response: no choices returned");
|
|
1542
|
+
}
|
|
1543
|
+
const choice = data.choices[0];
|
|
1544
|
+
return { message: choice.message };
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
function _normalizeAnthropicResponse(data) {
|
|
1548
|
+
const content = data.content || [];
|
|
1549
|
+
const textBlocks = content.filter((b) => b.type === "text");
|
|
1550
|
+
const toolBlocks = content.filter((b) => b.type === "tool_use");
|
|
1551
|
+
|
|
1552
|
+
const message = {
|
|
1553
|
+
role: "assistant",
|
|
1554
|
+
content: textBlocks.map((b) => b.text).join("\n") || "",
|
|
1555
|
+
};
|
|
1556
|
+
|
|
1557
|
+
if (toolBlocks.length > 0) {
|
|
1558
|
+
message.tool_calls = toolBlocks.map((b) => ({
|
|
1559
|
+
id: b.id,
|
|
1560
|
+
type: "function",
|
|
1561
|
+
function: {
|
|
1562
|
+
name: b.name,
|
|
1563
|
+
arguments: JSON.stringify(b.input),
|
|
1564
|
+
},
|
|
1565
|
+
}));
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
return { message };
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
// ─── Agent loop (async generator) ─────────────────────────────────────────
|
|
1572
|
+
|
|
1573
|
+
/**
|
|
1574
|
+
* Async generator that drives the agentic tool-use loop.
|
|
1575
|
+
*
|
|
1576
|
+
* Yields events:
|
|
1577
|
+
* { type: "slot-filling", slot, question } — when asking user for missing info
|
|
1578
|
+
* { type: "tool-executing", tool, args }
|
|
1579
|
+
* { type: "tool-result", tool, result, error }
|
|
1580
|
+
* { type: "response-complete", content }
|
|
1581
|
+
*
|
|
1582
|
+
* @param {Array} messages - mutable messages array (will be appended to)
|
|
1583
|
+
* @param {object} options - provider, model, baseUrl, apiKey, contextEngine, hookDb, skillLoader, cwd, slotFiller, interaction
|
|
1584
|
+
*/
|
|
1585
|
+
export async function* agentLoop(messages, options) {
|
|
1586
|
+
const MAX_ITERATIONS = 15;
|
|
1587
|
+
const signal = options.signal || null;
|
|
1588
|
+
const toolContext = {
|
|
1589
|
+
hookDb: options.hookDb || null,
|
|
1590
|
+
skillLoader: options.skillLoader || _defaultSkillLoader,
|
|
1591
|
+
cwd: options.cwd || process.cwd(),
|
|
1592
|
+
planManager: options.planManager || null,
|
|
1593
|
+
sessionId: options.sessionId || null,
|
|
1594
|
+
hostManagedToolPolicy: options.hostManagedToolPolicy || null,
|
|
1595
|
+
externalToolDescriptors: options.externalToolDescriptors || null,
|
|
1596
|
+
externalToolExecutors: options.externalToolExecutors || null,
|
|
1597
|
+
mcpClient: options.mcpClient || null,
|
|
1598
|
+
parentMessages: messages, // pass parent messages for sub-agent auto-condensation
|
|
1599
|
+
interaction: options.interaction || null,
|
|
1600
|
+
};
|
|
1601
|
+
|
|
1602
|
+
throwIfAborted(signal);
|
|
1603
|
+
|
|
1604
|
+
// ── Slot-filling phase ──────────────────────────────────────────────
|
|
1605
|
+
// Before calling the LLM, check if the user's message matches a known
|
|
1606
|
+
// intent with missing required parameters. If so, interactively fill them
|
|
1607
|
+
// and append the gathered context to the user message.
|
|
1608
|
+
if (options.slotFiller && options.interaction) {
|
|
1609
|
+
const lastUserMsg = [...messages].reverse().find((m) => m.role === "user");
|
|
1610
|
+
if (lastUserMsg) {
|
|
1611
|
+
try {
|
|
1612
|
+
const { CLISlotFiller } = await import("../lib/slot-filler.js");
|
|
1613
|
+
const intent = CLISlotFiller.detectIntent(lastUserMsg.content);
|
|
1614
|
+
|
|
1615
|
+
if (intent) {
|
|
1616
|
+
const requiredSlots = CLISlotFiller.getSlotDefinitions(
|
|
1617
|
+
intent.type,
|
|
1618
|
+
).required;
|
|
1619
|
+
const missingSlots = requiredSlots.filter((s) => !intent.entities[s]);
|
|
1620
|
+
|
|
1621
|
+
if (missingSlots.length > 0) {
|
|
1622
|
+
const result = await options.slotFiller.fillSlots(intent, {
|
|
1623
|
+
cwd: options.cwd || process.cwd(),
|
|
1624
|
+
});
|
|
1625
|
+
|
|
1626
|
+
// Yield slot-filling events for each filled slot
|
|
1627
|
+
for (const slot of result.filledSlots) {
|
|
1628
|
+
yield {
|
|
1629
|
+
type: "slot-filling",
|
|
1630
|
+
slot,
|
|
1631
|
+
question: `Filled "${slot}" = "${result.entities[slot]}"`,
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
// Append gathered context to the user message so the LLM has full info
|
|
1636
|
+
if (result.filledSlots.length > 0) {
|
|
1637
|
+
const contextParts = Object.entries(result.entities)
|
|
1638
|
+
.filter(([, v]) => v)
|
|
1639
|
+
.map(([k, v]) => `${k}: ${v}`);
|
|
1640
|
+
lastUserMsg.content += `\n\n[Context — user provided: ${contextParts.join(", ")}]`;
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
}
|
|
1644
|
+
} catch (error) {
|
|
1645
|
+
if (isAbortError(error) || signal?.aborted) {
|
|
1646
|
+
throw error;
|
|
1647
|
+
}
|
|
1648
|
+
// Slot-filling failure is non-critical — proceed to LLM
|
|
1649
|
+
}
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
|
|
1653
|
+
// Phase 7 parity harness hook: tests can inject a mock LLM function via
|
|
1654
|
+
// `options.chatFn` to drive the loop deterministically without hitting a
|
|
1655
|
+
// real provider. Production code path is unchanged — the fallback is the
|
|
1656
|
+
// real `chatWithTools`.
|
|
1657
|
+
const llmCall = options.chatFn || chatWithTools;
|
|
1658
|
+
|
|
1659
|
+
for (let i = 0; i < MAX_ITERATIONS; i++) {
|
|
1660
|
+
throwIfAborted(signal);
|
|
1661
|
+
const result = await llmCall(messages, options);
|
|
1662
|
+
throwIfAborted(signal);
|
|
1663
|
+
const msg = result?.message;
|
|
1664
|
+
|
|
1665
|
+
if (!msg) {
|
|
1666
|
+
yield { type: "response-complete", content: "(No response from LLM)" };
|
|
1667
|
+
return;
|
|
1668
|
+
}
|
|
1669
|
+
|
|
1670
|
+
const toolCalls = msg.tool_calls;
|
|
1671
|
+
|
|
1672
|
+
if (!toolCalls || toolCalls.length === 0) {
|
|
1673
|
+
yield { type: "response-complete", content: msg.content || "" };
|
|
1674
|
+
return;
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
// Add assistant message with tool calls
|
|
1678
|
+
messages.push(msg);
|
|
1679
|
+
|
|
1680
|
+
for (const call of toolCalls) {
|
|
1681
|
+
throwIfAborted(signal);
|
|
1682
|
+
const fn = call.function;
|
|
1683
|
+
const toolName = fn.name;
|
|
1684
|
+
let toolArgs;
|
|
1685
|
+
|
|
1686
|
+
try {
|
|
1687
|
+
toolArgs =
|
|
1688
|
+
typeof fn.arguments === "string"
|
|
1689
|
+
? JSON.parse(fn.arguments)
|
|
1690
|
+
: fn.arguments;
|
|
1691
|
+
} catch {
|
|
1692
|
+
toolArgs = {};
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
yield { type: "tool-executing", tool: toolName, args: toolArgs };
|
|
1696
|
+
|
|
1697
|
+
let toolResult;
|
|
1698
|
+
let toolError = null;
|
|
1699
|
+
try {
|
|
1700
|
+
toolResult = await executeTool(toolName, toolArgs, toolContext);
|
|
1701
|
+
} catch (err) {
|
|
1702
|
+
toolResult = { error: err.message };
|
|
1703
|
+
toolError = err.message;
|
|
1704
|
+
}
|
|
1705
|
+
|
|
1706
|
+
throwIfAborted(signal);
|
|
1707
|
+
|
|
1708
|
+
yield {
|
|
1709
|
+
type: "tool-result",
|
|
1710
|
+
tool: toolName,
|
|
1711
|
+
result: toolResult,
|
|
1712
|
+
error: toolError,
|
|
1713
|
+
};
|
|
1714
|
+
|
|
1715
|
+
messages.push({
|
|
1716
|
+
role: "tool",
|
|
1717
|
+
content: JSON.stringify(toolResult).substring(0, 5000),
|
|
1718
|
+
tool_call_id: call.id,
|
|
1719
|
+
});
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
|
|
1723
|
+
yield {
|
|
1724
|
+
type: "response-complete",
|
|
1725
|
+
content: "(Reached max tool call iterations)",
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
// ─── Format helpers ───────────────────────────────────────────────────────
|
|
1730
|
+
|
|
1731
|
+
export function formatToolArgs(name, args) {
|
|
1732
|
+
switch (name) {
|
|
1733
|
+
case "read_file":
|
|
1734
|
+
return args.path;
|
|
1735
|
+
case "write_file":
|
|
1736
|
+
return `${args.path} (${args.content?.length || 0} chars)`;
|
|
1737
|
+
case "edit_file":
|
|
1738
|
+
return args.path;
|
|
1739
|
+
case "edit_file_hashed":
|
|
1740
|
+
return `${args.path} @${args.anchor_hash}`;
|
|
1741
|
+
case "run_shell":
|
|
1742
|
+
return args.command;
|
|
1743
|
+
case "git":
|
|
1744
|
+
return args.command;
|
|
1745
|
+
case "search_files":
|
|
1746
|
+
return args.pattern;
|
|
1747
|
+
case "list_dir":
|
|
1748
|
+
return args.path || ".";
|
|
1749
|
+
case "run_skill":
|
|
1750
|
+
return `${args.skill_name}: ${(args.input || "").substring(0, 50)}`;
|
|
1751
|
+
case "list_skills":
|
|
1752
|
+
return args.category || args.query || "all";
|
|
1753
|
+
case "run_code":
|
|
1754
|
+
return `${args.language} (${(args.code || "").length} chars)`;
|
|
1755
|
+
case "spawn_sub_agent":
|
|
1756
|
+
return `[${args.role}] ${(args.task || "").substring(0, 60)}`;
|
|
1757
|
+
default:
|
|
1758
|
+
return JSON.stringify(args).substring(0, 60);
|
|
1759
|
+
}
|
|
1760
|
+
}
|