kovence-cli 1.2.0 → 1.3.0
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/CHANGELOG.md +38 -0
- package/README.md +66 -6
- package/nd.js +22 -1
- package/package.json +1 -1
- package/providers.js +524 -113
- package/src/agent/history.js +502 -9
- package/src/agent/project_context.js +219 -24
- package/src/agent/request_logger.js +148 -0
- package/src/agent/resilience.js +296 -46
- package/src/agent/streaming_write.js +23 -15
- package/src/agent/subagent.js +655 -0
- package/src/agent/turn.js +1210 -269
- package/src/cli/args.js +9 -1
- package/src/cli/sinks.js +188 -106
- package/src/commands/handlers.js +245 -7
- package/src/config/model_registry.js +39 -2
- package/src/config/sessions.js +19 -2
- package/src/config/skills.js +425 -0
- package/src/permissions/engine.js +22 -6
- package/src/permissions/store.js +4 -1
- package/src/settings/schema.js +298 -9
- package/src/settings/store.js +75 -6
- package/src/tools/browser.js +722 -0
- package/src/tools/edit.js +471 -0
- package/src/tools/exec.js +349 -34
- package/src/tools/patch_git.js +12 -1
- package/src/tools/read_tracker.js +87 -0
- package/src/tools/tasks.js +68 -28
- package/tools.js +778 -171
- package/tui.js +142 -30
- package/ui.js +22 -1
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const fs = require("node:fs");
|
|
4
|
+
const path = require("node:path");
|
|
5
|
+
const { DEFAULT_SYSTEM_PROMPT, normalizeAgentsConfig } = require("../settings/schema");
|
|
6
|
+
const {
|
|
7
|
+
buildStableSystemPrompt,
|
|
8
|
+
gatherEnvironmentSummary,
|
|
9
|
+
loadProjectInstructionsDetailed,
|
|
10
|
+
} = require("./project_context");
|
|
11
|
+
const { loadProviders } = require("../config/providers");
|
|
12
|
+
const { getEnvFallback } = require("../commands/handlers");
|
|
13
|
+
const { ReadTracker } = require("../tools/read_tracker");
|
|
14
|
+
|
|
15
|
+
const EXPLORE_ALLOWED_TOOLS = new Set([
|
|
16
|
+
"list_dir",
|
|
17
|
+
"glob_files",
|
|
18
|
+
"read_file",
|
|
19
|
+
"search_files",
|
|
20
|
+
"git_status",
|
|
21
|
+
"git_diff",
|
|
22
|
+
"git_log",
|
|
23
|
+
"web_fetch",
|
|
24
|
+
]);
|
|
25
|
+
|
|
26
|
+
const GENERAL_EXCLUDED_TOOLS = new Set([
|
|
27
|
+
"task",
|
|
28
|
+
"todo_write",
|
|
29
|
+
"memory",
|
|
30
|
+
"save_session_memory",
|
|
31
|
+
"save_global_memory",
|
|
32
|
+
"delete_global_memory",
|
|
33
|
+
]);
|
|
34
|
+
|
|
35
|
+
const SUBAGENT_MAX_OUTPUT_CHARS = 12000;
|
|
36
|
+
|
|
37
|
+
const MODE_RESTRICTIVENESS = {
|
|
38
|
+
plan: 0,
|
|
39
|
+
default: 1,
|
|
40
|
+
"accept-edits": 2,
|
|
41
|
+
auto: 3,
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const EXPLORE_ROLE_ADDENDUM = [
|
|
45
|
+
"# Sub-agent role: explore",
|
|
46
|
+
"- You are a fast read-only codebase researcher.",
|
|
47
|
+
"- Inspect files, search symbols, and trace callers using your read-only tools.",
|
|
48
|
+
"- Never modify files or state; cite exact file paths, symbol names, and path:line ranges.",
|
|
49
|
+
"- Report only what you directly observed, concisely, as the parent receives only your final answer.",
|
|
50
|
+
].join("\n");
|
|
51
|
+
|
|
52
|
+
const GENERAL_ROLE_ADDENDUM = [
|
|
53
|
+
"# Sub-agent role: general",
|
|
54
|
+
"- Execute the delegated subtask autonomously within parent permissions.",
|
|
55
|
+
"- Read relevant files before editing, keep changes targeted, and verify with tests/commands when appropriate.",
|
|
56
|
+
"- Do not expect interactive follow-ups; finish completely and report exact files changed, commands run, and results.",
|
|
57
|
+
].join("\n");
|
|
58
|
+
|
|
59
|
+
function createMutex() {
|
|
60
|
+
let tail = Promise.resolve();
|
|
61
|
+
return {
|
|
62
|
+
run(fn) {
|
|
63
|
+
const next = tail.then(
|
|
64
|
+
() => fn(),
|
|
65
|
+
() => fn()
|
|
66
|
+
);
|
|
67
|
+
tail = next.catch(() => {});
|
|
68
|
+
return next;
|
|
69
|
+
},
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function createSemaphore(limit = 3) {
|
|
74
|
+
const cap = Math.max(1, Number(limit) || 3);
|
|
75
|
+
let active = 0;
|
|
76
|
+
const waiters = [];
|
|
77
|
+
const acquire = () => {
|
|
78
|
+
if (active < cap) {
|
|
79
|
+
active += 1;
|
|
80
|
+
return Promise.resolve();
|
|
81
|
+
}
|
|
82
|
+
return new Promise((resolve) => waiters.push(resolve));
|
|
83
|
+
};
|
|
84
|
+
const release = () => {
|
|
85
|
+
if (waiters.length > 0) {
|
|
86
|
+
const wake = waiters.shift();
|
|
87
|
+
wake();
|
|
88
|
+
} else if (active > 0) {
|
|
89
|
+
active -= 1;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
return {
|
|
93
|
+
async run(fn) {
|
|
94
|
+
await acquire();
|
|
95
|
+
try {
|
|
96
|
+
return await fn();
|
|
97
|
+
} finally {
|
|
98
|
+
release();
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function createSubagentCoordinator(settings = {}) {
|
|
105
|
+
const agentsCfg = normalizeAgentsConfig(settings?.agents);
|
|
106
|
+
return {
|
|
107
|
+
semaphore: createSemaphore(agentsCfg.maxParallel),
|
|
108
|
+
generalMutex: createMutex(),
|
|
109
|
+
approvalMutex: createMutex(),
|
|
110
|
+
parallelGeneral: Boolean(agentsCfg.parallelGeneral),
|
|
111
|
+
maxParallel: agentsCfg.maxParallel,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function narrowAgentMode(parentMode = "default", requestedMode = "") {
|
|
116
|
+
const pRank = MODE_RESTRICTIVENESS[parentMode] ?? MODE_RESTRICTIVENESS.default;
|
|
117
|
+
if (!requestedMode) return parentMode || "default";
|
|
118
|
+
const req = String(requestedMode).trim().toLowerCase();
|
|
119
|
+
if (!(req in MODE_RESTRICTIVENESS)) return parentMode || "default";
|
|
120
|
+
const rRank = MODE_RESTRICTIVENESS[req];
|
|
121
|
+
return rRank < pRank ? req : parentMode;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function parseListValue(raw) {
|
|
125
|
+
const s = String(raw || "").trim();
|
|
126
|
+
if (!s) return [];
|
|
127
|
+
const stripped = s.startsWith("[") && s.endsWith("]") ? s.slice(1, -1) : s;
|
|
128
|
+
return stripped
|
|
129
|
+
.split(",")
|
|
130
|
+
.map((x) => x.trim().replace(/^["']|["']$/g, ""))
|
|
131
|
+
.filter(Boolean);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Tiny dependency-free YAML frontmatter parser for `.kovence/agents/*.md`.
|
|
136
|
+
*/
|
|
137
|
+
function parseAgentMarkdownFile(rawText, fallbackName = "") {
|
|
138
|
+
const text = String(rawText || "").replace(/\r\n/g, "\n");
|
|
139
|
+
const match = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
140
|
+
const meta = {};
|
|
141
|
+
let body = text.trim();
|
|
142
|
+
|
|
143
|
+
if (match) {
|
|
144
|
+
const fmLines = match[1].split("\n");
|
|
145
|
+
body = match[2].trim();
|
|
146
|
+
let activeListKey = null;
|
|
147
|
+
for (const line of fmLines) {
|
|
148
|
+
const listItem = line.match(/^\s*-\s+(.+)$/);
|
|
149
|
+
if (listItem && activeListKey) {
|
|
150
|
+
if (!Array.isArray(meta[activeListKey])) meta[activeListKey] = [];
|
|
151
|
+
meta[activeListKey].push(listItem[1].trim().replace(/^["']|["']$/g, ""));
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const kv = line.match(/^([A-Za-z0-9_.-]+)\s*:\s*(.*)$/);
|
|
155
|
+
if (!kv) {
|
|
156
|
+
activeListKey = null;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const k = kv[1].trim();
|
|
160
|
+
const v = kv[2].trim();
|
|
161
|
+
if (!v) {
|
|
162
|
+
meta[k] = [];
|
|
163
|
+
activeListKey = k;
|
|
164
|
+
} else {
|
|
165
|
+
activeListKey = null;
|
|
166
|
+
meta[k] = v.replace(/^["']|["']$/g, "");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const rawAllowed = meta.tools ?? meta.allowed_tools ?? meta.allowedTools;
|
|
172
|
+
const rawDisallowed = meta.disallowed_tools ?? meta.disallowedTools;
|
|
173
|
+
const allowedTools = Array.isArray(rawAllowed)
|
|
174
|
+
? rawAllowed
|
|
175
|
+
: typeof rawAllowed === "string"
|
|
176
|
+
? parseListValue(rawAllowed)
|
|
177
|
+
: null;
|
|
178
|
+
const disallowedTools = Array.isArray(rawDisallowed)
|
|
179
|
+
? rawDisallowed
|
|
180
|
+
: typeof rawDisallowed === "string"
|
|
181
|
+
? parseListValue(rawDisallowed)
|
|
182
|
+
: [];
|
|
183
|
+
|
|
184
|
+
const maxRaw = Number.parseInt(String(meta.max_steps ?? meta.maxSteps ?? ""), 10);
|
|
185
|
+
const maxSteps = Number.isSafeInteger(maxRaw) && maxRaw >= 1 ? maxRaw : null;
|
|
186
|
+
const tempRaw = meta.temperature !== undefined && meta.temperature !== "" ? Number(meta.temperature) : null;
|
|
187
|
+
const temperature = Number.isFinite(tempRaw) && tempRaw >= 0 && tempRaw <= 2 ? tempRaw : null;
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
name: String(meta.name || fallbackName || "")
|
|
191
|
+
.trim()
|
|
192
|
+
.toLowerCase(),
|
|
193
|
+
description: String(meta.description || "").trim(),
|
|
194
|
+
baseRole: String(meta.role || meta.base || "")
|
|
195
|
+
.trim()
|
|
196
|
+
.toLowerCase(),
|
|
197
|
+
allowedTools: allowedTools ? new Set(allowedTools) : null,
|
|
198
|
+
disallowedTools: new Set(disallowedTools),
|
|
199
|
+
model: String(meta.model || "").trim(),
|
|
200
|
+
provider: String(meta.provider || "").trim(),
|
|
201
|
+
maxSteps,
|
|
202
|
+
temperature,
|
|
203
|
+
agentMode: String(meta.agentMode || meta.mode || meta.permissionMode || "")
|
|
204
|
+
.trim()
|
|
205
|
+
.toLowerCase(),
|
|
206
|
+
prompt: body,
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function loadCustomAgentDefs(workspaceRoot = process.cwd(), paths = null) {
|
|
211
|
+
const defs = new Map();
|
|
212
|
+
const sources = [];
|
|
213
|
+
if (paths?.globalDir) sources.push({ dir: path.join(paths.globalDir, "agents"), scope: "global" });
|
|
214
|
+
sources.push({ dir: path.join(workspaceRoot, ".kovence", "agents"), scope: "project" });
|
|
215
|
+
|
|
216
|
+
for (const { dir, scope } of sources) {
|
|
217
|
+
let entries;
|
|
218
|
+
try {
|
|
219
|
+
if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) continue;
|
|
220
|
+
entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
221
|
+
} catch {
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
for (const entry of entries) {
|
|
225
|
+
if ((!entry.isFile() && !entry.isSymbolicLink()) || !entry.name.endsWith(".md")) continue;
|
|
226
|
+
const fullPath = path.join(dir, entry.name);
|
|
227
|
+
try {
|
|
228
|
+
const raw = fs.readFileSync(fullPath, "utf8");
|
|
229
|
+
const fallbackName = path.basename(entry.name, ".md");
|
|
230
|
+
const parsed = parseAgentMarkdownFile(raw, fallbackName);
|
|
231
|
+
// Untrusted project-level .kovence/agents/*.md may narrow permissions/model/temp, never redirect provider
|
|
232
|
+
if (scope === "project") parsed.provider = "";
|
|
233
|
+
parsed.source = scope;
|
|
234
|
+
if (parsed.name) defs.set(parsed.name, parsed);
|
|
235
|
+
} catch {
|
|
236
|
+
// Skip unreadable custom agent file
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return defs;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function capSubagentOutput(text, maxChars = SUBAGENT_MAX_OUTPUT_CHARS) {
|
|
244
|
+
const str = String(text || "").trim();
|
|
245
|
+
if (str.length <= maxChars) return str;
|
|
246
|
+
const headLen = Math.floor(maxChars * 0.6);
|
|
247
|
+
const tailLen = maxChars - headLen - 64;
|
|
248
|
+
const omitted = str.length - headLen - tailLen;
|
|
249
|
+
return `${str.slice(0, headLen)}\n\n... [output capped, omitted ${omitted} chars] ...\n\n${str.slice(str.length - tailLen)}`;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function resolveSubagentTarget({
|
|
253
|
+
agentName,
|
|
254
|
+
customDef = null,
|
|
255
|
+
parentProvider = null,
|
|
256
|
+
parentModel = "",
|
|
257
|
+
settings = {},
|
|
258
|
+
paths = null,
|
|
259
|
+
}) {
|
|
260
|
+
const agentsCfg = normalizeAgentsConfig(settings?.agents);
|
|
261
|
+
const roleCfg = agentName === "explore" ? agentsCfg.explore : agentsCfg.general;
|
|
262
|
+
|
|
263
|
+
let childProvider = parentProvider;
|
|
264
|
+
const requestedProvider = String(roleCfg?.provider || customDef?.provider || "").trim();
|
|
265
|
+
if (requestedProvider && requestedProvider !== parentProvider?.name) {
|
|
266
|
+
try {
|
|
267
|
+
const store = loadProviders(getEnvFallback(), paths || undefined);
|
|
268
|
+
if (store?.providers?.[requestedProvider]) {
|
|
269
|
+
childProvider = store.providers[requestedProvider];
|
|
270
|
+
}
|
|
271
|
+
} catch {
|
|
272
|
+
// Fall back to parentProvider cleanly
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const childModel = String(
|
|
277
|
+
roleCfg?.model || customDef?.model || parentModel || childProvider?.defaultModel || ""
|
|
278
|
+
).trim();
|
|
279
|
+
return { childProvider, childModel, roleCfg };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function validateAgentModelSettings(settings, provStore) {
|
|
283
|
+
const warnings = [];
|
|
284
|
+
const agentsCfg = normalizeAgentsConfig(settings?.agents);
|
|
285
|
+
const providersMap = provStore?.providers || {};
|
|
286
|
+
|
|
287
|
+
for (const role of ["explore", "general"]) {
|
|
288
|
+
const cfg = agentsCfg[role];
|
|
289
|
+
if (!cfg) continue;
|
|
290
|
+
let targetProvider = provStore?.active ? providersMap[provStore.active] : null;
|
|
291
|
+
|
|
292
|
+
if (cfg.provider) {
|
|
293
|
+
if (!providersMap[cfg.provider]) {
|
|
294
|
+
warnings.push(
|
|
295
|
+
`Agent '${role}' references unknown provider '${cfg.provider}'; falling back to parent provider.`
|
|
296
|
+
);
|
|
297
|
+
targetProvider = null;
|
|
298
|
+
} else {
|
|
299
|
+
targetProvider = providersMap[cfg.provider];
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (cfg.model && targetProvider && Array.isArray(targetProvider.models) && targetProvider.models.length > 0) {
|
|
303
|
+
if (!targetProvider.models.includes(cfg.model)) {
|
|
304
|
+
warnings.push(
|
|
305
|
+
`Agent '${role}' specifies model '${cfg.model}' not listed on provider '${targetProvider.name}'.`
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return warnings;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function resolveChildTools({ agentName, customDef = null, childModel, childProvider, settings, getToolsForRequest }) {
|
|
314
|
+
const isExplore = agentName === "explore" || customDef?.baseRole === "explore";
|
|
315
|
+
const baseDefs = getToolsForRequest({
|
|
316
|
+
model: childModel,
|
|
317
|
+
providerType: childProvider?.type || "",
|
|
318
|
+
toolset: isExplore ? "full" : settings?.toolset || "core",
|
|
319
|
+
includeTask: false,
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
const filtered = baseDefs.filter((def) => {
|
|
323
|
+
const name = def?.function?.name;
|
|
324
|
+
if (!name || GENERAL_EXCLUDED_TOOLS.has(name)) return false;
|
|
325
|
+
if (isExplore && !EXPLORE_ALLOWED_TOOLS.has(name)) return false;
|
|
326
|
+
// Narrow-only overrides from optional .kovence/agents/*.md
|
|
327
|
+
if (customDef?.allowedTools && !customDef.allowedTools.has(name)) return false;
|
|
328
|
+
if (customDef?.disallowedTools && customDef.disallowedTools.has(name)) return false;
|
|
329
|
+
return true;
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
return {
|
|
333
|
+
isExplore,
|
|
334
|
+
toolDefs: filtered,
|
|
335
|
+
allowedNames: new Set(filtered.map((d) => d.function.name)),
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function buildChildSystemPrompt({
|
|
340
|
+
agentName,
|
|
341
|
+
customDef = null,
|
|
342
|
+
isExplore,
|
|
343
|
+
childModel,
|
|
344
|
+
childProvider,
|
|
345
|
+
settings,
|
|
346
|
+
workspaceRoot,
|
|
347
|
+
effectiveAgentMode,
|
|
348
|
+
}) {
|
|
349
|
+
const stable = buildStableSystemPrompt({
|
|
350
|
+
systemPrompt: DEFAULT_SYSTEM_PROMPT,
|
|
351
|
+
model: childModel,
|
|
352
|
+
providerType: childProvider?.type || "",
|
|
353
|
+
language: settings?.language || "banglish",
|
|
354
|
+
includeDelegation: false,
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
const parts = [stable, isExplore ? EXPLORE_ROLE_ADDENDUM : GENERAL_ROLE_ADDENDUM];
|
|
358
|
+
if (customDef?.prompt) {
|
|
359
|
+
parts.push(`# Custom agent instructions (${agentName})\n${customDef.prompt}`);
|
|
360
|
+
}
|
|
361
|
+
parts.push(`Workspace Root: ${workspaceRoot}\nEnvironment: ${gatherEnvironmentSummary(workspaceRoot)}`);
|
|
362
|
+
|
|
363
|
+
const proj = loadProjectInstructionsDetailed(workspaceRoot);
|
|
364
|
+
if (proj.text) parts.push(proj.text);
|
|
365
|
+
|
|
366
|
+
if (effectiveAgentMode === "plan") {
|
|
367
|
+
parts.push(
|
|
368
|
+
[
|
|
369
|
+
"AGENT MODE = PLAN (READ-ONLY):",
|
|
370
|
+
"Investigate using read-only tools only. Do NOT modify files or run mutating commands.",
|
|
371
|
+
].join("\n")
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
return parts.join("\n\n");
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function createChildSink({ parentSink, description, onActivity }) {
|
|
378
|
+
const labelPrefix = `[sub-agent: ${description}]`;
|
|
379
|
+
let toolCallCount = 0;
|
|
380
|
+
|
|
381
|
+
return {
|
|
382
|
+
isTui: false,
|
|
383
|
+
interactive: Boolean(parentSink?.interactive),
|
|
384
|
+
headless: true,
|
|
385
|
+
log(kind, msg) {
|
|
386
|
+
if (kind === "tool" && String(msg || "").startsWith("⚙")) {
|
|
387
|
+
toolCallCount += 1;
|
|
388
|
+
onActivity?.({ toolCalls: toolCallCount });
|
|
389
|
+
} else if (kind === "permission" && parentSink?.log) {
|
|
390
|
+
parentSink.log("permission", String(msg || "").startsWith(labelPrefix) ? msg : `${labelPrefix} ${msg}`);
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
setBusy() {},
|
|
394
|
+
syncStatus() {},
|
|
395
|
+
notify: () => parentSink?.notify?.(),
|
|
396
|
+
startThinking() {
|
|
397
|
+
return {
|
|
398
|
+
stop() {},
|
|
399
|
+
write() {},
|
|
400
|
+
end() {},
|
|
401
|
+
setLabel() {},
|
|
402
|
+
};
|
|
403
|
+
},
|
|
404
|
+
confirm: parentSink?.confirm ? (prompt) => parentSink.confirm(prompt) : undefined,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Execute an isolated child sub-agent loop (`explore` or `general`) and return only final text + 1 stats line.
|
|
410
|
+
*/
|
|
411
|
+
async function runSubagentTask(args, ctx = {}) {
|
|
412
|
+
const { runAgentLoop, createAbortError } = require("./turn");
|
|
413
|
+
const { getToolsForRequest } = require("../../tools");
|
|
414
|
+
|
|
415
|
+
const prompt = String(args?.prompt || "").trim();
|
|
416
|
+
if (!prompt) return "Error: task 'prompt' is required and cannot be empty.";
|
|
417
|
+
|
|
418
|
+
const rawAgent = String(args?.agent || args?.subagent_type || "explore")
|
|
419
|
+
.trim()
|
|
420
|
+
.toLowerCase();
|
|
421
|
+
const description = String(args?.description || `${rawAgent} task`)
|
|
422
|
+
.replace(/\s+/g, " ")
|
|
423
|
+
.trim()
|
|
424
|
+
.slice(0, 60);
|
|
425
|
+
|
|
426
|
+
const workspaceRoot = ctx.workspaceRoot || ctx.cwd || process.cwd();
|
|
427
|
+
const customDefs = loadCustomAgentDefs(workspaceRoot, ctx.paths);
|
|
428
|
+
const customDef = customDefs.get(rawAgent) || null;
|
|
429
|
+
const isKnownBuiltin = rawAgent === "explore" || rawAgent === "general";
|
|
430
|
+
|
|
431
|
+
if (!isKnownBuiltin && !customDef) {
|
|
432
|
+
return `Error: Unknown sub-agent '${rawAgent}'. Use 'explore' or 'general' (or define .kovence/agents/${rawAgent}.md).`;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
const settings = ctx.settings || {};
|
|
436
|
+
const agentsCfg = normalizeAgentsConfig(settings.agents);
|
|
437
|
+
const coordinator = ctx.subagentCoordinator || createSubagentCoordinator(settings);
|
|
438
|
+
|
|
439
|
+
const isExplore = rawAgent === "explore" || customDef?.baseRole === "explore";
|
|
440
|
+
const { childProvider, childModel, roleCfg } = resolveSubagentTarget({
|
|
441
|
+
agentName: rawAgent,
|
|
442
|
+
customDef,
|
|
443
|
+
parentProvider: ctx.provider || null,
|
|
444
|
+
parentModel: ctx.model || "",
|
|
445
|
+
settings,
|
|
446
|
+
paths: ctx.paths || null,
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
if (!childProvider || childProvider.empty) {
|
|
450
|
+
return "Error: Sub-agent cannot run because no active AI provider is configured.";
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
const { toolDefs, allowedNames } = resolveChildTools({
|
|
454
|
+
agentName: rawAgent,
|
|
455
|
+
customDef,
|
|
456
|
+
childModel,
|
|
457
|
+
childProvider,
|
|
458
|
+
settings,
|
|
459
|
+
getToolsForRequest,
|
|
460
|
+
});
|
|
461
|
+
|
|
462
|
+
// Narrow-only permission inheritance: explore is hard read-only; general can only restrict parent mode
|
|
463
|
+
const parentMode = settings.agentMode || "default";
|
|
464
|
+
const narrowedFromMd = customDef?.agentMode ? narrowAgentMode(parentMode, customDef.agentMode) : parentMode;
|
|
465
|
+
const effectiveAgentMode = isExplore ? "plan" : narrowedFromMd;
|
|
466
|
+
const childSettings = {
|
|
467
|
+
...settings,
|
|
468
|
+
agentMode: effectiveAgentMode,
|
|
469
|
+
autoSummarize: false,
|
|
470
|
+
...(customDef?.temperature !== null && customDef?.temperature !== undefined
|
|
471
|
+
? { temperature: customDef.temperature }
|
|
472
|
+
: {}),
|
|
473
|
+
};
|
|
474
|
+
|
|
475
|
+
const configuredMaxSteps = Number(roleCfg?.maxSteps) || 30;
|
|
476
|
+
const maxSteps =
|
|
477
|
+
customDef?.maxSteps && customDef.maxSteps < configuredMaxSteps ? customDef.maxSteps : configuredMaxSteps;
|
|
478
|
+
|
|
479
|
+
const childPrompt = buildChildSystemPrompt({
|
|
480
|
+
agentName: rawAgent,
|
|
481
|
+
customDef,
|
|
482
|
+
isExplore,
|
|
483
|
+
childModel,
|
|
484
|
+
childProvider,
|
|
485
|
+
settings: childSettings,
|
|
486
|
+
workspaceRoot,
|
|
487
|
+
effectiveAgentMode,
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
// Derived AbortController linked to parent signal
|
|
491
|
+
const parentSignal = ctx.signal || null;
|
|
492
|
+
const childAbort = new AbortController();
|
|
493
|
+
const onParentAbort = () =>
|
|
494
|
+
childAbort.abort(parentSignal?.reason || createAbortError("Sub-agent cancelled by parent"));
|
|
495
|
+
if (parentSignal) {
|
|
496
|
+
if (parentSignal.aborted) {
|
|
497
|
+
throw createAbortError("Task cancelled by user");
|
|
498
|
+
}
|
|
499
|
+
parentSignal.addEventListener("abort", onParentAbort, { once: true });
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
const startedAt = Date.now();
|
|
503
|
+
let liveToolCalls = 0;
|
|
504
|
+
const uiHandle = ctx.startSubagent ? ctx.startSubagent({ agent: rawAgent, description }) : null;
|
|
505
|
+
if (!uiHandle && ctx.log) {
|
|
506
|
+
ctx.log("tool", `⚙ task(${rawAgent}): ${description} (started)`);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
const refreshTicker = uiHandle
|
|
510
|
+
? setInterval(() => {
|
|
511
|
+
uiHandle.update({
|
|
512
|
+
toolCalls: liveToolCalls,
|
|
513
|
+
elapsedMs: Date.now() - startedAt,
|
|
514
|
+
});
|
|
515
|
+
}, 500)
|
|
516
|
+
: null;
|
|
517
|
+
|
|
518
|
+
const runSlot = async () => {
|
|
519
|
+
if (childAbort.signal.aborted) {
|
|
520
|
+
throw createAbortError("Task cancelled by user");
|
|
521
|
+
}
|
|
522
|
+
const childHistory = [{ role: "user", content: prompt }];
|
|
523
|
+
const childSink = createChildSink({
|
|
524
|
+
parentSink: ctx.parentSink || ctx,
|
|
525
|
+
description,
|
|
526
|
+
onActivity: ({ toolCalls }) => {
|
|
527
|
+
liveToolCalls = toolCalls;
|
|
528
|
+
uiHandle?.update({
|
|
529
|
+
toolCalls: liveToolCalls,
|
|
530
|
+
elapsedMs: Date.now() - startedAt,
|
|
531
|
+
});
|
|
532
|
+
},
|
|
533
|
+
});
|
|
534
|
+
|
|
535
|
+
const childStats = {
|
|
536
|
+
promptTokens: 0,
|
|
537
|
+
completionTokens: 0,
|
|
538
|
+
cacheReadTokens: 0,
|
|
539
|
+
cacheWriteTokens: 0,
|
|
540
|
+
requests: 0,
|
|
541
|
+
};
|
|
542
|
+
const result = await runAgentLoop({
|
|
543
|
+
history: childHistory,
|
|
544
|
+
tools: toolDefs,
|
|
545
|
+
systemPrompt: childPrompt,
|
|
546
|
+
provider: childProvider,
|
|
547
|
+
model: childModel,
|
|
548
|
+
settings: childSettings,
|
|
549
|
+
maxSteps,
|
|
550
|
+
signal: childAbort.signal,
|
|
551
|
+
sink: childSink,
|
|
552
|
+
capabilities: ctx.capabilities || {},
|
|
553
|
+
onTurnStats: (turn) => {
|
|
554
|
+
childStats.requests += 1;
|
|
555
|
+
if (turn.usage) {
|
|
556
|
+
childStats.promptTokens += turn.usage.prompt_tokens || 0;
|
|
557
|
+
childStats.completionTokens += turn.usage.completion_tokens || 0;
|
|
558
|
+
childStats.cacheReadTokens += turn.usage.cache_read_input_tokens || 0;
|
|
559
|
+
childStats.cacheWriteTokens += turn.usage.cache_creation_input_tokens || 0;
|
|
560
|
+
}
|
|
561
|
+
},
|
|
562
|
+
permissions: {
|
|
563
|
+
workspaceRoot,
|
|
564
|
+
paths: ctx.paths || null,
|
|
565
|
+
extraDirs: ctx.extraDirs || [],
|
|
566
|
+
settings: childSettings,
|
|
567
|
+
sessionRules: ctx.sessionRules || [],
|
|
568
|
+
readTracker: new ReadTracker(),
|
|
569
|
+
sudoPasswords: ctx.sudoPasswords || new Map(),
|
|
570
|
+
bgTasks: ctx.bgTasks || null,
|
|
571
|
+
noSession: true,
|
|
572
|
+
allowedToolNames: allowedNames,
|
|
573
|
+
blockedToolNames: GENERAL_EXCLUDED_TOOLS,
|
|
574
|
+
forceReadOnly: isExplore,
|
|
575
|
+
approvalMutex: coordinator.approvalMutex,
|
|
576
|
+
approvalLabel: `[sub-agent: ${description}]`,
|
|
577
|
+
},
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
// Credit child token usage to parent session stats if present
|
|
581
|
+
if (ctx.session?.stats) {
|
|
582
|
+
ctx.session.stats.promptTokens = (ctx.session.stats.promptTokens || 0) + childStats.promptTokens;
|
|
583
|
+
ctx.session.stats.completionTokens =
|
|
584
|
+
(ctx.session.stats.completionTokens || 0) + childStats.completionTokens;
|
|
585
|
+
ctx.session.stats.cacheReadTokens = (ctx.session.stats.cacheReadTokens || 0) + childStats.cacheReadTokens;
|
|
586
|
+
ctx.session.stats.cacheWriteTokens =
|
|
587
|
+
(ctx.session.stats.cacheWriteTokens || 0) + childStats.cacheWriteTokens;
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const totalTools = result.stats?.toolCalls ?? liveToolCalls;
|
|
591
|
+
const totalSteps = result.stats?.steps ?? childStats.requests;
|
|
592
|
+
const totalTokens = childStats.promptTokens + childStats.completionTokens;
|
|
593
|
+
const elapsedMs = Date.now() - startedAt;
|
|
594
|
+
const sec = (elapsedMs / 1000).toFixed(1);
|
|
595
|
+
|
|
596
|
+
if (!result.ok || !String(result.answer || "").trim()) {
|
|
597
|
+
const reason = result.answer || "sub-agent returned an empty response";
|
|
598
|
+
uiHandle?.finish({ ok: false, toolCalls: totalTools, elapsedMs, error: reason });
|
|
599
|
+
if (!uiHandle && ctx.log) {
|
|
600
|
+
ctx.log("tool", `✗ task(${rawAgent}): ${description} - ${totalTools} tool calls - ${sec}s`);
|
|
601
|
+
}
|
|
602
|
+
return `Error: Sub-agent '${rawAgent}' failed: ${reason}`;
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
uiHandle?.finish({ ok: true, toolCalls: totalTools, elapsedMs });
|
|
606
|
+
if (!uiHandle && ctx.log) {
|
|
607
|
+
ctx.log("tool", `✓ task(${rawAgent}): ${description} - ${totalTools} tool calls - ${sec}s`);
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
const capped = capSubagentOutput(result.answer, SUBAGENT_MAX_OUTPUT_CHARS);
|
|
611
|
+
const statsLine = `[sub-agent(${rawAgent}): ${totalSteps} step(s) · ${totalTools} tool call(s) · ${totalTokens} tokens (${childStats.promptTokens} in/${childStats.completionTokens} out) · ${sec}s]`;
|
|
612
|
+
return `${capped}\n\n${statsLine}`;
|
|
613
|
+
};
|
|
614
|
+
|
|
615
|
+
try {
|
|
616
|
+
// Acquire generalMutex before semaphore when serialized so waiting general tasks don't block explore slots.
|
|
617
|
+
if (!isExplore && !agentsCfg.parallelGeneral) {
|
|
618
|
+
return await coordinator.generalMutex.run(() => coordinator.semaphore.run(runSlot));
|
|
619
|
+
}
|
|
620
|
+
return await coordinator.semaphore.run(runSlot);
|
|
621
|
+
} catch (err) {
|
|
622
|
+
const elapsedMs = Date.now() - startedAt;
|
|
623
|
+
const sec = (elapsedMs / 1000).toFixed(1);
|
|
624
|
+
if (parentSignal?.aborted || err?.name === "AbortError" || err?.aborted) {
|
|
625
|
+
uiHandle?.finish({ ok: false, toolCalls: liveToolCalls, elapsedMs, error: "cancelled" });
|
|
626
|
+
throw createAbortError(err?.message || "Task cancelled by user");
|
|
627
|
+
}
|
|
628
|
+
uiHandle?.finish({ ok: false, toolCalls: liveToolCalls, elapsedMs, error: err.message });
|
|
629
|
+
if (!uiHandle && ctx.log) {
|
|
630
|
+
ctx.log("tool", `✗ task(${rawAgent}): ${description} - ${liveToolCalls} tool calls - ${sec}s`);
|
|
631
|
+
}
|
|
632
|
+
return `Error: Sub-agent '${rawAgent}' failed: ${err.message}`;
|
|
633
|
+
} finally {
|
|
634
|
+
if (refreshTicker) clearInterval(refreshTicker);
|
|
635
|
+
parentSignal?.removeEventListener("abort", onParentAbort);
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
module.exports = {
|
|
640
|
+
EXPLORE_ALLOWED_TOOLS,
|
|
641
|
+
GENERAL_EXCLUDED_TOOLS,
|
|
642
|
+
SUBAGENT_MAX_OUTPUT_CHARS,
|
|
643
|
+
createMutex,
|
|
644
|
+
createSemaphore,
|
|
645
|
+
createSubagentCoordinator,
|
|
646
|
+
narrowAgentMode,
|
|
647
|
+
parseAgentMarkdownFile,
|
|
648
|
+
loadCustomAgentDefs,
|
|
649
|
+
capSubagentOutput,
|
|
650
|
+
resolveSubagentTarget,
|
|
651
|
+
validateAgentModelSettings,
|
|
652
|
+
resolveChildTools,
|
|
653
|
+
buildChildSystemPrompt,
|
|
654
|
+
runSubagentTask,
|
|
655
|
+
};
|