@listdoing/core 0.1.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/dist/index.d.mts +1441 -0
- package/dist/index.d.ts +1441 -0
- package/dist/index.js +3940 -0
- package/dist/index.mjs +3879 -0
- package/package.json +24 -0
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,3879 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var SENSITIVE_PERMISSIONS = /* @__PURE__ */ new Set(["filesystem", "network", "compute"]);
|
|
3
|
+
var PERMISSION_MODE_DEFAULTS = {
|
|
4
|
+
strict: {
|
|
5
|
+
"dom.read": "auto",
|
|
6
|
+
"dom.write.style": "auto",
|
|
7
|
+
"dom.write.content": "approval",
|
|
8
|
+
"dom.write.attribute": "force-approval",
|
|
9
|
+
"dom.write.structure": "force-approval",
|
|
10
|
+
"dom.write": "force-approval",
|
|
11
|
+
"compute.eval": "approval",
|
|
12
|
+
"compute.dom": "disabled",
|
|
13
|
+
"compute.network": "disabled",
|
|
14
|
+
"compute.storage": "disabled",
|
|
15
|
+
"compute": "force-approval",
|
|
16
|
+
"filesystem": "force-approval",
|
|
17
|
+
"network": "force-approval"
|
|
18
|
+
},
|
|
19
|
+
standard: {
|
|
20
|
+
"dom.read": "auto",
|
|
21
|
+
"dom.write.style": "auto",
|
|
22
|
+
"dom.write.content": "auto",
|
|
23
|
+
"dom.write.attribute": "approval",
|
|
24
|
+
"dom.write.structure": "approval",
|
|
25
|
+
"dom.write": "approval",
|
|
26
|
+
"compute.eval": "auto",
|
|
27
|
+
"compute.dom": "approval",
|
|
28
|
+
"compute.network": "force-approval",
|
|
29
|
+
"compute.storage": "force-approval",
|
|
30
|
+
"compute": "approval",
|
|
31
|
+
"filesystem": "approval",
|
|
32
|
+
"network": "force-approval"
|
|
33
|
+
},
|
|
34
|
+
trusted: {
|
|
35
|
+
"dom.read": "auto",
|
|
36
|
+
"dom.write.style": "auto",
|
|
37
|
+
"dom.write.content": "auto",
|
|
38
|
+
"dom.write.attribute": "auto",
|
|
39
|
+
"dom.write.structure": "auto",
|
|
40
|
+
"dom.write": "auto",
|
|
41
|
+
"compute.eval": "auto",
|
|
42
|
+
"compute.dom": "auto",
|
|
43
|
+
"compute.network": "auto",
|
|
44
|
+
"compute.storage": "auto",
|
|
45
|
+
"compute": "auto",
|
|
46
|
+
"filesystem": "auto",
|
|
47
|
+
"network": "auto"
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
var ACPErrorCodes = {
|
|
51
|
+
AGENT_NOT_INITIALIZED: -32100,
|
|
52
|
+
SKILL_NOT_FOUND: -32101,
|
|
53
|
+
SKILL_HANDLER_NOT_REGISTERED: -32102,
|
|
54
|
+
SKILL_REGISTRATION_FAILED: -32103,
|
|
55
|
+
SKILL_EXECUTION_FAILED: -32104,
|
|
56
|
+
SKILL_EXECUTION_TIMEOUT: -32105,
|
|
57
|
+
SKILL_PERMISSION_DENIED: -32106,
|
|
58
|
+
SKILL_PERMISSION_DISABLED: -32109,
|
|
59
|
+
SKILL_REJECTED: -32107,
|
|
60
|
+
SKILL_LOCATION_UNAVAILABLE: -32108,
|
|
61
|
+
SESSION_NOT_FOUND: -32110,
|
|
62
|
+
CONTEXT_OVERFLOW: -32120,
|
|
63
|
+
CONTEXT_COMPRESS_FAILED: -32121,
|
|
64
|
+
CONTEXT_SYNC_FAILED: -32122,
|
|
65
|
+
LLM_CALL_FAILED: -32130,
|
|
66
|
+
LLM_TOKEN_LIMIT: -32131,
|
|
67
|
+
LLM_RATE_LIMIT: -32132,
|
|
68
|
+
LLM_PROVIDER_UNAVAILABLE: -32133,
|
|
69
|
+
TOKEN_BUDGET_EXCEEDED: -32134,
|
|
70
|
+
TASK_PLAN_FAILED: -32160,
|
|
71
|
+
TASK_STEP_FAILED: -32161,
|
|
72
|
+
GRAPH_PLAN_FAILED: -32170,
|
|
73
|
+
GRAPH_CYCLE_DETECTED: -32171,
|
|
74
|
+
GRAPH_NODE_FAILED: -32172,
|
|
75
|
+
GRAPH_EXECUTION_ABORTED: -32173,
|
|
76
|
+
SUBAGENT_DEPTH_EXCEEDED: -32174,
|
|
77
|
+
SUBAGENT_TIMEOUT: -32175,
|
|
78
|
+
CODE_EXEC_DISABLED: -32180,
|
|
79
|
+
CODE_EXEC_TIMEOUT: -32181,
|
|
80
|
+
CODE_EXEC_LANGUAGE_NOT_SUPPORTED: -32182,
|
|
81
|
+
CODE_EXEC_PATH_NOT_ALLOWED: -32183,
|
|
82
|
+
PERSISTENCE_ERROR: -32140,
|
|
83
|
+
TRANSPORT_ERROR: -32141,
|
|
84
|
+
AUTH_REQUIRED: -32150,
|
|
85
|
+
AUTH_FAILED: -32151,
|
|
86
|
+
AUTH_FORBIDDEN: -32152,
|
|
87
|
+
SERVER_UNAVAILABLE: -32153
|
|
88
|
+
};
|
|
89
|
+
var ACPError = class extends Error {
|
|
90
|
+
constructor(code, message, data) {
|
|
91
|
+
super(message);
|
|
92
|
+
this.code = code;
|
|
93
|
+
this.data = data;
|
|
94
|
+
this.name = "ACPError";
|
|
95
|
+
}
|
|
96
|
+
toJSON() {
|
|
97
|
+
return {
|
|
98
|
+
code: this.code,
|
|
99
|
+
message: this.message,
|
|
100
|
+
data: this.data
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
// src/content/adapters/openai.ts
|
|
106
|
+
var OpenAIContentAdapter = class {
|
|
107
|
+
formatContent(blocks) {
|
|
108
|
+
return blocks.map((block) => {
|
|
109
|
+
switch (block.type) {
|
|
110
|
+
case "text":
|
|
111
|
+
return { type: "text", text: block.text };
|
|
112
|
+
case "image":
|
|
113
|
+
return {
|
|
114
|
+
type: "image_url",
|
|
115
|
+
image_url: {
|
|
116
|
+
url: block.data.startsWith("http") ? block.data : `data:${block.mimeType};base64,${block.data}`
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
case "resource":
|
|
120
|
+
return { type: "text", text: block.resource.text ?? block.resource.uri };
|
|
121
|
+
}
|
|
122
|
+
});
|
|
123
|
+
}
|
|
124
|
+
formatMessageContent(content) {
|
|
125
|
+
if (typeof content === "string") return content;
|
|
126
|
+
return this.formatContent(content);
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// src/llm/openai.ts
|
|
131
|
+
var OpenAIAdapter = class {
|
|
132
|
+
constructor(config) {
|
|
133
|
+
this.config = config;
|
|
134
|
+
this.contentAdapter = new OpenAIContentAdapter();
|
|
135
|
+
}
|
|
136
|
+
getBaseUrl() {
|
|
137
|
+
if (this.config.baseUrl) return this.config.baseUrl;
|
|
138
|
+
switch (this.config.adapter) {
|
|
139
|
+
case "ollama":
|
|
140
|
+
return "http://localhost:11434/v1";
|
|
141
|
+
case "anthropic":
|
|
142
|
+
return "https://api.anthropic.com/v1";
|
|
143
|
+
default:
|
|
144
|
+
return "https://api.openai.com/v1";
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
getEndpoint() {
|
|
148
|
+
const base = this.getBaseUrl().replace(/\/+$/, "");
|
|
149
|
+
return `${base}/chat/completions`;
|
|
150
|
+
}
|
|
151
|
+
buildHeaders() {
|
|
152
|
+
const headers = {
|
|
153
|
+
"Content-Type": "application/json"
|
|
154
|
+
};
|
|
155
|
+
if (this.config.headers) {
|
|
156
|
+
Object.assign(headers, this.config.headers);
|
|
157
|
+
}
|
|
158
|
+
if (this.config.apiKey && !Object.keys(headers).some((k) => k.toLowerCase() === "authorization")) {
|
|
159
|
+
headers["Authorization"] = `Bearer ${this.config.apiKey}`;
|
|
160
|
+
}
|
|
161
|
+
return headers;
|
|
162
|
+
}
|
|
163
|
+
messagesToOpenAI(messages) {
|
|
164
|
+
return messages.map((m) => {
|
|
165
|
+
const content = typeof m.content === "string" ? m.content : this.contentAdapter.formatMessageContent(m.content);
|
|
166
|
+
if (m.role === "tool") {
|
|
167
|
+
return {
|
|
168
|
+
role: "tool",
|
|
169
|
+
tool_call_id: m.toolCallId,
|
|
170
|
+
content
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
if (m.role === "assistant" && m.toolCalls?.length) {
|
|
174
|
+
return {
|
|
175
|
+
role: "assistant",
|
|
176
|
+
content: content || null,
|
|
177
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
178
|
+
id: tc.id,
|
|
179
|
+
type: "function",
|
|
180
|
+
function: {
|
|
181
|
+
name: tc.name,
|
|
182
|
+
arguments: JSON.stringify(tc.arguments)
|
|
183
|
+
}
|
|
184
|
+
}))
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
return { role: m.role, content };
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
toolsToOpenAI(tools) {
|
|
191
|
+
return tools.map((t) => ({
|
|
192
|
+
type: "function",
|
|
193
|
+
function: {
|
|
194
|
+
name: t.name,
|
|
195
|
+
description: t.description,
|
|
196
|
+
parameters: t.inputSchema
|
|
197
|
+
}
|
|
198
|
+
}));
|
|
199
|
+
}
|
|
200
|
+
async chat(messages, tools, options) {
|
|
201
|
+
if (this.config.adapter === "custom" && this.config.transformRequest && this.config.transformResponse) {
|
|
202
|
+
const reqBody = this.config.transformRequest(messages, tools, {});
|
|
203
|
+
const res2 = await fetch(this.getEndpoint(), {
|
|
204
|
+
method: "POST",
|
|
205
|
+
headers: this.buildHeaders(),
|
|
206
|
+
body: JSON.stringify(reqBody),
|
|
207
|
+
signal: options?.signal
|
|
208
|
+
});
|
|
209
|
+
if (!res2.ok) {
|
|
210
|
+
const text = await res2.text().catch(() => "");
|
|
211
|
+
this.checkContextOverflow(res2.status, text);
|
|
212
|
+
throw new Error(`LLM request failed: ${res2.status} ${text}`);
|
|
213
|
+
}
|
|
214
|
+
const data2 = await res2.json();
|
|
215
|
+
return this.config.transformResponse(data2);
|
|
216
|
+
}
|
|
217
|
+
const body = {
|
|
218
|
+
model: this.config.model,
|
|
219
|
+
messages: this.messagesToOpenAI(messages)
|
|
220
|
+
};
|
|
221
|
+
if (tools.length > 0) {
|
|
222
|
+
body.tools = this.toolsToOpenAI(tools);
|
|
223
|
+
}
|
|
224
|
+
if (this.config.temperature !== void 0) {
|
|
225
|
+
body.temperature = this.config.temperature;
|
|
226
|
+
}
|
|
227
|
+
if (this.config.maxTokens !== void 0) {
|
|
228
|
+
body.max_tokens = this.config.maxTokens;
|
|
229
|
+
}
|
|
230
|
+
if (this.config.extraBody) {
|
|
231
|
+
Object.assign(body, this.config.extraBody);
|
|
232
|
+
}
|
|
233
|
+
const res = await fetch(this.getEndpoint(), {
|
|
234
|
+
method: "POST",
|
|
235
|
+
headers: this.buildHeaders(),
|
|
236
|
+
body: JSON.stringify(body),
|
|
237
|
+
signal: options?.signal
|
|
238
|
+
});
|
|
239
|
+
if (!res.ok) {
|
|
240
|
+
const text = await res.text().catch(() => "");
|
|
241
|
+
this.checkContextOverflow(res.status, text);
|
|
242
|
+
throw new Error(`LLM request failed: ${res.status} ${text}`);
|
|
243
|
+
}
|
|
244
|
+
const data = await res.json();
|
|
245
|
+
return this.parseResponse(data);
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Stream LLM responses token-by-token via SSE.
|
|
249
|
+
* Yields StreamEvent for each token or tool_call delta.
|
|
250
|
+
* Collects the full response and returns it at the end.
|
|
251
|
+
*/
|
|
252
|
+
async *chatStream(messages, tools, options) {
|
|
253
|
+
const body = {
|
|
254
|
+
model: this.config.model,
|
|
255
|
+
messages: this.messagesToOpenAI(messages),
|
|
256
|
+
stream: true
|
|
257
|
+
};
|
|
258
|
+
if (tools.length > 0) {
|
|
259
|
+
body.tools = this.toolsToOpenAI(tools);
|
|
260
|
+
}
|
|
261
|
+
if (this.config.temperature !== void 0) {
|
|
262
|
+
body.temperature = this.config.temperature;
|
|
263
|
+
}
|
|
264
|
+
if (this.config.maxTokens !== void 0) {
|
|
265
|
+
body.max_tokens = this.config.maxTokens;
|
|
266
|
+
}
|
|
267
|
+
if (this.config.extraBody) {
|
|
268
|
+
Object.assign(body, this.config.extraBody);
|
|
269
|
+
}
|
|
270
|
+
const res = await fetch(this.getEndpoint(), {
|
|
271
|
+
method: "POST",
|
|
272
|
+
headers: this.buildHeaders(),
|
|
273
|
+
body: JSON.stringify(body),
|
|
274
|
+
signal: options?.signal
|
|
275
|
+
});
|
|
276
|
+
if (!res.ok) {
|
|
277
|
+
const text = await res.text().catch(() => "");
|
|
278
|
+
this.checkContextOverflow(res.status, text);
|
|
279
|
+
throw new Error(`LLM request failed: ${res.status} ${text}`);
|
|
280
|
+
}
|
|
281
|
+
const reader = res.body?.getReader();
|
|
282
|
+
if (!reader) {
|
|
283
|
+
const data = await res.json();
|
|
284
|
+
const parsed = this.parseResponse(data);
|
|
285
|
+
if (parsed.content) {
|
|
286
|
+
yield { type: "llm_text", content: parsed.content };
|
|
287
|
+
}
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
const decoder = new TextDecoder();
|
|
291
|
+
let buffer = "";
|
|
292
|
+
let content = "";
|
|
293
|
+
let reasoning = "";
|
|
294
|
+
const toolCallMap = /* @__PURE__ */ new Map();
|
|
295
|
+
try {
|
|
296
|
+
while (true) {
|
|
297
|
+
const { done, value } = await reader.read();
|
|
298
|
+
if (done) break;
|
|
299
|
+
buffer += decoder.decode(value, { stream: true });
|
|
300
|
+
const lines = buffer.split("\n");
|
|
301
|
+
buffer = lines.pop() ?? "";
|
|
302
|
+
for (const line of lines) {
|
|
303
|
+
const trimmed = line.trim();
|
|
304
|
+
if (!trimmed || !trimmed.startsWith("data:")) continue;
|
|
305
|
+
const data = trimmed.slice(5).trim();
|
|
306
|
+
if (data === "[DONE]") continue;
|
|
307
|
+
try {
|
|
308
|
+
const chunk = JSON.parse(data);
|
|
309
|
+
const delta = chunk.choices?.[0]?.delta;
|
|
310
|
+
if (!delta) continue;
|
|
311
|
+
if (delta.content) {
|
|
312
|
+
content += delta.content;
|
|
313
|
+
yield { type: "llm_text", content: delta.content };
|
|
314
|
+
}
|
|
315
|
+
if (delta.reasoning_content) {
|
|
316
|
+
reasoning += delta.reasoning_content;
|
|
317
|
+
yield { type: "llm_thinking", content: delta.reasoning_content };
|
|
318
|
+
}
|
|
319
|
+
if (delta.tool_calls) {
|
|
320
|
+
for (const tc of delta.tool_calls) {
|
|
321
|
+
const idx = tc.index ?? 0;
|
|
322
|
+
if (!toolCallMap.has(idx)) {
|
|
323
|
+
toolCallMap.set(idx, {
|
|
324
|
+
id: tc.id ?? "",
|
|
325
|
+
name: tc.function?.name ?? "",
|
|
326
|
+
arguments: ""
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
const entry = toolCallMap.get(idx);
|
|
330
|
+
if (tc.id) entry.id = tc.id;
|
|
331
|
+
if (tc.function?.name) entry.name = tc.function.name;
|
|
332
|
+
if (tc.function?.arguments) entry.arguments += tc.function.arguments;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
} catch {
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
} finally {
|
|
340
|
+
reader.releaseLock();
|
|
341
|
+
}
|
|
342
|
+
const toolCalls = [];
|
|
343
|
+
for (const [_, tc] of toolCallMap) {
|
|
344
|
+
let args = {};
|
|
345
|
+
try {
|
|
346
|
+
args = JSON.parse(tc.arguments || "{}");
|
|
347
|
+
} catch {
|
|
348
|
+
args = {};
|
|
349
|
+
}
|
|
350
|
+
toolCalls.push({ id: tc.id, name: tc.name, arguments: args });
|
|
351
|
+
}
|
|
352
|
+
yield {
|
|
353
|
+
type: "llm_response",
|
|
354
|
+
response: {
|
|
355
|
+
content,
|
|
356
|
+
reasoning: reasoning || void 0,
|
|
357
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
|
|
358
|
+
usage: void 0,
|
|
359
|
+
finishReason: toolCalls.length > 0 ? "tool_calls" : "stop"
|
|
360
|
+
}
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
/**
|
|
364
|
+
* Check if the error response indicates context length exceeded.
|
|
365
|
+
* Throws ACPError with CONTEXT_OVERFLOW code if detected.
|
|
366
|
+
*/
|
|
367
|
+
checkContextOverflow(status, body) {
|
|
368
|
+
if (status !== 400 && status !== 413) return;
|
|
369
|
+
let errMsg = body.toLowerCase();
|
|
370
|
+
try {
|
|
371
|
+
const errData = JSON.parse(body);
|
|
372
|
+
errMsg = (errData.error?.message ?? body).toLowerCase();
|
|
373
|
+
} catch {
|
|
374
|
+
}
|
|
375
|
+
if (errMsg.includes("context_length_exceeded") || errMsg.includes("maximum context length") || errMsg.includes("too many tokens")) {
|
|
376
|
+
throw new ACPError(ACPErrorCodes.CONTEXT_OVERFLOW, errMsg, { isContextOverflow: true });
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
parseResponse(data) {
|
|
380
|
+
const choice = data.choices?.[0];
|
|
381
|
+
if (!choice) {
|
|
382
|
+
throw new Error("No choices in LLM response");
|
|
383
|
+
}
|
|
384
|
+
const message = choice.message;
|
|
385
|
+
const content = message?.content || "";
|
|
386
|
+
const reasoning = message?.reasoning_content || void 0;
|
|
387
|
+
const toolCalls = [];
|
|
388
|
+
if (message?.tool_calls?.length) {
|
|
389
|
+
for (const tc of message.tool_calls) {
|
|
390
|
+
let args = {};
|
|
391
|
+
try {
|
|
392
|
+
args = JSON.parse(tc.function.arguments || "{}");
|
|
393
|
+
} catch {
|
|
394
|
+
args = {};
|
|
395
|
+
}
|
|
396
|
+
toolCalls.push({
|
|
397
|
+
id: tc.id,
|
|
398
|
+
name: tc.function.name,
|
|
399
|
+
arguments: args
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
content,
|
|
405
|
+
reasoning,
|
|
406
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : void 0,
|
|
407
|
+
usage: data.usage ? { input: data.usage.prompt_tokens, output: data.usage.completion_tokens } : void 0,
|
|
408
|
+
finishReason: choice.finish_reason
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
|
|
413
|
+
// src/skill/registry.ts
|
|
414
|
+
var SkillRegistry = class {
|
|
415
|
+
constructor() {
|
|
416
|
+
this.skills = /* @__PURE__ */ new Map();
|
|
417
|
+
}
|
|
418
|
+
register(skill) {
|
|
419
|
+
if (this.skills.has(skill.name)) {
|
|
420
|
+
console.warn(`Skill "${skill.name}" already registered, overwriting.`);
|
|
421
|
+
}
|
|
422
|
+
this.skills.set(skill.name, {
|
|
423
|
+
definition: skill,
|
|
424
|
+
handler: skill.handler
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
unregister(name) {
|
|
428
|
+
return this.skills.delete(name);
|
|
429
|
+
}
|
|
430
|
+
get(name) {
|
|
431
|
+
return this.skills.get(name)?.definition;
|
|
432
|
+
}
|
|
433
|
+
getHandler(name) {
|
|
434
|
+
return this.skills.get(name)?.handler;
|
|
435
|
+
}
|
|
436
|
+
list() {
|
|
437
|
+
return Array.from(this.skills.values()).map((s) => s.definition);
|
|
438
|
+
}
|
|
439
|
+
listToolDefs(filter) {
|
|
440
|
+
let skills = this.list();
|
|
441
|
+
if (filter?.tiers?.length) {
|
|
442
|
+
const tierSet = new Set(filter.tiers);
|
|
443
|
+
skills = skills.filter((s) => tierSet.has(s.tier ?? "system"));
|
|
444
|
+
}
|
|
445
|
+
if (filter?.permissions?.length) {
|
|
446
|
+
const permSet = new Set(filter.permissions);
|
|
447
|
+
skills = skills.filter((s) => {
|
|
448
|
+
const perms = s.permissions ?? [];
|
|
449
|
+
return perms.length === 0 || perms.some((p) => permSet.has(p));
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
return skills.map((s) => {
|
|
453
|
+
const workflowDef = s.workflow ?? s._clawWorkflow;
|
|
454
|
+
let mode = "call";
|
|
455
|
+
let estimatedTurns;
|
|
456
|
+
let stepCount;
|
|
457
|
+
if (s.agentLoop) {
|
|
458
|
+
mode = "loop";
|
|
459
|
+
estimatedTurns = s.agentLoop.maxTurns;
|
|
460
|
+
} else if (workflowDef) {
|
|
461
|
+
mode = "workflow";
|
|
462
|
+
stepCount = workflowDef.steps.length;
|
|
463
|
+
}
|
|
464
|
+
return {
|
|
465
|
+
name: s.name,
|
|
466
|
+
description: s.description,
|
|
467
|
+
inputSchema: s.inputSchema,
|
|
468
|
+
mode,
|
|
469
|
+
tier: s.tier ?? "system",
|
|
470
|
+
...s.permissions && { permissions: s.permissions },
|
|
471
|
+
...s.parallelSafe !== void 0 && { parallelSafe: s.parallelSafe },
|
|
472
|
+
...estimatedTurns != null && { estimatedTurns },
|
|
473
|
+
...stepCount != null && { stepCount }
|
|
474
|
+
};
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
has(name) {
|
|
478
|
+
return this.skills.has(name);
|
|
479
|
+
}
|
|
480
|
+
clear() {
|
|
481
|
+
this.skills.clear();
|
|
482
|
+
}
|
|
483
|
+
};
|
|
484
|
+
|
|
485
|
+
// src/skill/executor.ts
|
|
486
|
+
var SkillExecutor = class {
|
|
487
|
+
constructor(registry, worker) {
|
|
488
|
+
this.registry = registry;
|
|
489
|
+
this.worker = worker ?? {
|
|
490
|
+
async execute(def, params, ctx) {
|
|
491
|
+
const handler = registry.getHandler(def.name);
|
|
492
|
+
if (!handler) {
|
|
493
|
+
throw new ACPError(
|
|
494
|
+
ACPErrorCodes.SKILL_HANDLER_NOT_REGISTERED,
|
|
495
|
+
`Skill handler not registered: ${def.name}`,
|
|
496
|
+
{ name: def.name }
|
|
497
|
+
);
|
|
498
|
+
}
|
|
499
|
+
return handler(params, ctx);
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
getWorker() {
|
|
504
|
+
return this.worker;
|
|
505
|
+
}
|
|
506
|
+
getRegistry() {
|
|
507
|
+
return this.registry;
|
|
508
|
+
}
|
|
509
|
+
async execute(name, params, context) {
|
|
510
|
+
const def = this.registry.get(name);
|
|
511
|
+
if (!def) {
|
|
512
|
+
throw new ACPError(ACPErrorCodes.SKILL_NOT_FOUND, `Skill not found: ${name}`, { name });
|
|
513
|
+
}
|
|
514
|
+
const timeout = def.timeout ?? 3e4;
|
|
515
|
+
const controller = new AbortController();
|
|
516
|
+
const onParentAbort = () => controller.abort();
|
|
517
|
+
context.signal.addEventListener("abort", onParentAbort);
|
|
518
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
519
|
+
const execContext = {
|
|
520
|
+
...context,
|
|
521
|
+
signal: controller.signal
|
|
522
|
+
};
|
|
523
|
+
try {
|
|
524
|
+
const result = await this.worker.execute(def, params, execContext);
|
|
525
|
+
return result;
|
|
526
|
+
} catch (err) {
|
|
527
|
+
if (err.name === "AbortError" || controller.signal.aborted) {
|
|
528
|
+
throw new ACPError(
|
|
529
|
+
ACPErrorCodes.SKILL_EXECUTION_TIMEOUT,
|
|
530
|
+
`Skill execution timeout: ${name}`,
|
|
531
|
+
{ name, timeout }
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
if (err instanceof ACPError) throw err;
|
|
535
|
+
throw new ACPError(
|
|
536
|
+
ACPErrorCodes.SKILL_EXECUTION_FAILED,
|
|
537
|
+
`Skill execution failed: ${name}: ${err.message}`,
|
|
538
|
+
{ name, error: err.message }
|
|
539
|
+
);
|
|
540
|
+
} finally {
|
|
541
|
+
clearTimeout(timeoutId);
|
|
542
|
+
context.signal.removeEventListener("abort", onParentAbort);
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
/**
|
|
546
|
+
* Directly invoke a skill by name — used by ctx.invoke().
|
|
547
|
+
* No LLM loop, no approval. Shares parent's signal and timeout context.
|
|
548
|
+
*/
|
|
549
|
+
async invokeDirect(name, params, context) {
|
|
550
|
+
const def = this.registry.get(name);
|
|
551
|
+
if (!def) {
|
|
552
|
+
return {
|
|
553
|
+
content: [{ type: "text", text: `Skill not found: ${name}` }],
|
|
554
|
+
isError: true
|
|
555
|
+
};
|
|
556
|
+
}
|
|
557
|
+
const handler = this.registry.getHandler(name);
|
|
558
|
+
if (!handler) {
|
|
559
|
+
return {
|
|
560
|
+
content: [{ type: "text", text: `Skill handler not registered: ${name}` }],
|
|
561
|
+
isError: true
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
if (def.location === "server") {
|
|
565
|
+
return {
|
|
566
|
+
content: [{ type: "text", text: `Cannot invoke server-side skill directly: ${name}` }],
|
|
567
|
+
isError: true
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
try {
|
|
571
|
+
return await handler(params, context);
|
|
572
|
+
} catch (err) {
|
|
573
|
+
return {
|
|
574
|
+
content: [{ type: "text", text: `Invoke failed: ${err.message}` }],
|
|
575
|
+
isError: true
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
// src/skill/template.ts
|
|
582
|
+
function interpolateTemplate(template, variables) {
|
|
583
|
+
return template.replace(/\{\{([^}]+)\}\}/g, (_match, path) => {
|
|
584
|
+
const value = resolvePath(variables, path.trim());
|
|
585
|
+
if (value === void 0 || value === null) return "";
|
|
586
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
587
|
+
return String(value);
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
function interpolateInstruction(instruction, inputs) {
|
|
591
|
+
return interpolateTemplate(instruction, { inputs, steps: {} });
|
|
592
|
+
}
|
|
593
|
+
function resolvePath(obj, path) {
|
|
594
|
+
const parts = path.split(".");
|
|
595
|
+
let current = obj;
|
|
596
|
+
for (const part of parts) {
|
|
597
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
598
|
+
current = current[part];
|
|
599
|
+
}
|
|
600
|
+
return current;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// src/skill/permission.ts
|
|
604
|
+
function resolvePermissionPolicy(params) {
|
|
605
|
+
const {
|
|
606
|
+
skill,
|
|
607
|
+
args,
|
|
608
|
+
globalMode,
|
|
609
|
+
globalOverrides,
|
|
610
|
+
autoApprove,
|
|
611
|
+
chatMode,
|
|
612
|
+
requireApproval
|
|
613
|
+
} = params;
|
|
614
|
+
if (autoApprove) return "auto";
|
|
615
|
+
if (requireApproval?.has(skill.name)) return "force-approval";
|
|
616
|
+
const effectiveMode = chatMode ?? globalMode;
|
|
617
|
+
const requiredPermissions = resolveRequiredPermissions(skill, args);
|
|
618
|
+
let mostRestrictive = "auto";
|
|
619
|
+
for (const perm of requiredPermissions) {
|
|
620
|
+
const policy = resolveSinglePolicy(perm, effectiveMode, globalOverrides);
|
|
621
|
+
if (policyPriority(policy) > policyPriority(mostRestrictive)) {
|
|
622
|
+
mostRestrictive = policy;
|
|
623
|
+
}
|
|
624
|
+
if (policy === "disabled") return "disabled";
|
|
625
|
+
}
|
|
626
|
+
return mostRestrictive;
|
|
627
|
+
}
|
|
628
|
+
function resolveRequiredPermissions(skill, args) {
|
|
629
|
+
if (skill.capabilityMap) {
|
|
630
|
+
const matched = /* @__PURE__ */ new Set();
|
|
631
|
+
const actionKeys = ["action", "mode", "type", "operation"];
|
|
632
|
+
for (const key of actionKeys) {
|
|
633
|
+
const value = args[key];
|
|
634
|
+
if (value && skill.capabilityMap[value]) {
|
|
635
|
+
for (const perm of skill.capabilityMap[value]) {
|
|
636
|
+
matched.add(perm);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
if (matched.size === 0) {
|
|
641
|
+
for (const perms of Object.values(skill.capabilityMap)) {
|
|
642
|
+
for (const perm of perms) {
|
|
643
|
+
matched.add(perm);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
if (matched.size > 0) return Array.from(matched);
|
|
648
|
+
}
|
|
649
|
+
if (skill.permissions && skill.permissions.length > 0) {
|
|
650
|
+
return skill.permissions;
|
|
651
|
+
}
|
|
652
|
+
return [];
|
|
653
|
+
}
|
|
654
|
+
function resolveSinglePolicy(permission, mode, overrides) {
|
|
655
|
+
if (overrides && overrides[permission] !== void 0) {
|
|
656
|
+
return overrides[permission];
|
|
657
|
+
}
|
|
658
|
+
const modeTable = PERMISSION_MODE_DEFAULTS[mode];
|
|
659
|
+
if (modeTable[permission] !== void 0) {
|
|
660
|
+
return modeTable[permission];
|
|
661
|
+
}
|
|
662
|
+
const parts = permission.split(".");
|
|
663
|
+
for (let i = parts.length - 1; i > 0; i--) {
|
|
664
|
+
const parent = parts.slice(0, i).join(".");
|
|
665
|
+
if (overrides && overrides[parent] !== void 0) {
|
|
666
|
+
return overrides[parent];
|
|
667
|
+
}
|
|
668
|
+
if (modeTable[parent] !== void 0) {
|
|
669
|
+
return modeTable[parent];
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
return mode === "trusted" ? "auto" : "approval";
|
|
673
|
+
}
|
|
674
|
+
function policyPriority(policy) {
|
|
675
|
+
switch (policy) {
|
|
676
|
+
case "auto":
|
|
677
|
+
return 0;
|
|
678
|
+
case "approval":
|
|
679
|
+
return 1;
|
|
680
|
+
case "force-approval":
|
|
681
|
+
return 2;
|
|
682
|
+
case "disabled":
|
|
683
|
+
return 3;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/skill/mcp-router.ts
|
|
688
|
+
var McpRouter = class {
|
|
689
|
+
constructor() {
|
|
690
|
+
this.connections = /* @__PURE__ */ new Map();
|
|
691
|
+
}
|
|
692
|
+
/**
|
|
693
|
+
* Register an MCP Server connection.
|
|
694
|
+
*/
|
|
695
|
+
connect(connection) {
|
|
696
|
+
this.connections.set(connection.name, connection);
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Disconnect and remove an MCP Server.
|
|
700
|
+
*/
|
|
701
|
+
async disconnect(name) {
|
|
702
|
+
const conn = this.connections.get(name);
|
|
703
|
+
if (conn) {
|
|
704
|
+
await conn.disconnect();
|
|
705
|
+
this.connections.delete(name);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Disconnect all MCP Servers.
|
|
710
|
+
*/
|
|
711
|
+
async disconnectAll() {
|
|
712
|
+
for (const [name] of this.connections) {
|
|
713
|
+
await this.disconnect(name);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* List all connected MCP Servers and their tools.
|
|
718
|
+
*/
|
|
719
|
+
listConnections() {
|
|
720
|
+
return Array.from(this.connections.values()).map((conn) => ({
|
|
721
|
+
name: conn.name,
|
|
722
|
+
transport: conn.transport,
|
|
723
|
+
tools: conn.toolDefs.map((t) => t.name)
|
|
724
|
+
}));
|
|
725
|
+
}
|
|
726
|
+
/**
|
|
727
|
+
* Check if a tool name has the `mcp:` prefix.
|
|
728
|
+
*/
|
|
729
|
+
isMcpTool(toolName) {
|
|
730
|
+
return toolName.startsWith("mcp:");
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* Parse an `mcp:` prefixed tool name into server name and tool name.
|
|
734
|
+
* "mcp:github/list_prs" → { server: "github", tool: "list_prs" }
|
|
735
|
+
*/
|
|
736
|
+
parseMcpToolName(prefixedName) {
|
|
737
|
+
const withoutPrefix = prefixedName.slice(4);
|
|
738
|
+
const slashIndex = withoutPrefix.indexOf("/");
|
|
739
|
+
if (slashIndex === -1) {
|
|
740
|
+
throw new Error(`Invalid MCP tool name: "${prefixedName}". Expected format: "mcp:serverName/toolName"`);
|
|
741
|
+
}
|
|
742
|
+
return {
|
|
743
|
+
server: withoutPrefix.slice(0, slashIndex),
|
|
744
|
+
tool: withoutPrefix.slice(slashIndex + 1)
|
|
745
|
+
};
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Route a tool call to the appropriate MCP Server.
|
|
749
|
+
*/
|
|
750
|
+
async call(prefixedName, args) {
|
|
751
|
+
const { server, tool } = this.parseMcpToolName(prefixedName);
|
|
752
|
+
const conn = this.connections.get(server);
|
|
753
|
+
if (!conn) {
|
|
754
|
+
throw new Error(`MCP Server "${server}" not connected. Available: ${Array.from(this.connections.keys()).join(", ") || "none"}`);
|
|
755
|
+
}
|
|
756
|
+
return conn.call(tool, args);
|
|
757
|
+
}
|
|
758
|
+
/**
|
|
759
|
+
* Resolve `mcp:` prefixed tool names from a tools list to ToolDef[].
|
|
760
|
+
* Non-mcp names are silently skipped.
|
|
761
|
+
*/
|
|
762
|
+
resolveToolDefs(mcpToolNames) {
|
|
763
|
+
const result = [];
|
|
764
|
+
for (const name of mcpToolNames) {
|
|
765
|
+
if (!this.isMcpTool(name)) continue;
|
|
766
|
+
try {
|
|
767
|
+
const { server, tool } = this.parseMcpToolName(name);
|
|
768
|
+
const conn = this.connections.get(server);
|
|
769
|
+
if (conn) {
|
|
770
|
+
const toolDef = conn.toolDefs.find((t) => t.name === tool);
|
|
771
|
+
if (toolDef) {
|
|
772
|
+
result.push({ ...toolDef, name });
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
} catch {
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return result;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Check if a specific MCP server is connected.
|
|
782
|
+
*/
|
|
783
|
+
isConnected(serverName) {
|
|
784
|
+
return this.connections.has(serverName);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
|
|
788
|
+
// src/content/utils.ts
|
|
789
|
+
function contentToString(content) {
|
|
790
|
+
if (typeof content === "string") return content;
|
|
791
|
+
return content.filter((c) => c.type === "text").map((c) => c.text).join("\n");
|
|
792
|
+
}
|
|
793
|
+
function contentToPreview(content, maxLen = 100) {
|
|
794
|
+
const text = contentToString(content);
|
|
795
|
+
return text.length > maxLen ? text.slice(0, maxLen) + "..." : text;
|
|
796
|
+
}
|
|
797
|
+
function estimateContentTokens(blocks) {
|
|
798
|
+
const CHAR_TO_TOKEN_RATIO2 = 3.5;
|
|
799
|
+
let tokens = 0;
|
|
800
|
+
for (const block of blocks) {
|
|
801
|
+
switch (block.type) {
|
|
802
|
+
case "text":
|
|
803
|
+
tokens += Math.ceil(block.text.length / CHAR_TO_TOKEN_RATIO2);
|
|
804
|
+
break;
|
|
805
|
+
case "image":
|
|
806
|
+
tokens += 170;
|
|
807
|
+
break;
|
|
808
|
+
case "resource":
|
|
809
|
+
tokens += Math.ceil((block.resource.text ?? block.resource.uri).length / CHAR_TO_TOKEN_RATIO2);
|
|
810
|
+
break;
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
return tokens;
|
|
814
|
+
}
|
|
815
|
+
function fileInputsToContentBlocks(files) {
|
|
816
|
+
return files.map((f) => {
|
|
817
|
+
const isImage = f.mimeType.startsWith("image/");
|
|
818
|
+
if (isImage) {
|
|
819
|
+
return { type: "image", data: f.data, mimeType: f.mimeType };
|
|
820
|
+
}
|
|
821
|
+
return {
|
|
822
|
+
type: "resource",
|
|
823
|
+
resource: { uri: f.filename ?? `attachment:${f.mimeType}`, mimeType: f.mimeType, text: f.data }
|
|
824
|
+
};
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
// src/session/manager.ts
|
|
829
|
+
var SessionManager = class {
|
|
830
|
+
constructor() {
|
|
831
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
832
|
+
}
|
|
833
|
+
create(options) {
|
|
834
|
+
const id = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
835
|
+
const now = Date.now();
|
|
836
|
+
const session = {
|
|
837
|
+
id,
|
|
838
|
+
title: options?.title,
|
|
839
|
+
createdAt: now,
|
|
840
|
+
updatedAt: now,
|
|
841
|
+
meta: options?.meta,
|
|
842
|
+
messageCount: 0,
|
|
843
|
+
artifactCount: 0,
|
|
844
|
+
tokenCount: 0,
|
|
845
|
+
status: "active",
|
|
846
|
+
systemPrompt: options?.systemPrompt,
|
|
847
|
+
messages: []
|
|
848
|
+
};
|
|
849
|
+
this.sessions.set(id, session);
|
|
850
|
+
return session;
|
|
851
|
+
}
|
|
852
|
+
get(sessionId) {
|
|
853
|
+
return this.sessions.get(sessionId);
|
|
854
|
+
}
|
|
855
|
+
getOrThrow(sessionId) {
|
|
856
|
+
const session = this.sessions.get(sessionId);
|
|
857
|
+
if (!session) {
|
|
858
|
+
throw new ACPError(ACPErrorCodes.SESSION_NOT_FOUND, `Session not found: ${sessionId}`, {
|
|
859
|
+
sessionId
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
return session;
|
|
863
|
+
}
|
|
864
|
+
list(options) {
|
|
865
|
+
let result = Array.from(this.sessions.values());
|
|
866
|
+
if (options?.status) {
|
|
867
|
+
result = result.filter((s) => s.status === options.status);
|
|
868
|
+
}
|
|
869
|
+
result.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
870
|
+
const offset = options?.offset ?? 0;
|
|
871
|
+
const limit = options?.limit ?? 50;
|
|
872
|
+
return result.slice(offset, offset + limit);
|
|
873
|
+
}
|
|
874
|
+
search(query, options) {
|
|
875
|
+
const q = query.toLowerCase();
|
|
876
|
+
const results = [];
|
|
877
|
+
for (const session of this.sessions.values()) {
|
|
878
|
+
if (!options?.includeArchived && session.status === "archived") continue;
|
|
879
|
+
let score = 0;
|
|
880
|
+
if (session.title?.toLowerCase().includes(q)) score += 0.5;
|
|
881
|
+
if (session.summary?.toLowerCase().includes(q)) score += 0.3;
|
|
882
|
+
for (const msg of session.messages) {
|
|
883
|
+
if (contentToString(msg.content).toLowerCase().includes(q)) {
|
|
884
|
+
score += 0.1;
|
|
885
|
+
break;
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
if (score > 0) {
|
|
889
|
+
results.push({
|
|
890
|
+
sessionId: session.id,
|
|
891
|
+
title: session.title,
|
|
892
|
+
summary: session.summary,
|
|
893
|
+
relevanceScore: Math.min(score, 1),
|
|
894
|
+
messageCount: session.messageCount,
|
|
895
|
+
updatedAt: session.updatedAt
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
results.sort((a, b) => b.relevanceScore - a.relevanceScore);
|
|
900
|
+
return results.slice(0, options?.limit ?? 10);
|
|
901
|
+
}
|
|
902
|
+
addMessage(sessionId, message) {
|
|
903
|
+
const session = this.getOrThrow(sessionId);
|
|
904
|
+
session.messages.push(message);
|
|
905
|
+
session.messageCount = session.messages.length;
|
|
906
|
+
session.updatedAt = Date.now();
|
|
907
|
+
}
|
|
908
|
+
delete(sessionId) {
|
|
909
|
+
return this.sessions.delete(sessionId);
|
|
910
|
+
}
|
|
911
|
+
archive(sessionId) {
|
|
912
|
+
const session = this.getOrThrow(sessionId);
|
|
913
|
+
session.status = "archived";
|
|
914
|
+
session.updatedAt = Date.now();
|
|
915
|
+
}
|
|
916
|
+
merge(fromId, toId, strategy = "summary_and_artifacts") {
|
|
917
|
+
const from = this.getOrThrow(fromId);
|
|
918
|
+
const to = this.getOrThrow(toId);
|
|
919
|
+
if (strategy === "full") {
|
|
920
|
+
to.messages.push(...from.messages);
|
|
921
|
+
} else {
|
|
922
|
+
const summary = this.createSummary(from);
|
|
923
|
+
to.messages.push({
|
|
924
|
+
role: "user",
|
|
925
|
+
content: `[Context from session "${from.title || from.id}"]:
|
|
926
|
+
${summary}`
|
|
927
|
+
});
|
|
928
|
+
if (strategy === "summary_and_artifacts") {
|
|
929
|
+
const artifacts = from.messages.filter(
|
|
930
|
+
(m) => m.role === "assistant" && m.toolCalls?.length
|
|
931
|
+
);
|
|
932
|
+
if (artifacts.length > 0) {
|
|
933
|
+
to.messages.push({
|
|
934
|
+
role: "user",
|
|
935
|
+
content: `[Artifacts from session "${from.title || from.id}"]:
|
|
936
|
+
${artifacts.map((a) => contentToPreview(a.content, 200)).join("\n")}`
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
to.messageCount = to.messages.length;
|
|
942
|
+
to.updatedAt = Date.now();
|
|
943
|
+
}
|
|
944
|
+
createSummary(session) {
|
|
945
|
+
const userMsgs = session.messages.filter((m) => m.role === "user");
|
|
946
|
+
if (userMsgs.length === 0) return "Empty session";
|
|
947
|
+
return userMsgs.slice(-3).map((m) => contentToPreview(m.content, 200)).join("\n");
|
|
948
|
+
}
|
|
949
|
+
};
|
|
950
|
+
|
|
951
|
+
// src/context/model-context.ts
|
|
952
|
+
var MODEL_CAPABILITIES = {
|
|
953
|
+
"gpt-4o": { contextLength: 128e3, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
954
|
+
"gpt-4o-mini": { contextLength: 128e3, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
955
|
+
"gpt-4-turbo": { contextLength: 128e3, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
956
|
+
"gpt-4": { contextLength: 8192 },
|
|
957
|
+
"gpt-3.5-turbo": { contextLength: 16385 },
|
|
958
|
+
"o1": { contextLength: 2e5, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"] },
|
|
959
|
+
"o3-mini": { contextLength: 2e5, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"] },
|
|
960
|
+
"claude-sonnet-4-6": { contextLength: 2e5, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
961
|
+
"claude-opus-4-6": { contextLength: 2e5, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
962
|
+
"claude-haiku-4-5": { contextLength: 2e5, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"], maxImageSize: 20 * 1024 * 1024 },
|
|
963
|
+
"qwen-max": { contextLength: 32768 },
|
|
964
|
+
"qwen-plus": { contextLength: 131072 },
|
|
965
|
+
"qwen-turbo": { contextLength: 131072 },
|
|
966
|
+
"deepseek-chat": { contextLength: 65536 },
|
|
967
|
+
"deepseek-reasoner": { contextLength: 65536 },
|
|
968
|
+
"deepseek": { contextLength: 65536 },
|
|
969
|
+
"llama-3.1-70b": { contextLength: 131072 },
|
|
970
|
+
"llama-3.1-8b": { contextLength: 131072 },
|
|
971
|
+
"gemma-2-27b": { contextLength: 8192 },
|
|
972
|
+
"glm-4": { contextLength: 128e3, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"] },
|
|
973
|
+
"glm-4-flash": { contextLength: 128e3, supportsImages: true, supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"] },
|
|
974
|
+
"glm": { contextLength: 128e3 },
|
|
975
|
+
"moonshot-v1-8k": { contextLength: 8192 },
|
|
976
|
+
"moonshot-v1-32k": { contextLength: 32768 },
|
|
977
|
+
"moonshot-v1-auto": { contextLength: 131072 },
|
|
978
|
+
"moonshot": { contextLength: 32768 },
|
|
979
|
+
"kimi-k3": { contextLength: 131072 },
|
|
980
|
+
"kimi": { contextLength: 131072 }
|
|
981
|
+
};
|
|
982
|
+
var MODEL_CONTEXT_LENGTHS = {
|
|
983
|
+
"gpt-4o": 128e3,
|
|
984
|
+
"gpt-4o-mini": 128e3,
|
|
985
|
+
"gpt-4-turbo": 128e3,
|
|
986
|
+
"gpt-4": 8192,
|
|
987
|
+
"gpt-3.5-turbo": 16385,
|
|
988
|
+
"o1": 2e5,
|
|
989
|
+
"o3-mini": 2e5,
|
|
990
|
+
"claude-sonnet-4-6": 2e5,
|
|
991
|
+
"claude-opus-4-6": 2e5,
|
|
992
|
+
"claude-haiku-4-5": 2e5,
|
|
993
|
+
"qwen-max": 32768,
|
|
994
|
+
"qwen-plus": 131072,
|
|
995
|
+
"qwen-turbo": 131072,
|
|
996
|
+
"deepseek-chat": 65536,
|
|
997
|
+
"deepseek-reasoner": 65536,
|
|
998
|
+
"deepseek": 65536,
|
|
999
|
+
"llama-3.1-70b": 131072,
|
|
1000
|
+
"llama-3.1-8b": 131072,
|
|
1001
|
+
"gemma-2-27b": 8192,
|
|
1002
|
+
"glm-4": 128e3,
|
|
1003
|
+
"glm-4-flash": 128e3,
|
|
1004
|
+
"glm": 128e3,
|
|
1005
|
+
"moonshot-v1-8k": 8192,
|
|
1006
|
+
"moonshot-v1-32k": 32768,
|
|
1007
|
+
"moonshot-v1-auto": 131072,
|
|
1008
|
+
"moonshot": 32768,
|
|
1009
|
+
"kimi-k3": 131072,
|
|
1010
|
+
"kimi": 131072
|
|
1011
|
+
};
|
|
1012
|
+
function resolveModelContextLength(model, override) {
|
|
1013
|
+
if (override) return override;
|
|
1014
|
+
const lower = model.toLowerCase();
|
|
1015
|
+
if (MODEL_CONTEXT_LENGTHS[lower]) return MODEL_CONTEXT_LENGTHS[lower];
|
|
1016
|
+
const matched = [];
|
|
1017
|
+
for (const key of Object.keys(MODEL_CONTEXT_LENGTHS)) {
|
|
1018
|
+
if (lower.startsWith(key)) matched.push(key);
|
|
1019
|
+
}
|
|
1020
|
+
if (matched.length > 0) {
|
|
1021
|
+
matched.sort((a, b) => b.length - a.length);
|
|
1022
|
+
return MODEL_CONTEXT_LENGTHS[matched[0]];
|
|
1023
|
+
}
|
|
1024
|
+
console.warn(`[listdoing] Unknown model "${model}", using default contextLength=128000. Set config.context.contextLength to override.`);
|
|
1025
|
+
return 128e3;
|
|
1026
|
+
}
|
|
1027
|
+
function resolveModelCapabilities(model) {
|
|
1028
|
+
const lower = model.toLowerCase();
|
|
1029
|
+
if (MODEL_CAPABILITIES[lower]) return MODEL_CAPABILITIES[lower];
|
|
1030
|
+
const matched = [];
|
|
1031
|
+
for (const key of Object.keys(MODEL_CAPABILITIES)) {
|
|
1032
|
+
if (lower.startsWith(key)) matched.push(key);
|
|
1033
|
+
}
|
|
1034
|
+
if (matched.length > 0) {
|
|
1035
|
+
matched.sort((a, b) => b.length - a.length);
|
|
1036
|
+
return MODEL_CAPABILITIES[matched[0]];
|
|
1037
|
+
}
|
|
1038
|
+
return { contextLength: 4096 };
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// src/context/token-estimator.ts
|
|
1042
|
+
var CHAR_TO_TOKEN_RATIO = 3.5;
|
|
1043
|
+
var MESSAGE_OVERHEAD = 4;
|
|
1044
|
+
var TOOL_DEF_OVERHEAD = 10;
|
|
1045
|
+
function estimateTextTokens(text) {
|
|
1046
|
+
return Math.ceil(text.length / CHAR_TO_TOKEN_RATIO);
|
|
1047
|
+
}
|
|
1048
|
+
function estimateMessageTokens(msg) {
|
|
1049
|
+
let tokens = MESSAGE_OVERHEAD;
|
|
1050
|
+
if (typeof msg.content === "string") {
|
|
1051
|
+
tokens += estimateTextTokens(msg.content);
|
|
1052
|
+
} else {
|
|
1053
|
+
tokens += estimateContentTokens(msg.content);
|
|
1054
|
+
}
|
|
1055
|
+
if (msg.toolCalls) {
|
|
1056
|
+
tokens += estimateTextTokens(JSON.stringify(msg.toolCalls));
|
|
1057
|
+
}
|
|
1058
|
+
return tokens;
|
|
1059
|
+
}
|
|
1060
|
+
function estimateToolDefTokens(tool) {
|
|
1061
|
+
return TOOL_DEF_OVERHEAD + estimateTextTokens(tool.name) + estimateTextTokens(tool.description) + estimateTextTokens(JSON.stringify(tool.inputSchema));
|
|
1062
|
+
}
|
|
1063
|
+
function estimateRequestTokens(messages, tools, systemPrompt) {
|
|
1064
|
+
let total = 0;
|
|
1065
|
+
if (systemPrompt) total += estimateTextTokens(systemPrompt) + MESSAGE_OVERHEAD;
|
|
1066
|
+
for (const msg of messages) total += estimateMessageTokens(msg);
|
|
1067
|
+
for (const tool of tools) total += estimateToolDefTokens(tool);
|
|
1068
|
+
return total;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// src/context/manager.ts
|
|
1072
|
+
var ContextManager = class {
|
|
1073
|
+
constructor(config, model) {
|
|
1074
|
+
this.config = {
|
|
1075
|
+
historyStrategy: { type: "hybrid" },
|
|
1076
|
+
syncToServer: false,
|
|
1077
|
+
autoCompress: true,
|
|
1078
|
+
compressThreshold: 0.85,
|
|
1079
|
+
outputReserve: 1024,
|
|
1080
|
+
...config
|
|
1081
|
+
};
|
|
1082
|
+
this.model = model ?? "";
|
|
1083
|
+
}
|
|
1084
|
+
/** Update model (called when LLM config changes) */
|
|
1085
|
+
setModel(model) {
|
|
1086
|
+
this.model = model;
|
|
1087
|
+
}
|
|
1088
|
+
/** Compute the token budget for the current model & config */
|
|
1089
|
+
getBudget() {
|
|
1090
|
+
const ctxLen = resolveModelContextLength(this.model, this.config.contextLength);
|
|
1091
|
+
const reserve = this.config.outputReserve ?? 1024;
|
|
1092
|
+
return ctxLen - reserve;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Build the context window for a session — the actual messages sent to the LLM.
|
|
1096
|
+
* Now accepts tools to account for tool-definition token cost, and returns
|
|
1097
|
+
* token usage statistics so callers can decide whether to compress.
|
|
1098
|
+
*/
|
|
1099
|
+
buildWindow(messages, systemPrompt, tools, maxTokens) {
|
|
1100
|
+
const budget = maxTokens ?? this.config.maxTokens ?? this.getBudget();
|
|
1101
|
+
let fixedTokens = 0;
|
|
1102
|
+
if (systemPrompt) {
|
|
1103
|
+
fixedTokens += estimateTextTokens(systemPrompt) + 4;
|
|
1104
|
+
}
|
|
1105
|
+
const toolDefs = tools ?? [];
|
|
1106
|
+
for (const tool of toolDefs) {
|
|
1107
|
+
fixedTokens += estimateToolDefTokens(tool);
|
|
1108
|
+
}
|
|
1109
|
+
const remainingBudget = budget - fixedTokens;
|
|
1110
|
+
if (remainingBudget <= 0) {
|
|
1111
|
+
const result2 = [];
|
|
1112
|
+
if (systemPrompt) result2.push({ role: "system", content: systemPrompt });
|
|
1113
|
+
return { messages: result2, usedTokens: fixedTokens, budget };
|
|
1114
|
+
}
|
|
1115
|
+
const result = [];
|
|
1116
|
+
if (systemPrompt) {
|
|
1117
|
+
result.push({ role: "system", content: systemPrompt });
|
|
1118
|
+
}
|
|
1119
|
+
const reversed = [...messages].reverse();
|
|
1120
|
+
const selected = [];
|
|
1121
|
+
let usedByMessages = 0;
|
|
1122
|
+
for (const msg of reversed) {
|
|
1123
|
+
const msgTokens = estimateMessageTokens(msg);
|
|
1124
|
+
if (usedByMessages + msgTokens > remainingBudget) break;
|
|
1125
|
+
selected.unshift(msg);
|
|
1126
|
+
usedByMessages += msgTokens;
|
|
1127
|
+
}
|
|
1128
|
+
result.push(...selected);
|
|
1129
|
+
if (selected.length === 0 && messages.length > 0) {
|
|
1130
|
+
const lastUser = [...messages].reverse().find((m) => m.role === "user");
|
|
1131
|
+
if (lastUser) {
|
|
1132
|
+
result.push(lastUser);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
return { messages: result, usedTokens: fixedTokens + usedByMessages, budget };
|
|
1136
|
+
}
|
|
1137
|
+
/**
|
|
1138
|
+
* Ensure context fits within budget. Triggers auto-compression when
|
|
1139
|
+
* usage exceeds the configured threshold.
|
|
1140
|
+
*/
|
|
1141
|
+
ensureContextFits(messages, systemPrompt, tools, model) {
|
|
1142
|
+
if (model) this.setModel(model);
|
|
1143
|
+
const { usedTokens, budget } = this.buildWindow(messages, systemPrompt, tools);
|
|
1144
|
+
const threshold = this.config.compressThreshold ?? 0.85;
|
|
1145
|
+
if (usedTokens / budget <= threshold) {
|
|
1146
|
+
return { messages, wasCompressed: false };
|
|
1147
|
+
}
|
|
1148
|
+
const compressed = this.compress(messages, "hybrid");
|
|
1149
|
+
const afterCheck = this.buildWindow(compressed.messages, systemPrompt, tools);
|
|
1150
|
+
if (afterCheck.usedTokens / afterCheck.budget > 1) {
|
|
1151
|
+
console.warn(`[listdoing] Context still exceeds budget after compression (${afterCheck.usedTokens}/${afterCheck.budget} tokens). Truncating to recent messages only.`);
|
|
1152
|
+
const truncated = messages.slice(-3);
|
|
1153
|
+
return { messages: truncated, wasCompressed: true };
|
|
1154
|
+
}
|
|
1155
|
+
return { messages: compressed.messages, wasCompressed: true };
|
|
1156
|
+
}
|
|
1157
|
+
/**
|
|
1158
|
+
* Compress context by summarizing older messages.
|
|
1159
|
+
*/
|
|
1160
|
+
compress(messages, strategy) {
|
|
1161
|
+
const estimateTokens = (msgs) => msgs.reduce((sum, m) => sum + estimateMessageTokens(m), 0);
|
|
1162
|
+
const beforeTokens = estimateTokens(messages);
|
|
1163
|
+
const strat = strategy ?? this.config.historyStrategy?.type ?? "hybrid";
|
|
1164
|
+
let compressed;
|
|
1165
|
+
switch (strat) {
|
|
1166
|
+
case "sliding_window": {
|
|
1167
|
+
compressed = messages.slice(-10);
|
|
1168
|
+
break;
|
|
1169
|
+
}
|
|
1170
|
+
case "summary": {
|
|
1171
|
+
if (messages.length <= 4) {
|
|
1172
|
+
compressed = messages;
|
|
1173
|
+
} else {
|
|
1174
|
+
const old = messages.slice(0, -4);
|
|
1175
|
+
const recent = messages.slice(-4);
|
|
1176
|
+
const summaryText = old.filter((m) => m.role === "user" || m.role === "assistant").map((m) => `${m.role}: ${contentToPreview(m.content, 100)}`).join("\n");
|
|
1177
|
+
compressed = [
|
|
1178
|
+
{ role: "user", content: `[Previous context summary]:
|
|
1179
|
+
${summaryText}` },
|
|
1180
|
+
...recent
|
|
1181
|
+
];
|
|
1182
|
+
}
|
|
1183
|
+
break;
|
|
1184
|
+
}
|
|
1185
|
+
case "token_budget":
|
|
1186
|
+
case "hybrid":
|
|
1187
|
+
default: {
|
|
1188
|
+
const maxTokens = this.config.maxTokens ?? this.getBudget();
|
|
1189
|
+
let totalTokens = 0;
|
|
1190
|
+
const kept = [];
|
|
1191
|
+
for (const msg of [...messages].reverse()) {
|
|
1192
|
+
const t = estimateMessageTokens(msg);
|
|
1193
|
+
if (totalTokens + t > maxTokens) break;
|
|
1194
|
+
kept.unshift(msg);
|
|
1195
|
+
totalTokens += t;
|
|
1196
|
+
}
|
|
1197
|
+
if (kept.length < messages.length) {
|
|
1198
|
+
const dropped = messages.slice(0, messages.length - kept.length);
|
|
1199
|
+
const summaryText = dropped.filter((m) => m.role === "user" || m.role === "assistant").slice(-5).map((m) => `${m.role}: ${contentToPreview(m.content, 80)}`).join("\n");
|
|
1200
|
+
compressed = [
|
|
1201
|
+
{ role: "user", content: `[Earlier context]:
|
|
1202
|
+
${summaryText}` },
|
|
1203
|
+
...kept
|
|
1204
|
+
];
|
|
1205
|
+
} else {
|
|
1206
|
+
compressed = kept;
|
|
1207
|
+
}
|
|
1208
|
+
break;
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
const afterTokens = estimateTokens(compressed);
|
|
1212
|
+
return { messages: compressed, beforeTokens, afterTokens };
|
|
1213
|
+
}
|
|
1214
|
+
/**
|
|
1215
|
+
* Search across messages for relevant content.
|
|
1216
|
+
*/
|
|
1217
|
+
search(allSessionMessages, query, options) {
|
|
1218
|
+
const q = query.toLowerCase();
|
|
1219
|
+
const results = [];
|
|
1220
|
+
for (const [sessionId, messages] of allSessionMessages) {
|
|
1221
|
+
for (const msg of messages) {
|
|
1222
|
+
if (contentToString(msg.content).toLowerCase().includes(q)) {
|
|
1223
|
+
results.push({
|
|
1224
|
+
sessionId,
|
|
1225
|
+
relevanceScore: 0.5,
|
|
1226
|
+
content: contentToPreview(msg.content, 200),
|
|
1227
|
+
source: msg.role
|
|
1228
|
+
});
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
return results.slice(0, options?.limit ?? 5);
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
// src/task/planner.ts
|
|
1237
|
+
var TaskPlanner = class {
|
|
1238
|
+
constructor(llmAdapter) {
|
|
1239
|
+
this.llmAdapter = llmAdapter;
|
|
1240
|
+
}
|
|
1241
|
+
async plan(goal, availableTools) {
|
|
1242
|
+
const prompt = this.buildPlanningPrompt(goal, availableTools);
|
|
1243
|
+
const response = await this.llmAdapter.chat(
|
|
1244
|
+
[{ role: "user", content: prompt }],
|
|
1245
|
+
[]
|
|
1246
|
+
// No tools for the planning call itself
|
|
1247
|
+
);
|
|
1248
|
+
return this.parsePlan(goal, response.content);
|
|
1249
|
+
}
|
|
1250
|
+
buildPlanningPrompt(goal, tools) {
|
|
1251
|
+
const toolList = tools.map((t) => `- ${t.name}: ${t.description}`).join("\n");
|
|
1252
|
+
return [
|
|
1253
|
+
"You are a task planner. Break down the following goal into clear, sequential steps.",
|
|
1254
|
+
"",
|
|
1255
|
+
`Goal: ${goal}`,
|
|
1256
|
+
"",
|
|
1257
|
+
"Available tools:",
|
|
1258
|
+
toolList,
|
|
1259
|
+
"",
|
|
1260
|
+
"Output your plan as a JSON array of steps, each with:",
|
|
1261
|
+
'- "goal": what this step accomplishes (string)',
|
|
1262
|
+
'- "tools": suggested tool names for this step (string[], can be empty)',
|
|
1263
|
+
"",
|
|
1264
|
+
"Requirements:",
|
|
1265
|
+
"- Each step should be independently executable",
|
|
1266
|
+
"- Steps should be ordered by dependency",
|
|
1267
|
+
"- Keep steps focused \u2014 one logical action per step",
|
|
1268
|
+
"- Output ONLY the JSON array, no other text",
|
|
1269
|
+
"",
|
|
1270
|
+
"Example:",
|
|
1271
|
+
'[{"goal":"Search for product on Taobao","tools":["web_search"]},{"goal":"Compare prices across platforms","tools":["code_eval"]}]',
|
|
1272
|
+
"",
|
|
1273
|
+
"Your plan:"
|
|
1274
|
+
].join("\n");
|
|
1275
|
+
}
|
|
1276
|
+
parsePlan(goal, content) {
|
|
1277
|
+
const steps = this.extractSteps(content);
|
|
1278
|
+
const now = Date.now();
|
|
1279
|
+
return {
|
|
1280
|
+
id: `plan-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1281
|
+
goal,
|
|
1282
|
+
steps,
|
|
1283
|
+
status: "planning",
|
|
1284
|
+
createdAt: now,
|
|
1285
|
+
updatedAt: now,
|
|
1286
|
+
totalTokenUsage: { input: 0, output: 0 }
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
extractSteps(content) {
|
|
1290
|
+
const jsonStr = this.extractJSON(content);
|
|
1291
|
+
if (!jsonStr) {
|
|
1292
|
+
return [this.makeStep(0, goalFallback(content))];
|
|
1293
|
+
}
|
|
1294
|
+
try {
|
|
1295
|
+
const parsed = JSON.parse(jsonStr);
|
|
1296
|
+
if (!Array.isArray(parsed)) {
|
|
1297
|
+
return [this.makeStep(0, goalFallback(content))];
|
|
1298
|
+
}
|
|
1299
|
+
return parsed.map(
|
|
1300
|
+
(item, index) => this.makeStep(index, {
|
|
1301
|
+
goal: typeof item.goal === "string" ? item.goal : `Step ${index + 1}`,
|
|
1302
|
+
tools: Array.isArray(item.tools) ? item.tools.filter((t) => typeof t === "string") : void 0
|
|
1303
|
+
})
|
|
1304
|
+
);
|
|
1305
|
+
} catch {
|
|
1306
|
+
return [this.makeStep(0, goalFallback(content))];
|
|
1307
|
+
}
|
|
1308
|
+
}
|
|
1309
|
+
extractJSON(content) {
|
|
1310
|
+
const start = content.indexOf("[");
|
|
1311
|
+
const end = content.lastIndexOf("]");
|
|
1312
|
+
if (start !== -1 && end > start) {
|
|
1313
|
+
return content.slice(start, end + 1);
|
|
1314
|
+
}
|
|
1315
|
+
const objStart = content.indexOf("{");
|
|
1316
|
+
const objEnd = content.lastIndexOf("}");
|
|
1317
|
+
if (objStart !== -1 && objEnd > objStart) {
|
|
1318
|
+
return `[${content.slice(objStart, objEnd + 1)}]`;
|
|
1319
|
+
}
|
|
1320
|
+
return null;
|
|
1321
|
+
}
|
|
1322
|
+
makeStep(index, def) {
|
|
1323
|
+
return {
|
|
1324
|
+
id: `step-${index + 1}`,
|
|
1325
|
+
index,
|
|
1326
|
+
goal: def.goal,
|
|
1327
|
+
tools: def.tools,
|
|
1328
|
+
status: "pending",
|
|
1329
|
+
retryCount: 0
|
|
1330
|
+
};
|
|
1331
|
+
}
|
|
1332
|
+
};
|
|
1333
|
+
function goalFallback(content) {
|
|
1334
|
+
const cleaned = content.replace(/```[\s\S]*?```/g, "").trim();
|
|
1335
|
+
return { goal: cleaned.slice(0, 500) || "Execute the task" };
|
|
1336
|
+
}
|
|
1337
|
+
|
|
1338
|
+
// src/task/tracker.ts
|
|
1339
|
+
var PlanTracker = class {
|
|
1340
|
+
constructor(plan, sessionId, emit) {
|
|
1341
|
+
this.plan = plan;
|
|
1342
|
+
this.sessionId = sessionId;
|
|
1343
|
+
this.emit = emit;
|
|
1344
|
+
}
|
|
1345
|
+
/** Mark the plan as executing */
|
|
1346
|
+
startExecuting() {
|
|
1347
|
+
this.plan.status = "executing";
|
|
1348
|
+
this.plan.updatedAt = Date.now();
|
|
1349
|
+
}
|
|
1350
|
+
/** Mark a step as running */
|
|
1351
|
+
startStep(index) {
|
|
1352
|
+
if (index < 0 || index >= this.plan.steps.length) return;
|
|
1353
|
+
this.plan.steps[index].status = "running";
|
|
1354
|
+
this.plan.updatedAt = Date.now();
|
|
1355
|
+
this.emit("task:step_start", {
|
|
1356
|
+
sessionId: this.sessionId,
|
|
1357
|
+
step: this.plan.steps[index],
|
|
1358
|
+
progress: this.getProgress()
|
|
1359
|
+
});
|
|
1360
|
+
}
|
|
1361
|
+
/** Mark a step as done with its result */
|
|
1362
|
+
completeStep(index, result) {
|
|
1363
|
+
if (index < 0 || index >= this.plan.steps.length) return;
|
|
1364
|
+
const step = this.plan.steps[index];
|
|
1365
|
+
step.status = "done";
|
|
1366
|
+
step.result = result;
|
|
1367
|
+
this.plan.totalTokenUsage.input += result.tokenUsage.input;
|
|
1368
|
+
this.plan.totalTokenUsage.output += result.tokenUsage.output;
|
|
1369
|
+
this.plan.updatedAt = Date.now();
|
|
1370
|
+
this.emit("task:step_complete", {
|
|
1371
|
+
sessionId: this.sessionId,
|
|
1372
|
+
step,
|
|
1373
|
+
progress: this.getProgress()
|
|
1374
|
+
});
|
|
1375
|
+
}
|
|
1376
|
+
/** Mark a step as failed */
|
|
1377
|
+
failStep(index, result) {
|
|
1378
|
+
if (index < 0 || index >= this.plan.steps.length) return;
|
|
1379
|
+
const step = this.plan.steps[index];
|
|
1380
|
+
step.status = "failed";
|
|
1381
|
+
step.result = result;
|
|
1382
|
+
this.plan.totalTokenUsage.input += result.tokenUsage.input;
|
|
1383
|
+
this.plan.totalTokenUsage.output += result.tokenUsage.output;
|
|
1384
|
+
this.plan.updatedAt = Date.now();
|
|
1385
|
+
this.emit("task:step_failed", {
|
|
1386
|
+
sessionId: this.sessionId,
|
|
1387
|
+
step,
|
|
1388
|
+
progress: this.getProgress()
|
|
1389
|
+
});
|
|
1390
|
+
}
|
|
1391
|
+
/** Mark a step as skipped */
|
|
1392
|
+
skipStep(index) {
|
|
1393
|
+
if (index < 0 || index >= this.plan.steps.length) return;
|
|
1394
|
+
this.plan.steps[index].status = "skipped";
|
|
1395
|
+
this.plan.updatedAt = Date.now();
|
|
1396
|
+
}
|
|
1397
|
+
/** Set plan status */
|
|
1398
|
+
setPlanStatus(status) {
|
|
1399
|
+
this.plan.status = status;
|
|
1400
|
+
this.plan.updatedAt = Date.now();
|
|
1401
|
+
}
|
|
1402
|
+
/** Get current progress */
|
|
1403
|
+
getProgress() {
|
|
1404
|
+
const total = this.plan.steps.length;
|
|
1405
|
+
const done = this.plan.steps.filter(
|
|
1406
|
+
(s) => s.status === "done" || s.status === "skipped"
|
|
1407
|
+
).length;
|
|
1408
|
+
return {
|
|
1409
|
+
current: done,
|
|
1410
|
+
total,
|
|
1411
|
+
percentage: total > 0 ? Math.round(done / total * 100) : 0
|
|
1412
|
+
};
|
|
1413
|
+
}
|
|
1414
|
+
/** Get the plan */
|
|
1415
|
+
getPlan() {
|
|
1416
|
+
return this.plan;
|
|
1417
|
+
}
|
|
1418
|
+
/** Find the index of the first step matching a status */
|
|
1419
|
+
findStepIndex(status) {
|
|
1420
|
+
return this.plan.steps.findIndex((s) => s.status === status);
|
|
1421
|
+
}
|
|
1422
|
+
// ---- Persistence ----
|
|
1423
|
+
/** Persist plan to session.meta */
|
|
1424
|
+
persistPlan(session) {
|
|
1425
|
+
session.meta = session.meta ?? {};
|
|
1426
|
+
session.meta.taskPlan = this.plan;
|
|
1427
|
+
}
|
|
1428
|
+
/** Save checkpoint (current execution position) */
|
|
1429
|
+
saveCheckpoint(session, currentStepIndex) {
|
|
1430
|
+
const checkpoint = {
|
|
1431
|
+
planId: this.plan.id,
|
|
1432
|
+
currentStepIndex,
|
|
1433
|
+
sessionId: session.id,
|
|
1434
|
+
timestamp: Date.now()
|
|
1435
|
+
};
|
|
1436
|
+
session.meta = session.meta ?? {};
|
|
1437
|
+
session.meta.taskCheckpoint = checkpoint;
|
|
1438
|
+
return checkpoint;
|
|
1439
|
+
}
|
|
1440
|
+
/** Load plan from session.meta */
|
|
1441
|
+
static loadPlan(session) {
|
|
1442
|
+
return session.meta?.taskPlan ?? null;
|
|
1443
|
+
}
|
|
1444
|
+
/** Load checkpoint from session.meta */
|
|
1445
|
+
static loadCheckpoint(session) {
|
|
1446
|
+
return session.meta?.taskCheckpoint ?? null;
|
|
1447
|
+
}
|
|
1448
|
+
/** Clear checkpoint from session.meta */
|
|
1449
|
+
static clearCheckpoint(session) {
|
|
1450
|
+
if (session.meta) {
|
|
1451
|
+
delete session.meta.taskCheckpoint;
|
|
1452
|
+
}
|
|
1453
|
+
}
|
|
1454
|
+
};
|
|
1455
|
+
|
|
1456
|
+
// src/task/graph.ts
|
|
1457
|
+
var TaskGraph = class {
|
|
1458
|
+
constructor(nodes) {
|
|
1459
|
+
this.levels = [];
|
|
1460
|
+
this.nodes = new Map(nodes.map((n) => [n.id, n]));
|
|
1461
|
+
}
|
|
1462
|
+
/** Validate: no cycles, all dependency references valid */
|
|
1463
|
+
validate() {
|
|
1464
|
+
const errors = [];
|
|
1465
|
+
const nodeIds = new Set(this.nodes.keys());
|
|
1466
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1467
|
+
for (const id of this.nodes.keys()) {
|
|
1468
|
+
if (seen.has(id)) {
|
|
1469
|
+
errors.push(`Duplicate node ID: ${id}`);
|
|
1470
|
+
}
|
|
1471
|
+
seen.add(id);
|
|
1472
|
+
}
|
|
1473
|
+
for (const [id, node] of this.nodes) {
|
|
1474
|
+
for (const dep of node.dependsOn) {
|
|
1475
|
+
if (!nodeIds.has(dep)) {
|
|
1476
|
+
errors.push(`Node "${id}" depends on non-existent node "${dep}"`);
|
|
1477
|
+
}
|
|
1478
|
+
if (dep === id) {
|
|
1479
|
+
errors.push(`Node "${id}" has self-dependency`);
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
}
|
|
1483
|
+
const levelResult = this.computeLevelsUnsafe();
|
|
1484
|
+
if (levelResult.hasCycle) {
|
|
1485
|
+
errors.push(`Cycle detected: nodes ${levelResult.remainingNodes.join(", ")} form a cycle`);
|
|
1486
|
+
}
|
|
1487
|
+
return { valid: errors.length === 0, errors };
|
|
1488
|
+
}
|
|
1489
|
+
/** Kahn's algorithm topological sort → level list (same level = parallelizable) */
|
|
1490
|
+
computeLevels() {
|
|
1491
|
+
const result = this.computeLevelsUnsafe();
|
|
1492
|
+
this.levels = result.levels;
|
|
1493
|
+
return this.levels;
|
|
1494
|
+
}
|
|
1495
|
+
computeLevelsUnsafe() {
|
|
1496
|
+
const inDegree = /* @__PURE__ */ new Map();
|
|
1497
|
+
const adjacency = /* @__PURE__ */ new Map();
|
|
1498
|
+
for (const id of this.nodes.keys()) {
|
|
1499
|
+
inDegree.set(id, 0);
|
|
1500
|
+
adjacency.set(id, /* @__PURE__ */ new Set());
|
|
1501
|
+
}
|
|
1502
|
+
for (const [id, node] of this.nodes) {
|
|
1503
|
+
inDegree.set(id, node.dependsOn.length);
|
|
1504
|
+
for (const dep of node.dependsOn) {
|
|
1505
|
+
if (adjacency.has(dep)) {
|
|
1506
|
+
adjacency.get(dep).add(id);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
const levels = [];
|
|
1511
|
+
let currentLevel = [];
|
|
1512
|
+
for (const [id, degree] of inDegree) {
|
|
1513
|
+
if (degree === 0) {
|
|
1514
|
+
currentLevel.push(id);
|
|
1515
|
+
}
|
|
1516
|
+
}
|
|
1517
|
+
while (currentLevel.length > 0) {
|
|
1518
|
+
levels.push(currentLevel);
|
|
1519
|
+
const nextLevel = [];
|
|
1520
|
+
for (const id of currentLevel) {
|
|
1521
|
+
const dependents = adjacency.get(id) ?? /* @__PURE__ */ new Set();
|
|
1522
|
+
for (const depId of dependents) {
|
|
1523
|
+
const newDegree = (inDegree.get(depId) ?? 0) - 1;
|
|
1524
|
+
inDegree.set(depId, newDegree);
|
|
1525
|
+
if (newDegree === 0) {
|
|
1526
|
+
nextLevel.push(depId);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
currentLevel = nextLevel;
|
|
1531
|
+
}
|
|
1532
|
+
const assignedNodes = new Set(levels.flat());
|
|
1533
|
+
const remainingNodes = [];
|
|
1534
|
+
for (const id of this.nodes.keys()) {
|
|
1535
|
+
if (!assignedNodes.has(id)) {
|
|
1536
|
+
remainingNodes.push(id);
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
return {
|
|
1540
|
+
levels,
|
|
1541
|
+
hasCycle: remainingNodes.length > 0,
|
|
1542
|
+
remainingNodes
|
|
1543
|
+
};
|
|
1544
|
+
}
|
|
1545
|
+
getLevel(level) {
|
|
1546
|
+
if (level < 0 || level >= this.levels.length) return [];
|
|
1547
|
+
return this.levels[level].map((id) => this.nodes.get(id)).filter(Boolean);
|
|
1548
|
+
}
|
|
1549
|
+
getLevelCount() {
|
|
1550
|
+
return this.levels.length;
|
|
1551
|
+
}
|
|
1552
|
+
getNode(id) {
|
|
1553
|
+
return this.nodes.get(id);
|
|
1554
|
+
}
|
|
1555
|
+
getAllNodes() {
|
|
1556
|
+
return Array.from(this.nodes.values());
|
|
1557
|
+
}
|
|
1558
|
+
};
|
|
1559
|
+
|
|
1560
|
+
// src/task/graph-planner.ts
|
|
1561
|
+
var GraphPlanner = class {
|
|
1562
|
+
constructor(llmAdapter) {
|
|
1563
|
+
this.llmAdapter = llmAdapter;
|
|
1564
|
+
}
|
|
1565
|
+
async planGraph(goal, availableTools) {
|
|
1566
|
+
const prompt = this.buildGraphPlanningPrompt(goal, availableTools);
|
|
1567
|
+
let response;
|
|
1568
|
+
try {
|
|
1569
|
+
const result = await this.llmAdapter.chat(
|
|
1570
|
+
[{ role: "user", content: prompt }],
|
|
1571
|
+
[]
|
|
1572
|
+
// No tools for the planning call
|
|
1573
|
+
);
|
|
1574
|
+
response = result.content;
|
|
1575
|
+
} catch {
|
|
1576
|
+
return this.fallbackSequentialGraph(goal);
|
|
1577
|
+
}
|
|
1578
|
+
return this.parseGraphPlan(goal, response);
|
|
1579
|
+
}
|
|
1580
|
+
buildGraphPlanningPrompt(goal, tools) {
|
|
1581
|
+
const toolList = tools.map((t) => `- ${t.name}: ${t.description}`).join("\n");
|
|
1582
|
+
return [
|
|
1583
|
+
"You are a task planner that creates parallel execution plans. Break down the following goal into independently executable sub-tasks with dependencies.",
|
|
1584
|
+
"",
|
|
1585
|
+
`Goal: ${goal}`,
|
|
1586
|
+
"",
|
|
1587
|
+
"Available tools:",
|
|
1588
|
+
toolList,
|
|
1589
|
+
"",
|
|
1590
|
+
"Output your plan as a JSON array of sub-tasks, each with:",
|
|
1591
|
+
'- "id": unique identifier for this sub-task (string, e.g. "search", "analyze", "translate")',
|
|
1592
|
+
'- "goal": what this sub-task accomplishes (string)',
|
|
1593
|
+
'- "dependsOn": array of sub-task IDs that must complete before this one starts (string[], use empty array if no dependencies)',
|
|
1594
|
+
'- "tools": suggested tool names for this sub-task (string[], can be empty)',
|
|
1595
|
+
"",
|
|
1596
|
+
"Rules:",
|
|
1597
|
+
"- Sub-tasks with NO dependencies (empty dependsOn) can execute in parallel",
|
|
1598
|
+
"- Sub-task B needs sub-task A's output \u2192 B's dependsOn must include A's id",
|
|
1599
|
+
"- Maximize parallelism: if two sub-tasks have no data dependency, they should NOT have dependsOn relationships",
|
|
1600
|
+
"- Each sub-task should specify only the tools it needs",
|
|
1601
|
+
"- Keep sub-tasks focused \u2014 one logical action per sub-task",
|
|
1602
|
+
"- Output ONLY the JSON array, no other text",
|
|
1603
|
+
"",
|
|
1604
|
+
"Example:",
|
|
1605
|
+
'[{"id":"search_jp","goal":"Search for Japanese restaurants","dependsOn":[],"tools":["web_search"]},{"id":"search_it","goal":"Search for Italian restaurants","dependsOn":[],"tools":["web_search"]},{"id":"compare","goal":"Compare the two restaurant lists","dependsOn":["search_jp","search_it"],"tools":["code_eval"]}]',
|
|
1606
|
+
"",
|
|
1607
|
+
"Your plan:"
|
|
1608
|
+
].join("\n");
|
|
1609
|
+
}
|
|
1610
|
+
parseGraphPlan(goal, content) {
|
|
1611
|
+
const nodes = this.extractGraphNodes(content);
|
|
1612
|
+
const now = Date.now();
|
|
1613
|
+
if (nodes.length === 0) {
|
|
1614
|
+
return this.fallbackSequentialGraph(goal);
|
|
1615
|
+
}
|
|
1616
|
+
const graph = new TaskGraph(nodes);
|
|
1617
|
+
const validation = graph.validate();
|
|
1618
|
+
if (!validation.valid) {
|
|
1619
|
+
return this.fallbackSequentialGraph(goal);
|
|
1620
|
+
}
|
|
1621
|
+
const levels = graph.computeLevels();
|
|
1622
|
+
return {
|
|
1623
|
+
id: `graph-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1624
|
+
goal,
|
|
1625
|
+
nodes,
|
|
1626
|
+
levels,
|
|
1627
|
+
status: "planning",
|
|
1628
|
+
results: {},
|
|
1629
|
+
createdAt: now,
|
|
1630
|
+
updatedAt: now,
|
|
1631
|
+
totalTokenUsage: { input: 0, output: 0 }
|
|
1632
|
+
};
|
|
1633
|
+
}
|
|
1634
|
+
extractGraphNodes(content) {
|
|
1635
|
+
const jsonStr = this.extractJSON(content);
|
|
1636
|
+
if (!jsonStr) return [];
|
|
1637
|
+
try {
|
|
1638
|
+
const parsed = JSON.parse(jsonStr);
|
|
1639
|
+
if (!Array.isArray(parsed)) return [];
|
|
1640
|
+
return parsed.filter((item) => typeof item === "object" && item.id && item.goal).map((item) => ({
|
|
1641
|
+
id: String(item.id),
|
|
1642
|
+
goal: String(item.goal),
|
|
1643
|
+
dependsOn: Array.isArray(item.dependsOn) ? item.dependsOn.filter((d) => typeof d === "string") : [],
|
|
1644
|
+
triggerRule: item.triggerRule ?? void 0,
|
|
1645
|
+
agent: item.agent ?? void 0,
|
|
1646
|
+
retry: item.retry ?? void 0,
|
|
1647
|
+
fallback: item.fallback ?? void 0,
|
|
1648
|
+
timeout: typeof item.timeout === "number" ? item.timeout : void 0
|
|
1649
|
+
}));
|
|
1650
|
+
} catch {
|
|
1651
|
+
return [];
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
extractJSON(content) {
|
|
1655
|
+
const start = content.indexOf("[");
|
|
1656
|
+
const end = content.lastIndexOf("]");
|
|
1657
|
+
if (start !== -1 && end > start) {
|
|
1658
|
+
return content.slice(start, end + 1);
|
|
1659
|
+
}
|
|
1660
|
+
return null;
|
|
1661
|
+
}
|
|
1662
|
+
/** Fallback: create a sequential graph (each node depends on the previous one) */
|
|
1663
|
+
fallbackSequentialGraph(goal) {
|
|
1664
|
+
const now = Date.now();
|
|
1665
|
+
const nodes = [
|
|
1666
|
+
{
|
|
1667
|
+
id: "step-1",
|
|
1668
|
+
goal,
|
|
1669
|
+
dependsOn: []
|
|
1670
|
+
}
|
|
1671
|
+
];
|
|
1672
|
+
const levels = [["step-1"]];
|
|
1673
|
+
return {
|
|
1674
|
+
id: `graph-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
1675
|
+
goal,
|
|
1676
|
+
nodes,
|
|
1677
|
+
levels,
|
|
1678
|
+
status: "planning",
|
|
1679
|
+
results: {},
|
|
1680
|
+
createdAt: now,
|
|
1681
|
+
updatedAt: now,
|
|
1682
|
+
totalTokenUsage: { input: 0, output: 0 }
|
|
1683
|
+
};
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
|
|
1687
|
+
// src/sub-agent.ts
|
|
1688
|
+
var SubAgent = class {
|
|
1689
|
+
constructor(options) {
|
|
1690
|
+
this.sessionId = null;
|
|
1691
|
+
this.status = "idle";
|
|
1692
|
+
this.id = `subagent-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
1693
|
+
this.nodeId = options.nodeId;
|
|
1694
|
+
this.parentAgent = options.parentAgent;
|
|
1695
|
+
this.config = options.config;
|
|
1696
|
+
this.depth = options.depth;
|
|
1697
|
+
this.abortController = new AbortController();
|
|
1698
|
+
if (options.parentSignal) {
|
|
1699
|
+
options.parentSignal.addEventListener("abort", () => this.abortController.abort(), { once: true });
|
|
1700
|
+
}
|
|
1701
|
+
const maxDepth = this.config.maxDepth ?? 2;
|
|
1702
|
+
if (this.depth >= maxDepth) {
|
|
1703
|
+
this.config.canSpawnSubAgents = false;
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
/** Execute the sub-agent task with upstream outputs as context */
|
|
1707
|
+
async execute(goal, upstreamOutputs) {
|
|
1708
|
+
this.status = "running";
|
|
1709
|
+
const startTime = Date.now();
|
|
1710
|
+
try {
|
|
1711
|
+
const session = this.parentAgent.createSession({
|
|
1712
|
+
title: `SubAgent: ${this.nodeId}`,
|
|
1713
|
+
meta: {
|
|
1714
|
+
parentSessionId: this.parentAgent.getCurrentSessionId(),
|
|
1715
|
+
subAgentId: this.id,
|
|
1716
|
+
nodeId: this.nodeId,
|
|
1717
|
+
depth: this.depth
|
|
1718
|
+
},
|
|
1719
|
+
systemPrompt: this.config.systemPrompt
|
|
1720
|
+
});
|
|
1721
|
+
this.sessionId = session.id;
|
|
1722
|
+
const prompt = this.buildPrompt(goal, upstreamOutputs);
|
|
1723
|
+
const options = {
|
|
1724
|
+
sessionId: session.id,
|
|
1725
|
+
maxTurns: this.config.maxTurns ?? 10,
|
|
1726
|
+
depth: this.depth + 1,
|
|
1727
|
+
taskMode: void 0
|
|
1728
|
+
// Sub-agents don't recursively plan unless configured
|
|
1729
|
+
};
|
|
1730
|
+
if (this.config.tools) {
|
|
1731
|
+
options.tools = this.config.tools;
|
|
1732
|
+
}
|
|
1733
|
+
let result;
|
|
1734
|
+
try {
|
|
1735
|
+
result = await this.parentAgent.chatInner(prompt, session.id, options);
|
|
1736
|
+
} catch (err) {
|
|
1737
|
+
this.status = "failed";
|
|
1738
|
+
return {
|
|
1739
|
+
nodeId: this.nodeId,
|
|
1740
|
+
status: "failed",
|
|
1741
|
+
error: err.message,
|
|
1742
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1743
|
+
duration: Date.now() - startTime,
|
|
1744
|
+
retryCount: 0,
|
|
1745
|
+
sessionId: this.sessionId ?? void 0
|
|
1746
|
+
};
|
|
1747
|
+
}
|
|
1748
|
+
this.status = "done";
|
|
1749
|
+
return {
|
|
1750
|
+
nodeId: this.nodeId,
|
|
1751
|
+
status: "done",
|
|
1752
|
+
output: result.reply,
|
|
1753
|
+
tokenUsage: result.tokenUsage,
|
|
1754
|
+
duration: Date.now() - startTime,
|
|
1755
|
+
retryCount: 0,
|
|
1756
|
+
sessionId: this.sessionId ?? void 0
|
|
1757
|
+
};
|
|
1758
|
+
} catch (err) {
|
|
1759
|
+
this.status = "failed";
|
|
1760
|
+
return {
|
|
1761
|
+
nodeId: this.nodeId,
|
|
1762
|
+
status: "failed",
|
|
1763
|
+
error: err.message,
|
|
1764
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1765
|
+
duration: Date.now() - startTime,
|
|
1766
|
+
retryCount: 0,
|
|
1767
|
+
sessionId: this.sessionId ?? void 0
|
|
1768
|
+
};
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
/** Abort the sub-agent */
|
|
1772
|
+
abort() {
|
|
1773
|
+
this.abortController.abort();
|
|
1774
|
+
this.status = "aborted";
|
|
1775
|
+
}
|
|
1776
|
+
getStatus() {
|
|
1777
|
+
return this.status;
|
|
1778
|
+
}
|
|
1779
|
+
buildPrompt(goal, upstreamOutputs) {
|
|
1780
|
+
const parts = [];
|
|
1781
|
+
const outputEntries = Object.entries(upstreamOutputs);
|
|
1782
|
+
if (outputEntries.length > 0) {
|
|
1783
|
+
parts.push("[Upstream Results]:");
|
|
1784
|
+
for (const [nodeId, output] of outputEntries) {
|
|
1785
|
+
parts.push(`- ${nodeId}: "${output.slice(0, 500)}"`);
|
|
1786
|
+
}
|
|
1787
|
+
parts.push("");
|
|
1788
|
+
}
|
|
1789
|
+
parts.push(`Your task: ${goal}`);
|
|
1790
|
+
if (this.config.tools && this.config.tools.length > 0) {
|
|
1791
|
+
parts.push(`
|
|
1792
|
+
Available tools: ${this.config.tools.join(", ")}`);
|
|
1793
|
+
}
|
|
1794
|
+
if (!this.config.canSpawnSubAgents) {
|
|
1795
|
+
parts.push("\nNote: You cannot delegate to sub-agents. Complete the task directly.");
|
|
1796
|
+
}
|
|
1797
|
+
return parts.join("\n");
|
|
1798
|
+
}
|
|
1799
|
+
};
|
|
1800
|
+
|
|
1801
|
+
// src/task/graph-executor.ts
|
|
1802
|
+
var CIRCUIT_BREAKER_THRESHOLD = 3;
|
|
1803
|
+
var GraphExecutor = class {
|
|
1804
|
+
constructor(options) {
|
|
1805
|
+
this.toolFailureCount = /* @__PURE__ */ new Map();
|
|
1806
|
+
this.graph = options.graph;
|
|
1807
|
+
this.plan = options.plan;
|
|
1808
|
+
this.parentAgent = options.parentAgent;
|
|
1809
|
+
this.maxConcurrency = options.maxConcurrency ?? 3;
|
|
1810
|
+
this.maxDepth = options.maxDepth ?? 2;
|
|
1811
|
+
this.baseDepth = options.baseDepth ?? 0;
|
|
1812
|
+
this.abortController = new AbortController();
|
|
1813
|
+
this.emit = options.emit;
|
|
1814
|
+
}
|
|
1815
|
+
/** Execute the entire graph, level by level */
|
|
1816
|
+
async execute() {
|
|
1817
|
+
this.plan.status = "executing";
|
|
1818
|
+
for (let level = 0; level < this.graph.getLevelCount(); level++) {
|
|
1819
|
+
if (this.abortController.signal.aborted) {
|
|
1820
|
+
this.plan.status = "failed";
|
|
1821
|
+
return this.plan;
|
|
1822
|
+
}
|
|
1823
|
+
const nodes = this.graph.getLevel(level);
|
|
1824
|
+
const nodeIds = nodes.map((n) => n.id);
|
|
1825
|
+
this.emit("graph:level_start", { level, nodeIds });
|
|
1826
|
+
await this.executeLevel(level, nodes);
|
|
1827
|
+
const levelResults = nodeIds.map((id) => this.plan.results[id]).filter(Boolean);
|
|
1828
|
+
this.emit("graph:level_complete", { level, results: levelResults });
|
|
1829
|
+
}
|
|
1830
|
+
const progress = this.getProgress();
|
|
1831
|
+
if (progress.failed === 0 && progress.done === progress.total) {
|
|
1832
|
+
this.plan.status = "completed";
|
|
1833
|
+
this.emit("graph:complete", { plan: this.plan, progress });
|
|
1834
|
+
} else if (progress.done > 0) {
|
|
1835
|
+
this.plan.status = "partial";
|
|
1836
|
+
this.emit("graph:complete", { plan: this.plan, progress });
|
|
1837
|
+
} else {
|
|
1838
|
+
this.plan.status = "failed";
|
|
1839
|
+
const failedNodes = Object.entries(this.plan.results).filter(([, r]) => r.status === "failed").map(([id]) => id);
|
|
1840
|
+
this.emit("graph:failed", { plan: this.plan, failedNodes });
|
|
1841
|
+
}
|
|
1842
|
+
this.plan.updatedAt = Date.now();
|
|
1843
|
+
return this.plan;
|
|
1844
|
+
}
|
|
1845
|
+
/** Execute a single level — nodes run concurrently (limited by maxConcurrency) */
|
|
1846
|
+
async executeLevel(level, nodes) {
|
|
1847
|
+
const runnableNodes = nodes.filter((node) => this.shouldRun(node));
|
|
1848
|
+
for (const node of nodes) {
|
|
1849
|
+
if (!runnableNodes.includes(node)) {
|
|
1850
|
+
this.plan.results[node.id] = {
|
|
1851
|
+
nodeId: node.id,
|
|
1852
|
+
status: "skipped",
|
|
1853
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1854
|
+
duration: 0,
|
|
1855
|
+
retryCount: 0
|
|
1856
|
+
};
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
const semaphore = new Semaphore(this.maxConcurrency);
|
|
1860
|
+
const promises = runnableNodes.map(
|
|
1861
|
+
(node) => semaphore.acquire().then(async (release) => {
|
|
1862
|
+
try {
|
|
1863
|
+
await this.executeNode(node);
|
|
1864
|
+
} finally {
|
|
1865
|
+
release();
|
|
1866
|
+
}
|
|
1867
|
+
})
|
|
1868
|
+
);
|
|
1869
|
+
await Promise.allSettled(promises);
|
|
1870
|
+
}
|
|
1871
|
+
/** Execute a single node with retry + fallback */
|
|
1872
|
+
async executeNode(node) {
|
|
1873
|
+
if (this.abortController.signal.aborted) {
|
|
1874
|
+
this.plan.results[node.id] = {
|
|
1875
|
+
nodeId: node.id,
|
|
1876
|
+
status: "skipped",
|
|
1877
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1878
|
+
duration: 0,
|
|
1879
|
+
retryCount: 0
|
|
1880
|
+
};
|
|
1881
|
+
return;
|
|
1882
|
+
}
|
|
1883
|
+
const result = await this.executeWithRetry(node);
|
|
1884
|
+
this.plan.results[node.id] = result;
|
|
1885
|
+
this.plan.totalTokenUsage.input += result.tokenUsage.input;
|
|
1886
|
+
this.plan.totalTokenUsage.output += result.tokenUsage.output;
|
|
1887
|
+
if (result.status === "failed" && result.error) {
|
|
1888
|
+
this.trackToolFailures(node, result.error);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
/** Check if a node should execute based on its trigger rule and upstream results */
|
|
1892
|
+
shouldRun(node) {
|
|
1893
|
+
const rule = node.triggerRule ?? "all_success";
|
|
1894
|
+
if (node.dependsOn.length === 0) {
|
|
1895
|
+
return true;
|
|
1896
|
+
}
|
|
1897
|
+
const upstreamResults = node.dependsOn.map((depId) => this.plan.results[depId]).filter(Boolean);
|
|
1898
|
+
switch (rule) {
|
|
1899
|
+
case "all_success":
|
|
1900
|
+
return upstreamResults.length === node.dependsOn.length && upstreamResults.every((r) => r.status === "done");
|
|
1901
|
+
case "one_success":
|
|
1902
|
+
return upstreamResults.some((r) => r.status === "done");
|
|
1903
|
+
case "none_failed":
|
|
1904
|
+
return !upstreamResults.some((r) => r.status === "failed");
|
|
1905
|
+
case "all_done":
|
|
1906
|
+
return upstreamResults.length === node.dependsOn.length && upstreamResults.every(
|
|
1907
|
+
(r) => r.status === "done" || r.status === "failed" || r.status === "bypassed"
|
|
1908
|
+
);
|
|
1909
|
+
case "always":
|
|
1910
|
+
return true;
|
|
1911
|
+
default:
|
|
1912
|
+
return true;
|
|
1913
|
+
}
|
|
1914
|
+
}
|
|
1915
|
+
/** Execute with retry (exponential backoff) */
|
|
1916
|
+
async executeWithRetry(node) {
|
|
1917
|
+
const retry = node.retry ?? { maxRetries: 1 };
|
|
1918
|
+
const maxRetries = retry.maxRetries;
|
|
1919
|
+
const backoffMs = retry.backoffMs ?? 1e3;
|
|
1920
|
+
const maxBackoffMs = retry.maxBackoffMs ?? 3e4;
|
|
1921
|
+
let lastError = "";
|
|
1922
|
+
let retryCount = 0;
|
|
1923
|
+
for (let attempt = 0; attempt <= maxRetries; attempt++) {
|
|
1924
|
+
if (this.abortController.signal.aborted) {
|
|
1925
|
+
return {
|
|
1926
|
+
nodeId: node.id,
|
|
1927
|
+
status: "skipped",
|
|
1928
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1929
|
+
duration: 0,
|
|
1930
|
+
retryCount
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
const result = await this.runSubAgent(node);
|
|
1934
|
+
if (result.status === "done") {
|
|
1935
|
+
return { ...result, retryCount };
|
|
1936
|
+
}
|
|
1937
|
+
lastError = result.error ?? "Unknown error";
|
|
1938
|
+
retryCount = attempt + 1;
|
|
1939
|
+
if (attempt < maxRetries) {
|
|
1940
|
+
this.emit("subagent:fail", {
|
|
1941
|
+
nodeId: node.id,
|
|
1942
|
+
sessionId: result.sessionId,
|
|
1943
|
+
error: lastError,
|
|
1944
|
+
retryCount,
|
|
1945
|
+
willRetry: true
|
|
1946
|
+
});
|
|
1947
|
+
const delay = Math.min(backoffMs * Math.pow(2, attempt), maxBackoffMs);
|
|
1948
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1949
|
+
}
|
|
1950
|
+
}
|
|
1951
|
+
if (node.fallback) {
|
|
1952
|
+
this.emit("subagent:fail", {
|
|
1953
|
+
nodeId: node.id,
|
|
1954
|
+
sessionId: void 0,
|
|
1955
|
+
error: lastError,
|
|
1956
|
+
retryCount,
|
|
1957
|
+
willRetry: false
|
|
1958
|
+
});
|
|
1959
|
+
return this.runFallback(node, lastError, retryCount);
|
|
1960
|
+
}
|
|
1961
|
+
this.emit("subagent:fail", {
|
|
1962
|
+
nodeId: node.id,
|
|
1963
|
+
sessionId: void 0,
|
|
1964
|
+
error: lastError,
|
|
1965
|
+
retryCount,
|
|
1966
|
+
willRetry: false
|
|
1967
|
+
});
|
|
1968
|
+
return {
|
|
1969
|
+
nodeId: node.id,
|
|
1970
|
+
status: "failed",
|
|
1971
|
+
error: lastError,
|
|
1972
|
+
tokenUsage: { input: 0, output: 0 },
|
|
1973
|
+
duration: 0,
|
|
1974
|
+
retryCount
|
|
1975
|
+
};
|
|
1976
|
+
}
|
|
1977
|
+
/** Run a SubAgent for a node */
|
|
1978
|
+
async runSubAgent(node) {
|
|
1979
|
+
const agentConfig = node.agent ?? {};
|
|
1980
|
+
const subAgent = new SubAgent({
|
|
1981
|
+
nodeId: node.id,
|
|
1982
|
+
parentAgent: this.parentAgent,
|
|
1983
|
+
config: agentConfig,
|
|
1984
|
+
depth: this.baseDepth,
|
|
1985
|
+
parentSignal: this.abortController.signal
|
|
1986
|
+
});
|
|
1987
|
+
const filteredConfig = { ...agentConfig };
|
|
1988
|
+
if (filteredConfig.tools) {
|
|
1989
|
+
filteredConfig.tools = filteredConfig.tools.filter(
|
|
1990
|
+
(tool) => !this.isToolCircuitOpen(tool)
|
|
1991
|
+
);
|
|
1992
|
+
}
|
|
1993
|
+
const upstreamOutputs = {};
|
|
1994
|
+
for (const depId of node.dependsOn) {
|
|
1995
|
+
const depResult = this.plan.results[depId];
|
|
1996
|
+
if (depResult?.output) {
|
|
1997
|
+
upstreamOutputs[depId] = depResult.output;
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
this.emit("subagent:spawn", {
|
|
2001
|
+
nodeId: node.id,
|
|
2002
|
+
sessionId: subAgent.id,
|
|
2003
|
+
goal: node.goal,
|
|
2004
|
+
depth: this.baseDepth
|
|
2005
|
+
});
|
|
2006
|
+
if (node.timeout) {
|
|
2007
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
2008
|
+
setTimeout(() => reject(new ACPError(
|
|
2009
|
+
ACPErrorCodes.SUBAGENT_TIMEOUT,
|
|
2010
|
+
`Node "${node.id}" timed out after ${node.timeout}ms`
|
|
2011
|
+
)), node.timeout);
|
|
2012
|
+
});
|
|
2013
|
+
try {
|
|
2014
|
+
return await Promise.race([
|
|
2015
|
+
subAgent.execute(node.goal, upstreamOutputs),
|
|
2016
|
+
timeoutPromise
|
|
2017
|
+
]);
|
|
2018
|
+
} catch (err) {
|
|
2019
|
+
subAgent.abort();
|
|
2020
|
+
return {
|
|
2021
|
+
nodeId: node.id,
|
|
2022
|
+
status: "failed",
|
|
2023
|
+
error: err.message,
|
|
2024
|
+
tokenUsage: { input: 0, output: 0 },
|
|
2025
|
+
duration: 0,
|
|
2026
|
+
retryCount: 0
|
|
2027
|
+
};
|
|
2028
|
+
}
|
|
2029
|
+
}
|
|
2030
|
+
return subAgent.execute(node.goal, upstreamOutputs);
|
|
2031
|
+
}
|
|
2032
|
+
/** Fallback handling: bypass / fallback / compensate */
|
|
2033
|
+
async runFallback(node, lastError, retryCount) {
|
|
2034
|
+
const fallback = node.fallback;
|
|
2035
|
+
switch (fallback.type) {
|
|
2036
|
+
case "bypass": {
|
|
2037
|
+
this.emit("subagent:bypass", { nodeId: node.id, reason: lastError });
|
|
2038
|
+
return {
|
|
2039
|
+
nodeId: node.id,
|
|
2040
|
+
status: "bypassed",
|
|
2041
|
+
output: `[Node bypassed: ${lastError}]`,
|
|
2042
|
+
error: lastError,
|
|
2043
|
+
tokenUsage: { input: 0, output: 0 },
|
|
2044
|
+
duration: 0,
|
|
2045
|
+
retryCount
|
|
2046
|
+
};
|
|
2047
|
+
}
|
|
2048
|
+
case "fallback": {
|
|
2049
|
+
this.emit("subagent:fallback", { nodeId: node.id, fallbackType: "fallback" });
|
|
2050
|
+
const fallbackAgent = new SubAgent({
|
|
2051
|
+
nodeId: node.id,
|
|
2052
|
+
parentAgent: this.parentAgent,
|
|
2053
|
+
config: {
|
|
2054
|
+
systemPrompt: void 0,
|
|
2055
|
+
tools: fallback.fallbackTools,
|
|
2056
|
+
maxTurns: fallback.maxTurns ?? 10,
|
|
2057
|
+
canSpawnSubAgents: false
|
|
2058
|
+
},
|
|
2059
|
+
depth: this.baseDepth + 1,
|
|
2060
|
+
parentSignal: this.abortController.signal
|
|
2061
|
+
});
|
|
2062
|
+
const fallbackGoal = fallback.fallbackPrompt ?? `Alternative task for: ${node.goal}`;
|
|
2063
|
+
const upstreamOutputs = {};
|
|
2064
|
+
for (const depId of node.dependsOn) {
|
|
2065
|
+
const depResult = this.plan.results[depId];
|
|
2066
|
+
if (depResult?.output) {
|
|
2067
|
+
upstreamOutputs[depId] = depResult.output;
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
const result = await fallbackAgent.execute(fallbackGoal, upstreamOutputs);
|
|
2071
|
+
return { ...result, retryCount };
|
|
2072
|
+
}
|
|
2073
|
+
case "compensate": {
|
|
2074
|
+
this.emit("subagent:fallback", { nodeId: node.id, fallbackType: "compensate" });
|
|
2075
|
+
const compensations = fallback.compensations ?? {};
|
|
2076
|
+
for (const [compNodeId, compPrompt] of Object.entries(compensations)) {
|
|
2077
|
+
const compResult = this.plan.results[compNodeId];
|
|
2078
|
+
if (compResult?.status === "done") {
|
|
2079
|
+
this.emit("subagent:compensate", {
|
|
2080
|
+
nodeId: node.id,
|
|
2081
|
+
compensatingNodeId: compNodeId
|
|
2082
|
+
});
|
|
2083
|
+
const compAgent = new SubAgent({
|
|
2084
|
+
nodeId: `compensate-${compNodeId}`,
|
|
2085
|
+
parentAgent: this.parentAgent,
|
|
2086
|
+
config: { maxTurns: 5, canSpawnSubAgents: false },
|
|
2087
|
+
depth: this.baseDepth + 1,
|
|
2088
|
+
parentSignal: this.abortController.signal
|
|
2089
|
+
});
|
|
2090
|
+
await compAgent.execute(compPrompt, {
|
|
2091
|
+
[compNodeId]: compResult.output ?? ""
|
|
2092
|
+
});
|
|
2093
|
+
}
|
|
2094
|
+
}
|
|
2095
|
+
return {
|
|
2096
|
+
nodeId: node.id,
|
|
2097
|
+
status: "failed",
|
|
2098
|
+
error: `Failed but compensated: ${lastError}`,
|
|
2099
|
+
tokenUsage: { input: 0, output: 0 },
|
|
2100
|
+
duration: 0,
|
|
2101
|
+
retryCount
|
|
2102
|
+
};
|
|
2103
|
+
}
|
|
2104
|
+
default:
|
|
2105
|
+
return {
|
|
2106
|
+
nodeId: node.id,
|
|
2107
|
+
status: "failed",
|
|
2108
|
+
error: lastError,
|
|
2109
|
+
tokenUsage: { input: 0, output: 0 },
|
|
2110
|
+
duration: 0,
|
|
2111
|
+
retryCount
|
|
2112
|
+
};
|
|
2113
|
+
}
|
|
2114
|
+
}
|
|
2115
|
+
/** Circuit breaker: check if a tool has failed too many times */
|
|
2116
|
+
isToolCircuitOpen(toolName) {
|
|
2117
|
+
return (this.toolFailureCount.get(toolName) ?? 0) >= CIRCUIT_BREAKER_THRESHOLD;
|
|
2118
|
+
}
|
|
2119
|
+
/** Track tool failures for circuit breaking */
|
|
2120
|
+
trackToolFailures(node, error) {
|
|
2121
|
+
const tools = node.agent?.tools ?? [];
|
|
2122
|
+
for (const tool of tools) {
|
|
2123
|
+
if (error.includes(tool) || error.toLowerCase().includes("timeout") || error.toLowerCase().includes("error")) {
|
|
2124
|
+
this.toolFailureCount.set(tool, (this.toolFailureCount.get(tool) ?? 0) + 1);
|
|
2125
|
+
}
|
|
2126
|
+
}
|
|
2127
|
+
}
|
|
2128
|
+
/** Get execution progress */
|
|
2129
|
+
getProgress() {
|
|
2130
|
+
const results = Object.values(this.plan.results);
|
|
2131
|
+
const total = this.graph.getAllNodes().length;
|
|
2132
|
+
const done = results.filter((r) => r.status === "done").length;
|
|
2133
|
+
const failed = results.filter((r) => r.status === "failed").length;
|
|
2134
|
+
const bypassed = results.filter((r) => r.status === "bypassed").length;
|
|
2135
|
+
const running = results.filter((r) => r.status === "running").length;
|
|
2136
|
+
const pending = total - results.length;
|
|
2137
|
+
return {
|
|
2138
|
+
total,
|
|
2139
|
+
done,
|
|
2140
|
+
failed,
|
|
2141
|
+
bypassed,
|
|
2142
|
+
running,
|
|
2143
|
+
pending: pending > 0 ? pending : 0,
|
|
2144
|
+
percentage: total > 0 ? Math.round((done + bypassed) / total * 100) : 0
|
|
2145
|
+
};
|
|
2146
|
+
}
|
|
2147
|
+
/** Abort all sub-agents */
|
|
2148
|
+
abort() {
|
|
2149
|
+
this.abortController.abort();
|
|
2150
|
+
}
|
|
2151
|
+
};
|
|
2152
|
+
var Semaphore = class {
|
|
2153
|
+
constructor(max) {
|
|
2154
|
+
this.max = max;
|
|
2155
|
+
this.current = 0;
|
|
2156
|
+
this.queue = [];
|
|
2157
|
+
}
|
|
2158
|
+
async acquire() {
|
|
2159
|
+
if (this.current < this.max) {
|
|
2160
|
+
this.current++;
|
|
2161
|
+
return this.release.bind(this);
|
|
2162
|
+
}
|
|
2163
|
+
return new Promise((resolve) => {
|
|
2164
|
+
this.queue.push(resolve);
|
|
2165
|
+
});
|
|
2166
|
+
}
|
|
2167
|
+
release() {
|
|
2168
|
+
this.current--;
|
|
2169
|
+
const next = this.queue.shift();
|
|
2170
|
+
if (next) {
|
|
2171
|
+
this.current++;
|
|
2172
|
+
next(this.release.bind(this));
|
|
2173
|
+
}
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
2176
|
+
|
|
2177
|
+
// src/transport/local.ts
|
|
2178
|
+
var LocalTransport = class {
|
|
2179
|
+
constructor() {
|
|
2180
|
+
this.handlers = /* @__PURE__ */ new Map();
|
|
2181
|
+
}
|
|
2182
|
+
registerHandler(method, handler) {
|
|
2183
|
+
this.handlers.set(method, handler);
|
|
2184
|
+
}
|
|
2185
|
+
async send(method, params) {
|
|
2186
|
+
const handler = this.handlers.get(method);
|
|
2187
|
+
if (!handler) {
|
|
2188
|
+
return {
|
|
2189
|
+
error: { code: -32601, message: `Method not found: ${method}` }
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
return handler(params);
|
|
2193
|
+
}
|
|
2194
|
+
notify(_method, _params) {
|
|
2195
|
+
}
|
|
2196
|
+
};
|
|
2197
|
+
|
|
2198
|
+
// src/transport/http.ts
|
|
2199
|
+
var HttpTransport = class {
|
|
2200
|
+
constructor(baseUrl, authToken, customHeaders) {
|
|
2201
|
+
this.requestId = 0;
|
|
2202
|
+
this.baseUrl = baseUrl.replace(/\/+$/, "");
|
|
2203
|
+
this.authToken = authToken;
|
|
2204
|
+
this.customHeaders = customHeaders;
|
|
2205
|
+
}
|
|
2206
|
+
setSessionId(id) {
|
|
2207
|
+
this.sessionId = id;
|
|
2208
|
+
}
|
|
2209
|
+
setAuthToken(token) {
|
|
2210
|
+
this.authToken = token;
|
|
2211
|
+
}
|
|
2212
|
+
buildHeaders(extra) {
|
|
2213
|
+
const headers = {
|
|
2214
|
+
"Content-Type": "application/json",
|
|
2215
|
+
...extra || {}
|
|
2216
|
+
};
|
|
2217
|
+
if (this.authToken) {
|
|
2218
|
+
headers["Authorization"] = `Bearer ${this.authToken}`;
|
|
2219
|
+
}
|
|
2220
|
+
if (this.sessionId) {
|
|
2221
|
+
headers["Mcp-Session-Id"] = this.sessionId;
|
|
2222
|
+
}
|
|
2223
|
+
if (this.customHeaders) {
|
|
2224
|
+
Object.assign(headers, this.customHeaders);
|
|
2225
|
+
}
|
|
2226
|
+
return headers;
|
|
2227
|
+
}
|
|
2228
|
+
async send(method, params) {
|
|
2229
|
+
const id = ++this.requestId;
|
|
2230
|
+
const body = {
|
|
2231
|
+
jsonrpc: "2.0",
|
|
2232
|
+
id,
|
|
2233
|
+
method,
|
|
2234
|
+
params: params ?? {}
|
|
2235
|
+
};
|
|
2236
|
+
try {
|
|
2237
|
+
const res = await fetch(`${this.baseUrl}/mcp`, {
|
|
2238
|
+
method: "POST",
|
|
2239
|
+
headers: this.buildHeaders({ Accept: "application/json" }),
|
|
2240
|
+
body: JSON.stringify(body)
|
|
2241
|
+
});
|
|
2242
|
+
const data = await res.json();
|
|
2243
|
+
const sid = res.headers.get("Mcp-Session-Id");
|
|
2244
|
+
if (sid) this.sessionId = sid;
|
|
2245
|
+
if (data.error) {
|
|
2246
|
+
throw new ACPError(data.error.code, data.error.message, data.error.data);
|
|
2247
|
+
}
|
|
2248
|
+
return data.result;
|
|
2249
|
+
} catch (err) {
|
|
2250
|
+
if (err instanceof ACPError) throw err;
|
|
2251
|
+
throw new ACPError(
|
|
2252
|
+
ACPErrorCodes.TRANSPORT_ERROR,
|
|
2253
|
+
`Transport error: ${err.message}`,
|
|
2254
|
+
{ method, originalError: err.message }
|
|
2255
|
+
);
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
notify(method, params) {
|
|
2259
|
+
const body = {
|
|
2260
|
+
jsonrpc: "2.0",
|
|
2261
|
+
method,
|
|
2262
|
+
params: params ?? {}
|
|
2263
|
+
};
|
|
2264
|
+
fetch(`${this.baseUrl}/mcp`, {
|
|
2265
|
+
method: "POST",
|
|
2266
|
+
headers: this.buildHeaders(),
|
|
2267
|
+
body: JSON.stringify(body)
|
|
2268
|
+
}).catch(() => {
|
|
2269
|
+
});
|
|
2270
|
+
}
|
|
2271
|
+
/**
|
|
2272
|
+
* Stream a chat request via SSE.
|
|
2273
|
+
*/
|
|
2274
|
+
async *streamChat(method, params) {
|
|
2275
|
+
const id = ++this.requestId;
|
|
2276
|
+
const body = {
|
|
2277
|
+
jsonrpc: "2.0",
|
|
2278
|
+
id,
|
|
2279
|
+
method,
|
|
2280
|
+
params: params ?? {}
|
|
2281
|
+
};
|
|
2282
|
+
const res = await fetch(`${this.baseUrl}/mcp`, {
|
|
2283
|
+
method: "POST",
|
|
2284
|
+
headers: this.buildHeaders({ Accept: "text/event-stream" }),
|
|
2285
|
+
body: JSON.stringify(body)
|
|
2286
|
+
});
|
|
2287
|
+
if (!res.body) {
|
|
2288
|
+
throw new ACPError(ACPErrorCodes.TRANSPORT_ERROR, "No response body for stream");
|
|
2289
|
+
}
|
|
2290
|
+
const reader = res.body.getReader();
|
|
2291
|
+
const decoder = new TextDecoder();
|
|
2292
|
+
let buffer = "";
|
|
2293
|
+
while (true) {
|
|
2294
|
+
const { done, value } = await reader.read();
|
|
2295
|
+
if (done) break;
|
|
2296
|
+
buffer += decoder.decode(value, { stream: true });
|
|
2297
|
+
const lines = buffer.split("\n");
|
|
2298
|
+
buffer = lines.pop() || "";
|
|
2299
|
+
for (const line of lines) {
|
|
2300
|
+
if (line.startsWith("data: ")) {
|
|
2301
|
+
try {
|
|
2302
|
+
const data = JSON.parse(line.slice(6));
|
|
2303
|
+
if (data.result !== void 0) {
|
|
2304
|
+
yield { id: data.id, result: data.result };
|
|
2305
|
+
} else if (data.method) {
|
|
2306
|
+
yield { method: data.method, params: data.params };
|
|
2307
|
+
}
|
|
2308
|
+
} catch {
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
};
|
|
2315
|
+
|
|
2316
|
+
// src/persistence/memory.ts
|
|
2317
|
+
var MemoryPersistence = class {
|
|
2318
|
+
constructor() {
|
|
2319
|
+
this.sessions = /* @__PURE__ */ new Map();
|
|
2320
|
+
this.settings = /* @__PURE__ */ new Map();
|
|
2321
|
+
}
|
|
2322
|
+
async saveSession(session) {
|
|
2323
|
+
this.sessions.set(session.id, session);
|
|
2324
|
+
}
|
|
2325
|
+
async loadSession(sessionId) {
|
|
2326
|
+
return this.sessions.get(sessionId) ?? null;
|
|
2327
|
+
}
|
|
2328
|
+
async listSessions(options) {
|
|
2329
|
+
let result = Array.from(this.sessions.values());
|
|
2330
|
+
if (options?.status) {
|
|
2331
|
+
result = result.filter((s) => s.status === options.status);
|
|
2332
|
+
}
|
|
2333
|
+
result.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
2334
|
+
const offset = options?.offset ?? 0;
|
|
2335
|
+
const limit = options?.limit ?? 50;
|
|
2336
|
+
return result.slice(offset, offset + limit);
|
|
2337
|
+
}
|
|
2338
|
+
async deleteSession(sessionId) {
|
|
2339
|
+
this.sessions.delete(sessionId);
|
|
2340
|
+
}
|
|
2341
|
+
async saveSetting(key, value) {
|
|
2342
|
+
this.settings.set(key, value);
|
|
2343
|
+
}
|
|
2344
|
+
async loadSetting(key) {
|
|
2345
|
+
return this.settings.get(key);
|
|
2346
|
+
}
|
|
2347
|
+
};
|
|
2348
|
+
|
|
2349
|
+
// src/ldoing.ts
|
|
2350
|
+
function detectRuntime() {
|
|
2351
|
+
if (typeof window !== "undefined" && typeof document !== "undefined") return "browser";
|
|
2352
|
+
return "node";
|
|
2353
|
+
}
|
|
2354
|
+
var Ldoing = class {
|
|
2355
|
+
constructor(config) {
|
|
2356
|
+
this.initialized = false;
|
|
2357
|
+
this.startTime = 0;
|
|
2358
|
+
this.currentSessionId = null;
|
|
2359
|
+
this.abortControllers = /* @__PURE__ */ new Map();
|
|
2360
|
+
// Approval pending promises
|
|
2361
|
+
this.approvalResolvers = /* @__PURE__ */ new Map();
|
|
2362
|
+
// Event listeners
|
|
2363
|
+
this.eventHandlers = /* @__PURE__ */ new Map();
|
|
2364
|
+
// Token estimation calibration
|
|
2365
|
+
this.tokenCalibrationRatio = 1;
|
|
2366
|
+
this.config = config;
|
|
2367
|
+
this.agentId = `agent-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
2368
|
+
this.llmAdapter = new OpenAIAdapter(config.llm);
|
|
2369
|
+
this.skillRegistry = new SkillRegistry();
|
|
2370
|
+
this.skillExecutor = new SkillExecutor(this.skillRegistry);
|
|
2371
|
+
this.mcpRouter = new McpRouter();
|
|
2372
|
+
this.sessionManager = new SessionManager();
|
|
2373
|
+
this.contextManager = new ContextManager(config.context, config.llm.model);
|
|
2374
|
+
if (config.serverUrl) {
|
|
2375
|
+
this.transport = new HttpTransport(config.serverUrl, config.authToken, config.headers);
|
|
2376
|
+
} else {
|
|
2377
|
+
this.transport = new LocalTransport();
|
|
2378
|
+
}
|
|
2379
|
+
this.persistence = config.persistence ?? new MemoryPersistence();
|
|
2380
|
+
}
|
|
2381
|
+
// ---- Lifecycle ----
|
|
2382
|
+
async init() {
|
|
2383
|
+
this.startTime = Date.now();
|
|
2384
|
+
const skillConfig = this.config.skills ?? {};
|
|
2385
|
+
if (skillConfig.loadDefaults !== false) {
|
|
2386
|
+
if (this.config.skillProvider) {
|
|
2387
|
+
this.config.skillProvider.loadSkills(this.skillRegistry, {
|
|
2388
|
+
disable: skillConfig.disable,
|
|
2389
|
+
enable: skillConfig.enable,
|
|
2390
|
+
tiers: skillConfig.tiers,
|
|
2391
|
+
permissions: skillConfig.permissions
|
|
2392
|
+
});
|
|
2393
|
+
}
|
|
2394
|
+
}
|
|
2395
|
+
let mode = "local";
|
|
2396
|
+
let connected = false;
|
|
2397
|
+
if (this.config.serverUrl) {
|
|
2398
|
+
try {
|
|
2399
|
+
const result2 = await this.transport.send("initialize", {
|
|
2400
|
+
protocolVersion: "2025-03-26",
|
|
2401
|
+
capabilities: {
|
|
2402
|
+
acp: {
|
|
2403
|
+
chat: true,
|
|
2404
|
+
sessions: true,
|
|
2405
|
+
contextManagement: true,
|
|
2406
|
+
dynamicSkillRegistration: true,
|
|
2407
|
+
llmConfig: this.config.llm
|
|
2408
|
+
}
|
|
2409
|
+
},
|
|
2410
|
+
clientInfo: { name: "listdoing-sdk", version: "0.1.0" }
|
|
2411
|
+
});
|
|
2412
|
+
connected = true;
|
|
2413
|
+
const serverSkills = result2?.capabilities?.acp?.serverSkills ?? [];
|
|
2414
|
+
for (const name of serverSkills) {
|
|
2415
|
+
if (!this.skillRegistry.has(name)) {
|
|
2416
|
+
this.skillRegistry.register({
|
|
2417
|
+
name,
|
|
2418
|
+
description: `Server skill: ${name}`,
|
|
2419
|
+
inputSchema: { type: "object", properties: {} },
|
|
2420
|
+
location: "server"
|
|
2421
|
+
});
|
|
2422
|
+
}
|
|
2423
|
+
}
|
|
2424
|
+
mode = this.skillRegistry.list().some((s) => s.location === "local") ? "hybrid" : "remote";
|
|
2425
|
+
} catch {
|
|
2426
|
+
mode = "local";
|
|
2427
|
+
}
|
|
2428
|
+
}
|
|
2429
|
+
let llmConnected = false;
|
|
2430
|
+
try {
|
|
2431
|
+
llmConnected = true;
|
|
2432
|
+
} catch {
|
|
2433
|
+
llmConnected = false;
|
|
2434
|
+
}
|
|
2435
|
+
this.initialized = true;
|
|
2436
|
+
const result = {
|
|
2437
|
+
agentId: this.agentId,
|
|
2438
|
+
mode,
|
|
2439
|
+
llm: {
|
|
2440
|
+
connected: llmConnected,
|
|
2441
|
+
provider: this.config.llm.adapter,
|
|
2442
|
+
model: this.config.llm.model
|
|
2443
|
+
},
|
|
2444
|
+
capabilities: {
|
|
2445
|
+
localSkills: this.skillRegistry.list().filter((s) => s.location !== "server").map((s) => s.name),
|
|
2446
|
+
serverSkills: this.skillRegistry.list().filter((s) => s.location === "server").map((s) => s.name),
|
|
2447
|
+
llmProxy: mode !== "local"
|
|
2448
|
+
}
|
|
2449
|
+
};
|
|
2450
|
+
this.emit("init", result);
|
|
2451
|
+
return result;
|
|
2452
|
+
}
|
|
2453
|
+
async destroy() {
|
|
2454
|
+
for (const [, controller] of this.abortControllers) {
|
|
2455
|
+
controller.abort();
|
|
2456
|
+
}
|
|
2457
|
+
this.abortControllers.clear();
|
|
2458
|
+
this.initialized = false;
|
|
2459
|
+
this.emit("destroy", {});
|
|
2460
|
+
}
|
|
2461
|
+
getStatus() {
|
|
2462
|
+
return {
|
|
2463
|
+
agentId: this.agentId,
|
|
2464
|
+
mode: this.config.serverUrl ? "hybrid" : "local",
|
|
2465
|
+
uptime: Date.now() - this.startTime,
|
|
2466
|
+
activeSessions: this.sessionManager.list({ status: "active" }).length,
|
|
2467
|
+
loadedSkills: this.skillRegistry.list().length,
|
|
2468
|
+
llm: {
|
|
2469
|
+
adapter: this.config.llm.adapter,
|
|
2470
|
+
model: this.config.llm.model,
|
|
2471
|
+
connected: true
|
|
2472
|
+
}
|
|
2473
|
+
};
|
|
2474
|
+
}
|
|
2475
|
+
// ---- Chat ----
|
|
2476
|
+
async chat(message, options) {
|
|
2477
|
+
this.ensureInitialized();
|
|
2478
|
+
if (options?.taskMode === "plan") {
|
|
2479
|
+
return this.chatWithPlan(message, options);
|
|
2480
|
+
}
|
|
2481
|
+
if (options?.taskMode === "graph") {
|
|
2482
|
+
return this.chatWithGraph(message, options);
|
|
2483
|
+
}
|
|
2484
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
2485
|
+
this.currentSessionId = sessionId;
|
|
2486
|
+
const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
|
|
2487
|
+
const requireApproval = new Set(options?.requireApproval ?? []);
|
|
2488
|
+
const controller = new AbortController();
|
|
2489
|
+
this.abortControllers.set(sessionId, controller);
|
|
2490
|
+
const startTime = Date.now();
|
|
2491
|
+
let totalInputTokens = 0;
|
|
2492
|
+
let totalOutputTokens = 0;
|
|
2493
|
+
const executionTrace = [];
|
|
2494
|
+
try {
|
|
2495
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
2496
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
2497
|
+
let turn = 0;
|
|
2498
|
+
let continueLoop = true;
|
|
2499
|
+
let retried = false;
|
|
2500
|
+
while (continueLoop && turn < maxTurns) {
|
|
2501
|
+
turn++;
|
|
2502
|
+
const session2 = this.sessionManager.getOrThrow(sessionId);
|
|
2503
|
+
const systemPrompt = this.resolveSystemPrompt(sessionId, session2.systemPrompt ?? this.config.systemPrompt ?? "");
|
|
2504
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
2505
|
+
const tools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
2506
|
+
for (const name of this.computeAutoApproval(tools)) {
|
|
2507
|
+
requireApproval.add(name);
|
|
2508
|
+
}
|
|
2509
|
+
const ctxCheck = this.contextManager.ensureContextFits(
|
|
2510
|
+
session2.messages,
|
|
2511
|
+
systemPrompt,
|
|
2512
|
+
tools,
|
|
2513
|
+
this.config.llm.model
|
|
2514
|
+
);
|
|
2515
|
+
if (ctxCheck.wasCompressed) {
|
|
2516
|
+
session2.messages = ctxCheck.messages;
|
|
2517
|
+
this.emit("context:compress", { sessionId, reason: "auto" });
|
|
2518
|
+
}
|
|
2519
|
+
const contextMessages = this.contextManager.buildWindow(
|
|
2520
|
+
session2.messages,
|
|
2521
|
+
systemPrompt,
|
|
2522
|
+
tools
|
|
2523
|
+
).messages;
|
|
2524
|
+
let llmResponse;
|
|
2525
|
+
try {
|
|
2526
|
+
llmResponse = await this.llmAdapter.chat(contextMessages, tools, {
|
|
2527
|
+
signal: controller.signal
|
|
2528
|
+
});
|
|
2529
|
+
} catch (err) {
|
|
2530
|
+
if (err.code === ACPErrorCodes.CONTEXT_OVERFLOW && !retried) {
|
|
2531
|
+
this.compressContext(sessionId, "hybrid");
|
|
2532
|
+
retried = true;
|
|
2533
|
+
turn--;
|
|
2534
|
+
continue;
|
|
2535
|
+
}
|
|
2536
|
+
throw new ACPError(ACPErrorCodes.LLM_CALL_FAILED, `LLM call failed: ${err.message}`, { turn });
|
|
2537
|
+
}
|
|
2538
|
+
if (llmResponse.usage) {
|
|
2539
|
+
totalInputTokens += llmResponse.usage.input;
|
|
2540
|
+
totalOutputTokens += llmResponse.usage.output;
|
|
2541
|
+
const estimated = estimateRequestTokens(contextMessages, tools, systemPrompt);
|
|
2542
|
+
if (estimated > 0 && llmResponse.usage.input > 0) {
|
|
2543
|
+
const ratio = llmResponse.usage.input / estimated;
|
|
2544
|
+
this.tokenCalibrationRatio = 0.3 * ratio + 0.7 * this.tokenCalibrationRatio;
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
if (!llmResponse.toolCalls?.length) {
|
|
2548
|
+
this.sessionManager.addMessage(sessionId, {
|
|
2549
|
+
role: "assistant",
|
|
2550
|
+
content: llmResponse.content
|
|
2551
|
+
});
|
|
2552
|
+
continueLoop = false;
|
|
2553
|
+
break;
|
|
2554
|
+
}
|
|
2555
|
+
this.sessionManager.addMessage(sessionId, {
|
|
2556
|
+
role: "assistant",
|
|
2557
|
+
content: llmResponse.content,
|
|
2558
|
+
toolCalls: llmResponse.toolCalls
|
|
2559
|
+
});
|
|
2560
|
+
const turnTrace = { turn, toolCalls: [] };
|
|
2561
|
+
const plan = this.planToolExecution(llmResponse.toolCalls, options ?? {}, requireApproval);
|
|
2562
|
+
await this.processApprovalQueue(plan.items, sessionId, (event, data) => this.emit(event, data));
|
|
2563
|
+
const batchTraces = await this.executeToolBatch(plan.items, sessionId, controller, plan.canParallelize, (event, data) => this.emit(event, data));
|
|
2564
|
+
turnTrace.toolCalls = batchTraces;
|
|
2565
|
+
const executableCount = plan.items.filter((i) => !i.resolved).length;
|
|
2566
|
+
turnTrace.parallel = plan.canParallelize && executableCount > 1;
|
|
2567
|
+
executionTrace.push(turnTrace);
|
|
2568
|
+
}
|
|
2569
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2570
|
+
const lastAssistant = [...session.messages].reverse().find((m) => m.role === "assistant" && !m.toolCalls?.length);
|
|
2571
|
+
const reply = typeof lastAssistant?.content === "string" ? lastAssistant.content : lastAssistant ? contentToString(lastAssistant.content) : "";
|
|
2572
|
+
const chatResult = { reply, sessionId, executionTrace, tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
2573
|
+
this.emit("chat:complete", { sessionId, reply, tokenUsage: chatResult.tokenUsage });
|
|
2574
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
2575
|
+
});
|
|
2576
|
+
return chatResult;
|
|
2577
|
+
} finally {
|
|
2578
|
+
this.abortControllers.delete(sessionId);
|
|
2579
|
+
}
|
|
2580
|
+
}
|
|
2581
|
+
async *chatStream(message, options) {
|
|
2582
|
+
this.ensureInitialized();
|
|
2583
|
+
if (options?.taskMode === "plan") {
|
|
2584
|
+
yield* this.chatStreamWithPlan(message, options);
|
|
2585
|
+
return;
|
|
2586
|
+
}
|
|
2587
|
+
if (options?.taskMode === "graph") {
|
|
2588
|
+
yield* this.chatStreamWithGraph(message, options);
|
|
2589
|
+
return;
|
|
2590
|
+
}
|
|
2591
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
2592
|
+
this.currentSessionId = sessionId;
|
|
2593
|
+
const maxTurns = options?.maxTurns ?? this.config.limits?.maxTurnsPerChat ?? 20;
|
|
2594
|
+
const requireApproval = new Set(options?.requireApproval ?? []);
|
|
2595
|
+
const controller = new AbortController();
|
|
2596
|
+
this.abortControllers.set(sessionId, controller);
|
|
2597
|
+
const startTime = Date.now();
|
|
2598
|
+
let totalInputTokens = 0;
|
|
2599
|
+
let totalOutputTokens = 0;
|
|
2600
|
+
let retried = false;
|
|
2601
|
+
try {
|
|
2602
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
2603
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
2604
|
+
let turn = 0;
|
|
2605
|
+
let continueLoop = true;
|
|
2606
|
+
while (continueLoop && turn < maxTurns) {
|
|
2607
|
+
turn++;
|
|
2608
|
+
const session2 = this.sessionManager.getOrThrow(sessionId);
|
|
2609
|
+
const systemPrompt = this.resolveSystemPrompt(sessionId, session2.systemPrompt ?? this.config.systemPrompt ?? "");
|
|
2610
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
2611
|
+
const tools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
2612
|
+
for (const name of this.computeAutoApproval(tools)) {
|
|
2613
|
+
requireApproval.add(name);
|
|
2614
|
+
}
|
|
2615
|
+
const ctxCheck = this.contextManager.ensureContextFits(session2.messages, systemPrompt, tools, this.config.llm.model);
|
|
2616
|
+
if (ctxCheck.wasCompressed) {
|
|
2617
|
+
session2.messages = ctxCheck.messages;
|
|
2618
|
+
this.emit("context:compress", { sessionId, reason: "auto" });
|
|
2619
|
+
}
|
|
2620
|
+
const contextMessages = this.contextManager.buildWindow(session2.messages, systemPrompt, tools).messages;
|
|
2621
|
+
let llmResponse;
|
|
2622
|
+
try {
|
|
2623
|
+
const useStreaming = typeof this.llmAdapter.chatStream === "function";
|
|
2624
|
+
if (useStreaming) {
|
|
2625
|
+
llmResponse = yield* this.streamLlmResponse(contextMessages, tools, controller.signal);
|
|
2626
|
+
} else {
|
|
2627
|
+
llmResponse = await this.llmAdapter.chat(contextMessages, tools, { signal: controller.signal });
|
|
2628
|
+
if (llmResponse.reasoning) {
|
|
2629
|
+
yield { type: "llm_thinking", content: llmResponse.reasoning };
|
|
2630
|
+
}
|
|
2631
|
+
if (llmResponse.content) {
|
|
2632
|
+
yield { type: "llm_text", content: llmResponse.content };
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
} catch (err) {
|
|
2636
|
+
if (err.code === ACPErrorCodes.CONTEXT_OVERFLOW && !retried) {
|
|
2637
|
+
this.compressContext(sessionId, "hybrid");
|
|
2638
|
+
retried = true;
|
|
2639
|
+
turn--;
|
|
2640
|
+
continue;
|
|
2641
|
+
}
|
|
2642
|
+
yield { type: "error", code: ACPErrorCodes.LLM_CALL_FAILED, message: err.message };
|
|
2643
|
+
return;
|
|
2644
|
+
}
|
|
2645
|
+
if (llmResponse.usage) {
|
|
2646
|
+
totalInputTokens += llmResponse.usage.input;
|
|
2647
|
+
totalOutputTokens += llmResponse.usage.output;
|
|
2648
|
+
const estimated = estimateRequestTokens(contextMessages, tools, systemPrompt);
|
|
2649
|
+
if (estimated > 0 && llmResponse.usage.input > 0) {
|
|
2650
|
+
const ratio = llmResponse.usage.input / estimated;
|
|
2651
|
+
this.tokenCalibrationRatio = 0.3 * ratio + 0.7 * this.tokenCalibrationRatio;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
if (!llmResponse.toolCalls?.length) {
|
|
2655
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: llmResponse.content });
|
|
2656
|
+
break;
|
|
2657
|
+
}
|
|
2658
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: llmResponse.content, toolCalls: llmResponse.toolCalls });
|
|
2659
|
+
const plan = this.planToolExecution(llmResponse.toolCalls, options ?? {}, requireApproval);
|
|
2660
|
+
const approvalEvents = [];
|
|
2661
|
+
const approvalYield = (evt) => approvalEvents.push(evt);
|
|
2662
|
+
await this.processApprovalQueue(plan.items, sessionId, (event, data) => this.emit(event, data), approvalYield);
|
|
2663
|
+
for (const evt of approvalEvents) yield evt;
|
|
2664
|
+
const batchEvents = [];
|
|
2665
|
+
const batchYield = (evt) => batchEvents.push(evt);
|
|
2666
|
+
await this.executeToolBatchStream(plan.items, sessionId, controller, plan.canParallelize, batchYield);
|
|
2667
|
+
for (const evt of batchEvents) yield evt;
|
|
2668
|
+
}
|
|
2669
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2670
|
+
const lastAssistant = [...session.messages].reverse().find((m) => m.role === "assistant" && !m.toolCalls?.length);
|
|
2671
|
+
yield { type: "done", reply: typeof lastAssistant?.content === "string" ? lastAssistant.content : lastAssistant ? contentToString(lastAssistant.content) : "", tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
2672
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
2673
|
+
});
|
|
2674
|
+
} finally {
|
|
2675
|
+
this.abortControllers.delete(sessionId);
|
|
2676
|
+
}
|
|
2677
|
+
}
|
|
2678
|
+
async abort(sessionId) {
|
|
2679
|
+
const sid = sessionId ?? this.currentSessionId;
|
|
2680
|
+
if (sid) {
|
|
2681
|
+
const controller = this.abortControllers.get(sid);
|
|
2682
|
+
if (controller) {
|
|
2683
|
+
controller.abort();
|
|
2684
|
+
this.abortControllers.delete(sid);
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
}
|
|
2688
|
+
// ---- Tool Approval ----
|
|
2689
|
+
approveTool(callId, approved, _reason) {
|
|
2690
|
+
const resolver = this.approvalResolvers.get(callId);
|
|
2691
|
+
if (resolver) {
|
|
2692
|
+
resolver.resolve(approved);
|
|
2693
|
+
this.approvalResolvers.delete(callId);
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
waitForApproval(callId) {
|
|
2697
|
+
return new Promise((resolve, reject) => {
|
|
2698
|
+
this.approvalResolvers.set(callId, { resolve, reject });
|
|
2699
|
+
setTimeout(() => {
|
|
2700
|
+
if (this.approvalResolvers.has(callId)) {
|
|
2701
|
+
this.approvalResolvers.delete(callId);
|
|
2702
|
+
resolve(false);
|
|
2703
|
+
}
|
|
2704
|
+
}, 6e4);
|
|
2705
|
+
});
|
|
2706
|
+
}
|
|
2707
|
+
// ---- Skill Management ----
|
|
2708
|
+
registerSkill(skill) {
|
|
2709
|
+
this.skillRegistry.register(skill);
|
|
2710
|
+
}
|
|
2711
|
+
unregisterSkill(name) {
|
|
2712
|
+
this.skillRegistry.unregister(name);
|
|
2713
|
+
}
|
|
2714
|
+
listSkills() {
|
|
2715
|
+
return this.skillRegistry.list();
|
|
2716
|
+
}
|
|
2717
|
+
useSkillPack(pack, config) {
|
|
2718
|
+
const runtime = this.config.runtime ?? detectRuntime();
|
|
2719
|
+
const packRuntime = pack.runtime ?? "both";
|
|
2720
|
+
if (packRuntime !== "both" && packRuntime !== runtime) {
|
|
2721
|
+
throw new ACPError(ACPErrorCodes.SKILL_REGISTRATION_FAILED, `SkillPack "${pack.name}" requires runtime "${packRuntime}" but current runtime is "${runtime}"`, { packName: pack.name, packRuntime, actualRuntime: runtime });
|
|
2722
|
+
}
|
|
2723
|
+
const env = { runtime, hasAgent: true };
|
|
2724
|
+
const result = pack.create(config ?? {}, env);
|
|
2725
|
+
const skillNames = [];
|
|
2726
|
+
for (const skill of result.skills) {
|
|
2727
|
+
skill._packName = pack.name;
|
|
2728
|
+
if (!skill.tier) {
|
|
2729
|
+
skill.tier = "extension";
|
|
2730
|
+
}
|
|
2731
|
+
if (!skill.workflow && skill._clawWorkflow) {
|
|
2732
|
+
skill.workflow = skill._clawWorkflow;
|
|
2733
|
+
}
|
|
2734
|
+
if (!skill.handler) {
|
|
2735
|
+
if (skill.agentLoop) {
|
|
2736
|
+
skill.handler = this.createAgentLoopHandler(skill);
|
|
2737
|
+
} else if (skill.workflow) {
|
|
2738
|
+
skill.handler = this.createWorkflowHandler(skill);
|
|
2739
|
+
} else if (skill.subgraph) {
|
|
2740
|
+
skill.handler = this.createSubgraphHandler(skill);
|
|
2741
|
+
}
|
|
2742
|
+
}
|
|
2743
|
+
this.skillRegistry.register(skill);
|
|
2744
|
+
skillNames.push(skill.name);
|
|
2745
|
+
}
|
|
2746
|
+
return { packName: pack.name, skills: skillNames, destroy: result.destroy };
|
|
2747
|
+
}
|
|
2748
|
+
unuseSkillPack(registration) {
|
|
2749
|
+
for (const skillName of registration.skills) {
|
|
2750
|
+
this.skillRegistry.unregister(skillName);
|
|
2751
|
+
}
|
|
2752
|
+
if (registration.destroy) {
|
|
2753
|
+
registration.destroy();
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
createAgentLoopHandler(skill) {
|
|
2757
|
+
const loop = skill.agentLoop;
|
|
2758
|
+
return async (params, ctx) => {
|
|
2759
|
+
let prompt;
|
|
2760
|
+
if (loop.instruction.includes("{{")) {
|
|
2761
|
+
prompt = interpolateInstruction(loop.instruction, params);
|
|
2762
|
+
} else if (Object.keys(params).length > 0) {
|
|
2763
|
+
prompt = `${loop.instruction}
|
|
2764
|
+
|
|
2765
|
+
Parameters:
|
|
2766
|
+
${JSON.stringify(params, null, 2)}`;
|
|
2767
|
+
} else {
|
|
2768
|
+
prompt = loop.instruction;
|
|
2769
|
+
}
|
|
2770
|
+
const result = await ctx.agent.chatInner(prompt, ctx.sessionId, { maxTurns: loop.maxTurns ?? 10, tools: loop.tools });
|
|
2771
|
+
return { content: [{ type: "text", text: result.reply }] };
|
|
2772
|
+
};
|
|
2773
|
+
}
|
|
2774
|
+
/** Internal chat for agentLoop/workflow/sub-agent execution. Condenses inner messages after completion. */
|
|
2775
|
+
async chatInner(prompt, sessionId, options) {
|
|
2776
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2777
|
+
const messageCountBefore = session.messages.length;
|
|
2778
|
+
const result = await this.chat(prompt, options);
|
|
2779
|
+
const sessionAfter = this.sessionManager.getOrThrow(sessionId);
|
|
2780
|
+
if (sessionAfter.messages.length > messageCountBefore + 2) {
|
|
2781
|
+
const innerMessages = sessionAfter.messages.splice(messageCountBefore);
|
|
2782
|
+
const lastAssistant = [...innerMessages].reverse().find((m) => m.role === "assistant" && !m.toolCalls?.length);
|
|
2783
|
+
if (lastAssistant) {
|
|
2784
|
+
sessionAfter.messages.push({ role: "assistant", content: `[Agent loop completed]: ${contentToPreview(lastAssistant.content, 200)}` });
|
|
2785
|
+
}
|
|
2786
|
+
}
|
|
2787
|
+
return result;
|
|
2788
|
+
}
|
|
2789
|
+
// ---- Task Plan Execution ----
|
|
2790
|
+
async chatWithPlan(message, options) {
|
|
2791
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
2792
|
+
this.currentSessionId = sessionId;
|
|
2793
|
+
const controller = new AbortController();
|
|
2794
|
+
this.abortControllers.set(sessionId, controller);
|
|
2795
|
+
const startTime = Date.now();
|
|
2796
|
+
let totalInputTokens = 0;
|
|
2797
|
+
let totalOutputTokens = 0;
|
|
2798
|
+
const executionTrace = [];
|
|
2799
|
+
try {
|
|
2800
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
2801
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
2802
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
2803
|
+
const filteredTools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
2804
|
+
const messageText = typeof message === "string" ? message : contentToString(message);
|
|
2805
|
+
let plan;
|
|
2806
|
+
try {
|
|
2807
|
+
const planner = new TaskPlanner(this.llmAdapter);
|
|
2808
|
+
plan = await planner.plan(messageText, filteredTools);
|
|
2809
|
+
} catch (err) {
|
|
2810
|
+
throw new ACPError(ACPErrorCodes.TASK_PLAN_FAILED, `Task planning failed: ${err.message}`);
|
|
2811
|
+
}
|
|
2812
|
+
const tracker = new PlanTracker(plan, sessionId, (event, data) => this.emit(event, data));
|
|
2813
|
+
tracker.startExecuting();
|
|
2814
|
+
this.emit("task:plan", { sessionId, plan });
|
|
2815
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2816
|
+
tracker.persistPlan(session);
|
|
2817
|
+
const maxRetry = options?.stepRetryCount ?? 1;
|
|
2818
|
+
const continueOnFailure = options?.continueOnStepFailure ?? true;
|
|
2819
|
+
for (let i = 0; i < plan.steps.length; i++) {
|
|
2820
|
+
if (controller.signal.aborted) break;
|
|
2821
|
+
const step = plan.steps[i];
|
|
2822
|
+
if (step.status === "done" || step.status === "skipped") continue;
|
|
2823
|
+
tracker.startStep(i);
|
|
2824
|
+
let stepResult;
|
|
2825
|
+
let succeeded = false;
|
|
2826
|
+
for (let attempt = 0; attempt <= maxRetry; attempt++) {
|
|
2827
|
+
try {
|
|
2828
|
+
const result = await this.chatInner(step.goal, sessionId, { maxTurns: options?.maxTurns ?? 10, tools: step.tools });
|
|
2829
|
+
stepResult = { output: result.reply, toolCalls: result.executionTrace.reduce((sum, t) => sum + t.toolCalls.length, 0), tokenUsage: result.tokenUsage, duration: result.totalDuration };
|
|
2830
|
+
totalInputTokens += result.tokenUsage.input;
|
|
2831
|
+
totalOutputTokens += result.tokenUsage.output;
|
|
2832
|
+
executionTrace.push(...result.executionTrace);
|
|
2833
|
+
succeeded = true;
|
|
2834
|
+
break;
|
|
2835
|
+
} catch (err) {
|
|
2836
|
+
stepResult = { output: "", toolCalls: 0, tokenUsage: { input: 0, output: 0 }, duration: 0, error: err.message };
|
|
2837
|
+
plan.steps[i].retryCount = attempt + 1;
|
|
2838
|
+
}
|
|
2839
|
+
}
|
|
2840
|
+
if (succeeded && stepResult) {
|
|
2841
|
+
tracker.completeStep(i, stepResult);
|
|
2842
|
+
} else if (stepResult) {
|
|
2843
|
+
tracker.failStep(i, stepResult);
|
|
2844
|
+
if (!continueOnFailure) {
|
|
2845
|
+
tracker.setPlanStatus("failed");
|
|
2846
|
+
break;
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
tracker.persistPlan(session);
|
|
2850
|
+
tracker.saveCheckpoint(session, i + 1);
|
|
2851
|
+
}
|
|
2852
|
+
const progress = tracker.getProgress();
|
|
2853
|
+
tracker.setPlanStatus(progress.percentage === 100 ? "completed" : "failed");
|
|
2854
|
+
tracker.persistPlan(session);
|
|
2855
|
+
PlanTracker.clearCheckpoint(session);
|
|
2856
|
+
const summaryLines = plan.steps.filter((s) => s.status === "done" && s.result).map((s) => `Step ${s.index + 1} (${s.goal}): ${s.result.output.slice(0, 150)}`);
|
|
2857
|
+
const finalReply = summaryLines.length > 0 ? `Task completed (${progress.current}/${progress.total} steps).
|
|
2858
|
+
|
|
2859
|
+
${summaryLines.join("\n")}` : "Task completed with no successful steps.";
|
|
2860
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
2861
|
+
const chatResult = { reply: finalReply, sessionId, executionTrace, tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
2862
|
+
this.emit("chat:complete", { sessionId, reply: finalReply, tokenUsage: chatResult.tokenUsage });
|
|
2863
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
2864
|
+
});
|
|
2865
|
+
return chatResult;
|
|
2866
|
+
} finally {
|
|
2867
|
+
this.abortControllers.delete(sessionId);
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
async *chatStreamWithPlan(message, options) {
|
|
2871
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
2872
|
+
this.currentSessionId = sessionId;
|
|
2873
|
+
const controller = new AbortController();
|
|
2874
|
+
this.abortControllers.set(sessionId, controller);
|
|
2875
|
+
const startTime = Date.now();
|
|
2876
|
+
let totalInputTokens = 0;
|
|
2877
|
+
let totalOutputTokens = 0;
|
|
2878
|
+
try {
|
|
2879
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
2880
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
2881
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
2882
|
+
const filteredTools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
2883
|
+
const messageText = typeof message === "string" ? message : contentToString(message);
|
|
2884
|
+
let plan;
|
|
2885
|
+
try {
|
|
2886
|
+
const planner = new TaskPlanner(this.llmAdapter);
|
|
2887
|
+
plan = await planner.plan(messageText, filteredTools);
|
|
2888
|
+
} catch (err) {
|
|
2889
|
+
yield { type: "error", code: ACPErrorCodes.TASK_PLAN_FAILED, message: `Task planning failed: ${err.message}` };
|
|
2890
|
+
return;
|
|
2891
|
+
}
|
|
2892
|
+
const tracker = new PlanTracker(plan, sessionId, () => {
|
|
2893
|
+
});
|
|
2894
|
+
tracker.startExecuting();
|
|
2895
|
+
yield { type: "task:plan", plan };
|
|
2896
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2897
|
+
tracker.persistPlan(session);
|
|
2898
|
+
const maxRetry = options?.stepRetryCount ?? 1;
|
|
2899
|
+
const continueOnFailure = options?.continueOnStepFailure ?? true;
|
|
2900
|
+
for (let i = 0; i < plan.steps.length; i++) {
|
|
2901
|
+
if (controller.signal.aborted) break;
|
|
2902
|
+
const step = plan.steps[i];
|
|
2903
|
+
if (step.status === "done" || step.status === "skipped") continue;
|
|
2904
|
+
tracker.startStep(i);
|
|
2905
|
+
yield { type: "task:step_start", step: plan.steps[i], progress: tracker.getProgress() };
|
|
2906
|
+
let stepResult;
|
|
2907
|
+
let succeeded = false;
|
|
2908
|
+
for (let attempt = 0; attempt <= maxRetry; attempt++) {
|
|
2909
|
+
try {
|
|
2910
|
+
const result = await this.chatInner(step.goal, sessionId, { maxTurns: options?.maxTurns ?? 10, tools: step.tools });
|
|
2911
|
+
stepResult = { output: result.reply, toolCalls: result.executionTrace.reduce((sum, t) => sum + t.toolCalls.length, 0), tokenUsage: result.tokenUsage, duration: result.totalDuration };
|
|
2912
|
+
totalInputTokens += result.tokenUsage.input;
|
|
2913
|
+
totalOutputTokens += result.tokenUsage.output;
|
|
2914
|
+
succeeded = true;
|
|
2915
|
+
break;
|
|
2916
|
+
} catch (err) {
|
|
2917
|
+
stepResult = { output: "", toolCalls: 0, tokenUsage: { input: 0, output: 0 }, duration: 0, error: err.message };
|
|
2918
|
+
plan.steps[i].retryCount = attempt + 1;
|
|
2919
|
+
}
|
|
2920
|
+
}
|
|
2921
|
+
if (succeeded && stepResult) {
|
|
2922
|
+
tracker.completeStep(i, stepResult);
|
|
2923
|
+
yield { type: "task:step_complete", step: plan.steps[i], progress: tracker.getProgress() };
|
|
2924
|
+
} else if (stepResult) {
|
|
2925
|
+
tracker.failStep(i, stepResult);
|
|
2926
|
+
yield { type: "task:step_failed", step: plan.steps[i], progress: tracker.getProgress() };
|
|
2927
|
+
if (!continueOnFailure) {
|
|
2928
|
+
tracker.setPlanStatus("failed");
|
|
2929
|
+
break;
|
|
2930
|
+
}
|
|
2931
|
+
}
|
|
2932
|
+
tracker.persistPlan(session);
|
|
2933
|
+
tracker.saveCheckpoint(session, i + 1);
|
|
2934
|
+
}
|
|
2935
|
+
const progress = tracker.getProgress();
|
|
2936
|
+
tracker.setPlanStatus(progress.percentage === 100 ? "completed" : "failed");
|
|
2937
|
+
tracker.persistPlan(session);
|
|
2938
|
+
PlanTracker.clearCheckpoint(session);
|
|
2939
|
+
const summaryLines = plan.steps.filter((s) => s.status === "done" && s.result).map((s) => `Step ${s.index + 1} (${s.goal}): ${s.result.output.slice(0, 150)}`);
|
|
2940
|
+
const finalReply = summaryLines.length > 0 ? `Task completed (${progress.current}/${progress.total} steps).
|
|
2941
|
+
|
|
2942
|
+
${summaryLines.join("\n")}` : "Task completed with no successful steps.";
|
|
2943
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
2944
|
+
yield { type: "done", reply: finalReply, tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
2945
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
2946
|
+
});
|
|
2947
|
+
} finally {
|
|
2948
|
+
this.abortControllers.delete(sessionId);
|
|
2949
|
+
}
|
|
2950
|
+
}
|
|
2951
|
+
async resumeTask(sessionId, options) {
|
|
2952
|
+
this.ensureInitialized();
|
|
2953
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
2954
|
+
const savedPlan = PlanTracker.loadPlan(session);
|
|
2955
|
+
if (!savedPlan) {
|
|
2956
|
+
throw new ACPError(ACPErrorCodes.TASK_PLAN_FAILED, "No task plan found in session");
|
|
2957
|
+
}
|
|
2958
|
+
for (const step of savedPlan.steps) {
|
|
2959
|
+
if (step.status === "failed") {
|
|
2960
|
+
step.status = "pending";
|
|
2961
|
+
step.retryCount = 0;
|
|
2962
|
+
step.result = void 0;
|
|
2963
|
+
}
|
|
2964
|
+
}
|
|
2965
|
+
const controller = new AbortController();
|
|
2966
|
+
this.abortControllers.set(sessionId, controller);
|
|
2967
|
+
const startTime = Date.now();
|
|
2968
|
+
let totalInputTokens = 0;
|
|
2969
|
+
let totalOutputTokens = 0;
|
|
2970
|
+
const executionTrace = [];
|
|
2971
|
+
try {
|
|
2972
|
+
const tracker = new PlanTracker(savedPlan, sessionId, (event, data) => this.emit(event, data));
|
|
2973
|
+
tracker.startExecuting();
|
|
2974
|
+
const maxRetry = options?.stepRetryCount ?? 1;
|
|
2975
|
+
const continueOnFailure = options?.continueOnStepFailure ?? true;
|
|
2976
|
+
for (let i = 0; i < savedPlan.steps.length; i++) {
|
|
2977
|
+
if (controller.signal.aborted) break;
|
|
2978
|
+
const step = savedPlan.steps[i];
|
|
2979
|
+
if (step.status === "done" || step.status === "skipped") continue;
|
|
2980
|
+
tracker.startStep(i);
|
|
2981
|
+
let stepResult;
|
|
2982
|
+
let succeeded = false;
|
|
2983
|
+
for (let attempt = 0; attempt <= maxRetry; attempt++) {
|
|
2984
|
+
try {
|
|
2985
|
+
const result = await this.chatInner(step.goal, sessionId, { maxTurns: options?.maxTurns ?? 10, tools: step.tools });
|
|
2986
|
+
stepResult = { output: result.reply, toolCalls: result.executionTrace.reduce((sum, t) => sum + t.toolCalls.length, 0), tokenUsage: result.tokenUsage, duration: result.totalDuration };
|
|
2987
|
+
totalInputTokens += result.tokenUsage.input;
|
|
2988
|
+
totalOutputTokens += result.tokenUsage.output;
|
|
2989
|
+
executionTrace.push(...result.executionTrace);
|
|
2990
|
+
succeeded = true;
|
|
2991
|
+
break;
|
|
2992
|
+
} catch (err) {
|
|
2993
|
+
stepResult = { output: "", toolCalls: 0, tokenUsage: { input: 0, output: 0 }, duration: 0, error: err.message };
|
|
2994
|
+
savedPlan.steps[i].retryCount = attempt + 1;
|
|
2995
|
+
}
|
|
2996
|
+
}
|
|
2997
|
+
if (succeeded && stepResult) {
|
|
2998
|
+
tracker.completeStep(i, stepResult);
|
|
2999
|
+
} else if (stepResult) {
|
|
3000
|
+
tracker.failStep(i, stepResult);
|
|
3001
|
+
if (!continueOnFailure) {
|
|
3002
|
+
tracker.setPlanStatus("failed");
|
|
3003
|
+
break;
|
|
3004
|
+
}
|
|
3005
|
+
}
|
|
3006
|
+
tracker.persistPlan(session);
|
|
3007
|
+
tracker.saveCheckpoint(session, i + 1);
|
|
3008
|
+
}
|
|
3009
|
+
const progress = tracker.getProgress();
|
|
3010
|
+
tracker.setPlanStatus(progress.percentage === 100 ? "completed" : "failed");
|
|
3011
|
+
tracker.persistPlan(session);
|
|
3012
|
+
PlanTracker.clearCheckpoint(session);
|
|
3013
|
+
const summaryLines = savedPlan.steps.filter((s) => s.status === "done" && s.result).map((s) => `Step ${s.index + 1} (${s.goal}): ${s.result.output.slice(0, 150)}`);
|
|
3014
|
+
const finalReply = summaryLines.length > 0 ? `Task resumed & completed (${progress.current}/${progress.total} steps).
|
|
3015
|
+
|
|
3016
|
+
${summaryLines.join("\n")}` : "Task resumed but no steps completed successfully.";
|
|
3017
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
3018
|
+
const chatResult = { reply: finalReply, sessionId, executionTrace, tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
3019
|
+
this.emit("chat:complete", { sessionId, reply: finalReply, tokenUsage: chatResult.tokenUsage });
|
|
3020
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
3021
|
+
});
|
|
3022
|
+
return chatResult;
|
|
3023
|
+
} finally {
|
|
3024
|
+
this.abortControllers.delete(sessionId);
|
|
3025
|
+
}
|
|
3026
|
+
}
|
|
3027
|
+
getTaskPlan(sessionId) {
|
|
3028
|
+
const session = this.sessionManager.get(sessionId);
|
|
3029
|
+
if (!session) return null;
|
|
3030
|
+
return PlanTracker.loadPlan(session);
|
|
3031
|
+
}
|
|
3032
|
+
/** Get current session ID (used by SubAgent for parent reference) */
|
|
3033
|
+
getCurrentSessionId() {
|
|
3034
|
+
return this.currentSessionId;
|
|
3035
|
+
}
|
|
3036
|
+
// ---- Graph Execution (Sub-Agent Orchestration) ----
|
|
3037
|
+
async chatWithGraph(message, options) {
|
|
3038
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
3039
|
+
this.currentSessionId = sessionId;
|
|
3040
|
+
const controller = new AbortController();
|
|
3041
|
+
this.abortControllers.set(sessionId, controller);
|
|
3042
|
+
const startTime = Date.now();
|
|
3043
|
+
try {
|
|
3044
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
3045
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
3046
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
3047
|
+
const filteredTools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
3048
|
+
const messageText = typeof message === "string" ? message : contentToString(message);
|
|
3049
|
+
let plan;
|
|
3050
|
+
try {
|
|
3051
|
+
const planner = new GraphPlanner(this.llmAdapter);
|
|
3052
|
+
plan = await planner.planGraph(messageText, filteredTools);
|
|
3053
|
+
} catch (err) {
|
|
3054
|
+
throw new ACPError(ACPErrorCodes.GRAPH_PLAN_FAILED, `Graph planning failed: ${err.message}`);
|
|
3055
|
+
}
|
|
3056
|
+
const graph = new TaskGraph(plan.nodes);
|
|
3057
|
+
const validation = graph.validate();
|
|
3058
|
+
if (!validation.valid) {
|
|
3059
|
+
throw new ACPError(ACPErrorCodes.GRAPH_CYCLE_DETECTED, `Invalid graph: ${validation.errors.join(", ")}`);
|
|
3060
|
+
}
|
|
3061
|
+
plan.levels = graph.computeLevels();
|
|
3062
|
+
plan.status = "executing";
|
|
3063
|
+
this.emit("graph:plan", { sessionId, plan });
|
|
3064
|
+
const executor = new GraphExecutor({
|
|
3065
|
+
graph,
|
|
3066
|
+
parentAgent: this,
|
|
3067
|
+
plan,
|
|
3068
|
+
maxConcurrency: options?.graphConfig?.maxConcurrency ?? 3,
|
|
3069
|
+
maxDepth: options?.graphConfig?.maxDepth ?? 2,
|
|
3070
|
+
baseDepth: options?.depth ?? 0,
|
|
3071
|
+
emit: (event, data) => this.emit(event, data)
|
|
3072
|
+
});
|
|
3073
|
+
const finalPlan = await executor.execute();
|
|
3074
|
+
const resultLines = Object.entries(finalPlan.results).filter(([, r]) => r.status === "done" && r.output).map(([nodeId, r]) => `[${nodeId}] ${r.output.slice(0, 200)}`);
|
|
3075
|
+
const progress = executor.getProgress();
|
|
3076
|
+
const finalReply = resultLines.length > 0 ? `Graph task completed (${progress.done}/${progress.total} nodes done, ${progress.failed} failed, ${progress.bypassed} bypassed).
|
|
3077
|
+
|
|
3078
|
+
${resultLines.join("\n")}` : "Graph task completed with no successful nodes.";
|
|
3079
|
+
const totalTokenUsage = finalPlan.totalTokenUsage;
|
|
3080
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
3081
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
3082
|
+
session.meta = session.meta ?? {};
|
|
3083
|
+
session.meta.graphPlan = finalPlan;
|
|
3084
|
+
const chatResult = {
|
|
3085
|
+
reply: finalReply,
|
|
3086
|
+
sessionId,
|
|
3087
|
+
executionTrace: [],
|
|
3088
|
+
tokenUsage: totalTokenUsage,
|
|
3089
|
+
totalDuration: Date.now() - startTime
|
|
3090
|
+
};
|
|
3091
|
+
this.emit("chat:complete", { sessionId, reply: finalReply, tokenUsage: chatResult.tokenUsage });
|
|
3092
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
3093
|
+
});
|
|
3094
|
+
return chatResult;
|
|
3095
|
+
} finally {
|
|
3096
|
+
this.abortControllers.delete(sessionId);
|
|
3097
|
+
}
|
|
3098
|
+
}
|
|
3099
|
+
async *chatStreamWithGraph(message, options) {
|
|
3100
|
+
const sessionId = options?.sessionId ?? this.currentSessionId ?? this.ensureSession().id;
|
|
3101
|
+
this.currentSessionId = sessionId;
|
|
3102
|
+
const controller = new AbortController();
|
|
3103
|
+
this.abortControllers.set(sessionId, controller);
|
|
3104
|
+
const startTime = Date.now();
|
|
3105
|
+
let totalInputTokens = 0;
|
|
3106
|
+
let totalOutputTokens = 0;
|
|
3107
|
+
try {
|
|
3108
|
+
const userContent = this.buildUserContent(message, options?.attachments);
|
|
3109
|
+
this.sessionManager.addMessage(sessionId, { role: "user", content: userContent });
|
|
3110
|
+
const allTools = this.skillRegistry.listToolDefs();
|
|
3111
|
+
const filteredTools = this.resolveTools(allTools, { allowedTools: options?.tools, toolsByPermission: options?.toolsByPermission });
|
|
3112
|
+
const messageText = typeof message === "string" ? message : contentToString(message);
|
|
3113
|
+
let plan;
|
|
3114
|
+
try {
|
|
3115
|
+
const planner = new GraphPlanner(this.llmAdapter);
|
|
3116
|
+
plan = await planner.planGraph(messageText, filteredTools);
|
|
3117
|
+
} catch (err) {
|
|
3118
|
+
yield { type: "error", code: ACPErrorCodes.GRAPH_PLAN_FAILED, message: `Graph planning failed: ${err.message}` };
|
|
3119
|
+
return;
|
|
3120
|
+
}
|
|
3121
|
+
const graph = new TaskGraph(plan.nodes);
|
|
3122
|
+
const validation = graph.validate();
|
|
3123
|
+
if (!validation.valid) {
|
|
3124
|
+
yield { type: "error", code: ACPErrorCodes.GRAPH_CYCLE_DETECTED, message: `Invalid graph: ${validation.errors.join(", ")}` };
|
|
3125
|
+
return;
|
|
3126
|
+
}
|
|
3127
|
+
plan.levels = graph.computeLevels();
|
|
3128
|
+
plan.status = "executing";
|
|
3129
|
+
yield { type: "graph:plan", plan };
|
|
3130
|
+
const executor = new GraphExecutor({
|
|
3131
|
+
graph,
|
|
3132
|
+
parentAgent: this,
|
|
3133
|
+
plan,
|
|
3134
|
+
maxConcurrency: options?.graphConfig?.maxConcurrency ?? 3,
|
|
3135
|
+
maxDepth: options?.graphConfig?.maxDepth ?? 2,
|
|
3136
|
+
baseDepth: options?.depth ?? 0,
|
|
3137
|
+
emit: (event, data) => {
|
|
3138
|
+
if (event.startsWith("subagent:") || event.startsWith("graph:")) {
|
|
3139
|
+
this.emit(event, data);
|
|
3140
|
+
}
|
|
3141
|
+
}
|
|
3142
|
+
});
|
|
3143
|
+
const finalPlan = await executor.execute();
|
|
3144
|
+
const progress = executor.getProgress();
|
|
3145
|
+
const resultLines = Object.entries(finalPlan.results).filter(([, r]) => r.status === "done" && r.output).map(([nodeId, r]) => `[${nodeId}] ${r.output.slice(0, 200)}`);
|
|
3146
|
+
const finalReply = resultLines.length > 0 ? `Graph task completed (${progress.done}/${progress.total} nodes done, ${progress.failed} failed, ${progress.bypassed} bypassed).
|
|
3147
|
+
|
|
3148
|
+
${resultLines.join("\n")}` : "Graph task completed with no successful nodes.";
|
|
3149
|
+
totalInputTokens = finalPlan.totalTokenUsage.input;
|
|
3150
|
+
totalOutputTokens = finalPlan.totalTokenUsage.output;
|
|
3151
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
3152
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
3153
|
+
session.meta = session.meta ?? {};
|
|
3154
|
+
session.meta.graphPlan = finalPlan;
|
|
3155
|
+
yield { type: "done", reply: finalReply, tokenUsage: { input: totalInputTokens, output: totalOutputTokens }, totalDuration: Date.now() - startTime };
|
|
3156
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
3157
|
+
});
|
|
3158
|
+
} finally {
|
|
3159
|
+
this.abortControllers.delete(sessionId);
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
/** Resume a graph execution from checkpoint */
|
|
3163
|
+
async resumeGraph(sessionId, options) {
|
|
3164
|
+
this.ensureInitialized();
|
|
3165
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
3166
|
+
const savedPlan = session.meta?.graphPlan ?? null;
|
|
3167
|
+
if (!savedPlan) {
|
|
3168
|
+
throw new ACPError(ACPErrorCodes.GRAPH_PLAN_FAILED, "No graph plan found in session");
|
|
3169
|
+
}
|
|
3170
|
+
for (const [nodeId, result] of Object.entries(savedPlan.results)) {
|
|
3171
|
+
if (result.status === "failed" || result.status === "bypassed") {
|
|
3172
|
+
savedPlan.results[nodeId] = {
|
|
3173
|
+
nodeId,
|
|
3174
|
+
status: "pending",
|
|
3175
|
+
tokenUsage: { input: 0, output: 0 },
|
|
3176
|
+
duration: 0,
|
|
3177
|
+
retryCount: 0
|
|
3178
|
+
};
|
|
3179
|
+
}
|
|
3180
|
+
}
|
|
3181
|
+
savedPlan.status = "executing";
|
|
3182
|
+
const controller = new AbortController();
|
|
3183
|
+
this.abortControllers.set(sessionId, controller);
|
|
3184
|
+
const startTime = Date.now();
|
|
3185
|
+
try {
|
|
3186
|
+
const graph = new TaskGraph(savedPlan.nodes);
|
|
3187
|
+
const executor = new GraphExecutor({
|
|
3188
|
+
graph,
|
|
3189
|
+
parentAgent: this,
|
|
3190
|
+
plan: savedPlan,
|
|
3191
|
+
maxConcurrency: options?.graphConfig?.maxConcurrency ?? 3,
|
|
3192
|
+
maxDepth: options?.graphConfig?.maxDepth ?? 2,
|
|
3193
|
+
baseDepth: options?.depth ?? 0,
|
|
3194
|
+
emit: (event, data) => this.emit(event, data)
|
|
3195
|
+
});
|
|
3196
|
+
const finalPlan = await executor.execute();
|
|
3197
|
+
const resultLines = Object.entries(finalPlan.results).filter(([, r]) => r.status === "done" && r.output).map(([nodeId, r]) => `[${nodeId}] ${r.output.slice(0, 200)}`);
|
|
3198
|
+
const progress = executor.getProgress();
|
|
3199
|
+
const finalReply = resultLines.length > 0 ? `Graph resumed & completed (${progress.done}/${progress.total} nodes done).
|
|
3200
|
+
|
|
3201
|
+
${resultLines.join("\n")}` : "Graph resumed but no nodes completed successfully.";
|
|
3202
|
+
this.sessionManager.addMessage(sessionId, { role: "assistant", content: finalReply });
|
|
3203
|
+
session.meta = session.meta ?? {};
|
|
3204
|
+
session.meta.graphPlan = finalPlan;
|
|
3205
|
+
const chatResult = {
|
|
3206
|
+
reply: finalReply,
|
|
3207
|
+
sessionId,
|
|
3208
|
+
executionTrace: [],
|
|
3209
|
+
tokenUsage: finalPlan.totalTokenUsage,
|
|
3210
|
+
totalDuration: Date.now() - startTime
|
|
3211
|
+
};
|
|
3212
|
+
this.emit("chat:complete", { sessionId, reply: finalReply, tokenUsage: chatResult.tokenUsage });
|
|
3213
|
+
await this.persistence.saveSession(session).catch(() => {
|
|
3214
|
+
});
|
|
3215
|
+
return chatResult;
|
|
3216
|
+
} finally {
|
|
3217
|
+
this.abortControllers.delete(sessionId);
|
|
3218
|
+
}
|
|
3219
|
+
}
|
|
3220
|
+
/** Get graph plan from session */
|
|
3221
|
+
getGraphPlan(sessionId) {
|
|
3222
|
+
const session = this.sessionManager.get(sessionId);
|
|
3223
|
+
if (!session) return null;
|
|
3224
|
+
return session.meta?.graphPlan ?? null;
|
|
3225
|
+
}
|
|
3226
|
+
createWorkflowHandler(skill) {
|
|
3227
|
+
const workflow = skill.workflow ?? skill._clawWorkflow;
|
|
3228
|
+
const hasDag = workflow.steps.some((s) => s.dependsOn != null);
|
|
3229
|
+
if (hasDag) {
|
|
3230
|
+
return this.createDagWorkflowHandler(skill);
|
|
3231
|
+
}
|
|
3232
|
+
return async (params, ctx) => {
|
|
3233
|
+
const stepOutputs = {};
|
|
3234
|
+
const completedSteps = [];
|
|
3235
|
+
const failedSteps = [];
|
|
3236
|
+
const total = workflow.steps.length;
|
|
3237
|
+
for (let i = 0; i < workflow.steps.length; i++) {
|
|
3238
|
+
const step = workflow.steps[i];
|
|
3239
|
+
const interpolatedPrompt = interpolateTemplate(step.prompt, {
|
|
3240
|
+
inputs: params,
|
|
3241
|
+
steps: stepOutputs
|
|
3242
|
+
});
|
|
3243
|
+
const progress = {
|
|
3244
|
+
current: i,
|
|
3245
|
+
total,
|
|
3246
|
+
percentage: Math.round(i / total * 100),
|
|
3247
|
+
completedSteps: [...completedSteps],
|
|
3248
|
+
failedSteps: [...failedSteps]
|
|
3249
|
+
};
|
|
3250
|
+
this.emit("workflow:step_start", { step, stepIndex: i, progress });
|
|
3251
|
+
try {
|
|
3252
|
+
const result = await ctx.agent.chatInner(interpolatedPrompt, ctx.sessionId, {
|
|
3253
|
+
maxTurns: step.maxTurns ?? 10,
|
|
3254
|
+
tools: step.tools
|
|
3255
|
+
});
|
|
3256
|
+
stepOutputs[step.name] = { output: result.reply };
|
|
3257
|
+
completedSteps.push(step.name);
|
|
3258
|
+
const completeProgress = {
|
|
3259
|
+
current: i + 1,
|
|
3260
|
+
total,
|
|
3261
|
+
percentage: Math.round((i + 1) / total * 100),
|
|
3262
|
+
completedSteps: [...completedSteps],
|
|
3263
|
+
failedSteps: [...failedSteps]
|
|
3264
|
+
};
|
|
3265
|
+
this.emit("workflow:step_complete", {
|
|
3266
|
+
step,
|
|
3267
|
+
stepIndex: i,
|
|
3268
|
+
output: result.reply,
|
|
3269
|
+
progress: completeProgress
|
|
3270
|
+
});
|
|
3271
|
+
} catch (err) {
|
|
3272
|
+
failedSteps.push(step.name);
|
|
3273
|
+
const failProgress = {
|
|
3274
|
+
current: i + 1,
|
|
3275
|
+
total,
|
|
3276
|
+
percentage: Math.round((i + 1) / total * 100),
|
|
3277
|
+
completedSteps: [...completedSteps],
|
|
3278
|
+
failedSteps: [...failedSteps]
|
|
3279
|
+
};
|
|
3280
|
+
this.emit("workflow:step_failed", {
|
|
3281
|
+
step,
|
|
3282
|
+
stepIndex: i,
|
|
3283
|
+
error: err.message,
|
|
3284
|
+
progress: failProgress
|
|
3285
|
+
});
|
|
3286
|
+
return {
|
|
3287
|
+
content: [{ type: "text", text: `Workflow failed at step "${step.name}": ${err.message}` }],
|
|
3288
|
+
isError: true
|
|
3289
|
+
};
|
|
3290
|
+
}
|
|
3291
|
+
}
|
|
3292
|
+
const summaryLines = Object.entries(stepOutputs).map(
|
|
3293
|
+
([name, data]) => `[${name}] ${data.output.slice(0, 200)}`
|
|
3294
|
+
);
|
|
3295
|
+
return { content: [{ type: "text", text: summaryLines.join("\n") }] };
|
|
3296
|
+
};
|
|
3297
|
+
}
|
|
3298
|
+
/** Create DAG workflow handler — steps with dependsOn are executed via GraphExecutor */
|
|
3299
|
+
createDagWorkflowHandler(skill) {
|
|
3300
|
+
const workflow = skill.workflow ?? skill._clawWorkflow;
|
|
3301
|
+
return async (params, ctx) => {
|
|
3302
|
+
const nodes = workflow.steps.map((step, _i) => ({
|
|
3303
|
+
id: step.name,
|
|
3304
|
+
goal: step.prompt,
|
|
3305
|
+
dependsOn: step.dependsOn ?? [],
|
|
3306
|
+
triggerRule: step.triggerRule,
|
|
3307
|
+
agent: step.agent ?? {
|
|
3308
|
+
tools: step.tools,
|
|
3309
|
+
maxTurns: step.maxTurns ?? 10,
|
|
3310
|
+
canSpawnSubAgents: false
|
|
3311
|
+
},
|
|
3312
|
+
retry: step.retry,
|
|
3313
|
+
fallback: step.fallback
|
|
3314
|
+
}));
|
|
3315
|
+
const graph = new TaskGraph(nodes);
|
|
3316
|
+
const validation = graph.validate();
|
|
3317
|
+
if (!validation.valid) {
|
|
3318
|
+
return {
|
|
3319
|
+
content: [{ type: "text", text: `DAG validation failed: ${validation.errors.join(", ")}` }],
|
|
3320
|
+
isError: true
|
|
3321
|
+
};
|
|
3322
|
+
}
|
|
3323
|
+
const levels = graph.computeLevels();
|
|
3324
|
+
const now = Date.now();
|
|
3325
|
+
const plan = {
|
|
3326
|
+
id: `graph-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
3327
|
+
goal: skill.description,
|
|
3328
|
+
nodes,
|
|
3329
|
+
levels,
|
|
3330
|
+
status: "planning",
|
|
3331
|
+
results: {},
|
|
3332
|
+
createdAt: now,
|
|
3333
|
+
updatedAt: now,
|
|
3334
|
+
totalTokenUsage: { input: 0, output: 0 }
|
|
3335
|
+
};
|
|
3336
|
+
const executor = new GraphExecutor({
|
|
3337
|
+
graph,
|
|
3338
|
+
parentAgent: this,
|
|
3339
|
+
plan,
|
|
3340
|
+
maxConcurrency: 3,
|
|
3341
|
+
maxDepth: 2,
|
|
3342
|
+
baseDepth: ctx.depth ?? 0,
|
|
3343
|
+
emit: (event, data) => this.emit(event, data)
|
|
3344
|
+
});
|
|
3345
|
+
const finalPlan = await executor.execute();
|
|
3346
|
+
const aggregation = skill.subgraph?.aggregation ?? "concat";
|
|
3347
|
+
if (aggregation === "last") {
|
|
3348
|
+
const lastDone = Object.values(finalPlan.results).reverse().find((r) => r.status === "done" && r.output);
|
|
3349
|
+
return { content: [{ type: "text", text: lastDone?.output ?? "" }] };
|
|
3350
|
+
}
|
|
3351
|
+
const lines = Object.entries(finalPlan.results).filter(([, r]) => r.status === "done" && r.output).map(([nodeId, r]) => `[${nodeId}] ${r.output.slice(0, 200)}`);
|
|
3352
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
3353
|
+
};
|
|
3354
|
+
}
|
|
3355
|
+
/** Create subgraph handler for SkillDefinition.subgraph */
|
|
3356
|
+
createSubgraphHandler(skill) {
|
|
3357
|
+
const subgraphDef = skill.subgraph;
|
|
3358
|
+
return async (params, ctx) => {
|
|
3359
|
+
const nodes = subgraphDef.nodes;
|
|
3360
|
+
const graph = new TaskGraph(nodes);
|
|
3361
|
+
const validation = graph.validate();
|
|
3362
|
+
if (!validation.valid) {
|
|
3363
|
+
return {
|
|
3364
|
+
content: [{ type: "text", text: `Subgraph validation failed: ${validation.errors.join(", ")}` }],
|
|
3365
|
+
isError: true
|
|
3366
|
+
};
|
|
3367
|
+
}
|
|
3368
|
+
const levels = graph.computeLevels();
|
|
3369
|
+
const now = Date.now();
|
|
3370
|
+
const plan = {
|
|
3371
|
+
id: `subgraph-${now}-${Math.random().toString(36).slice(2, 8)}`,
|
|
3372
|
+
goal: skill.description,
|
|
3373
|
+
nodes,
|
|
3374
|
+
levels,
|
|
3375
|
+
status: "planning",
|
|
3376
|
+
results: {},
|
|
3377
|
+
createdAt: now,
|
|
3378
|
+
updatedAt: now,
|
|
3379
|
+
totalTokenUsage: { input: 0, output: 0 }
|
|
3380
|
+
};
|
|
3381
|
+
const executor = new GraphExecutor({
|
|
3382
|
+
graph,
|
|
3383
|
+
parentAgent: this,
|
|
3384
|
+
plan,
|
|
3385
|
+
maxConcurrency: 3,
|
|
3386
|
+
maxDepth: 2,
|
|
3387
|
+
baseDepth: ctx.depth ?? 0,
|
|
3388
|
+
emit: (event, data) => this.emit(event, data)
|
|
3389
|
+
});
|
|
3390
|
+
const finalPlan = await executor.execute();
|
|
3391
|
+
const aggregation = subgraphDef.aggregation ?? "concat";
|
|
3392
|
+
if (aggregation === "last") {
|
|
3393
|
+
const lastDone = Object.values(finalPlan.results).reverse().find((r) => r.status === "done" && r.output);
|
|
3394
|
+
return { content: [{ type: "text", text: lastDone?.output ?? "" }] };
|
|
3395
|
+
}
|
|
3396
|
+
const lines = Object.entries(finalPlan.results).filter(([, r]) => r.status === "done" && r.output).map(([nodeId, r]) => `[${nodeId}] ${r.output.slice(0, 200)}`);
|
|
3397
|
+
return { content: [{ type: "text", text: lines.join("\n") }] };
|
|
3398
|
+
};
|
|
3399
|
+
}
|
|
3400
|
+
async installSkill(_source, _name, _options) {
|
|
3401
|
+
throw new ACPError(ACPErrorCodes.SKILL_REGISTRATION_FAILED, "Skill installation not yet implemented");
|
|
3402
|
+
}
|
|
3403
|
+
async uninstallSkill(_name) {
|
|
3404
|
+
throw new ACPError(ACPErrorCodes.SKILL_REGISTRATION_FAILED, "Skill uninstallation not yet implemented");
|
|
3405
|
+
}
|
|
3406
|
+
// ---- Session Management ----
|
|
3407
|
+
createSession(options) {
|
|
3408
|
+
const session = this.sessionManager.create(options);
|
|
3409
|
+
this.currentSessionId = session.id;
|
|
3410
|
+
return session;
|
|
3411
|
+
}
|
|
3412
|
+
getSession(sessionId) {
|
|
3413
|
+
return this.sessionManager.get(sessionId);
|
|
3414
|
+
}
|
|
3415
|
+
listSessions(options) {
|
|
3416
|
+
return this.sessionManager.list(options);
|
|
3417
|
+
}
|
|
3418
|
+
searchSessions(query, options) {
|
|
3419
|
+
return this.sessionManager.search(query, options);
|
|
3420
|
+
}
|
|
3421
|
+
mergeSessions(fromId, toId, strategy) {
|
|
3422
|
+
this.sessionManager.merge(fromId, toId, strategy);
|
|
3423
|
+
}
|
|
3424
|
+
deleteSession(sessionId) {
|
|
3425
|
+
this.sessionManager.delete(sessionId);
|
|
3426
|
+
if (this.currentSessionId === sessionId) {
|
|
3427
|
+
this.currentSessionId = null;
|
|
3428
|
+
}
|
|
3429
|
+
}
|
|
3430
|
+
archiveSession(sessionId) {
|
|
3431
|
+
this.sessionManager.archive(sessionId);
|
|
3432
|
+
}
|
|
3433
|
+
// ---- Context Management ----
|
|
3434
|
+
getContext(sessionId, format = "window") {
|
|
3435
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
3436
|
+
if (format === "messages") return session.messages;
|
|
3437
|
+
if (format === "summary") return session.summary ?? "";
|
|
3438
|
+
return this.contextManager.buildWindow(session.messages, session.systemPrompt ?? this.config.systemPrompt, this.skillRegistry.listToolDefs()).messages;
|
|
3439
|
+
}
|
|
3440
|
+
searchContext(query, options) {
|
|
3441
|
+
const allMessages = /* @__PURE__ */ new Map();
|
|
3442
|
+
for (const session of this.sessionManager.list()) {
|
|
3443
|
+
allMessages.set(session.id, session.messages);
|
|
3444
|
+
}
|
|
3445
|
+
return this.contextManager.search(allMessages, query, options);
|
|
3446
|
+
}
|
|
3447
|
+
compressContext(sessionId, strategy) {
|
|
3448
|
+
const session = this.sessionManager.getOrThrow(sessionId);
|
|
3449
|
+
const result = this.contextManager.compress(session.messages, strategy);
|
|
3450
|
+
session.messages = result.messages;
|
|
3451
|
+
session.tokenCount = result.afterTokens;
|
|
3452
|
+
session.updatedAt = Date.now();
|
|
3453
|
+
this.emit("context:compress", { sessionId, beforeTokens: result.beforeTokens, afterTokens: result.afterTokens });
|
|
3454
|
+
return { beforeTokens: result.beforeTokens, afterTokens: result.afterTokens, compressionRatio: result.afterTokens / (result.beforeTokens || 1) };
|
|
3455
|
+
}
|
|
3456
|
+
// ---- Runtime Config ----
|
|
3457
|
+
configure(config) {
|
|
3458
|
+
if (config.llm) {
|
|
3459
|
+
Object.assign(this.config.llm, config.llm);
|
|
3460
|
+
this.llmAdapter = new OpenAIAdapter(this.config.llm);
|
|
3461
|
+
this.contextManager.setModel(this.config.llm.model);
|
|
3462
|
+
}
|
|
3463
|
+
if (config.serverUrl) {
|
|
3464
|
+
this.config.serverUrl = config.serverUrl;
|
|
3465
|
+
this.transport = new HttpTransport(config.serverUrl, this.config.authToken, this.config.headers);
|
|
3466
|
+
}
|
|
3467
|
+
if (config.authToken) {
|
|
3468
|
+
this.config.authToken = config.authToken;
|
|
3469
|
+
}
|
|
3470
|
+
if (config.systemPrompt) {
|
|
3471
|
+
this.config.systemPrompt = config.systemPrompt;
|
|
3472
|
+
}
|
|
3473
|
+
}
|
|
3474
|
+
// ---- Events ----
|
|
3475
|
+
on(event, handler) {
|
|
3476
|
+
if (!this.eventHandlers.has(event)) {
|
|
3477
|
+
this.eventHandlers.set(event, /* @__PURE__ */ new Set());
|
|
3478
|
+
}
|
|
3479
|
+
this.eventHandlers.get(event).add(handler);
|
|
3480
|
+
}
|
|
3481
|
+
off(event, handler) {
|
|
3482
|
+
this.eventHandlers.get(event)?.delete(handler);
|
|
3483
|
+
}
|
|
3484
|
+
emit(event, data) {
|
|
3485
|
+
this.eventHandlers.get(event)?.forEach((handler) => {
|
|
3486
|
+
try {
|
|
3487
|
+
handler(data);
|
|
3488
|
+
} catch {
|
|
3489
|
+
}
|
|
3490
|
+
});
|
|
3491
|
+
}
|
|
3492
|
+
// ---- Private Helpers ----
|
|
3493
|
+
/**
|
|
3494
|
+
* Stream LLM response token-by-token via the adapter's chatStream.
|
|
3495
|
+
* Forwards llm_text events to the caller and collects the full StandardLLMResponse.
|
|
3496
|
+
*/
|
|
3497
|
+
async *streamLlmResponse(messages, tools, signal) {
|
|
3498
|
+
let fullResponse = null;
|
|
3499
|
+
for await (const event of this.llmAdapter.chatStream(messages, tools, { signal })) {
|
|
3500
|
+
if (event.type === "llm_text" || event.type === "llm_thinking") {
|
|
3501
|
+
yield event;
|
|
3502
|
+
} else if (event.type === "llm_response") {
|
|
3503
|
+
fullResponse = event.response;
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
return fullResponse ?? { content: "", toolCalls: void 0, finishReason: "stop" };
|
|
3507
|
+
}
|
|
3508
|
+
/**
|
|
3509
|
+
* Resolve tool list: filter by tier/permission/name + add MCP tool definitions.
|
|
3510
|
+
*
|
|
3511
|
+
* - No allowedTools & no toolsByPermission → only system tier tools
|
|
3512
|
+
* - allowedTools only → filter by name (backward compat)
|
|
3513
|
+
* - toolsByPermission (with or without allowedTools) → union of permission-matched + name-matched
|
|
3514
|
+
*/
|
|
3515
|
+
resolveTools(allTools, options) {
|
|
3516
|
+
const { allowedTools, toolsByPermission } = options ?? {};
|
|
3517
|
+
if (!allowedTools && !toolsByPermission) {
|
|
3518
|
+
const systemTools = allTools.filter((t) => (t.tier ?? "system") === "system");
|
|
3519
|
+
return systemTools;
|
|
3520
|
+
}
|
|
3521
|
+
let localTools;
|
|
3522
|
+
if (toolsByPermission) {
|
|
3523
|
+
const permSet = new Set(toolsByPermission);
|
|
3524
|
+
const byPermission = allTools.filter((t) => {
|
|
3525
|
+
if (permSet.has("*")) return true;
|
|
3526
|
+
const perms = t.permissions ?? [];
|
|
3527
|
+
return perms.length === 0 || perms.some((p) => permSet.has(p));
|
|
3528
|
+
});
|
|
3529
|
+
if (allowedTools) {
|
|
3530
|
+
const nameSet = new Set(allowedTools.filter((n) => !this.mcpRouter.isMcpTool(n)));
|
|
3531
|
+
const byName = allTools.filter((t) => nameSet.has(t.name));
|
|
3532
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3533
|
+
localTools = [];
|
|
3534
|
+
for (const t of [...byName, ...byPermission]) {
|
|
3535
|
+
if (!seen.has(t.name)) {
|
|
3536
|
+
seen.add(t.name);
|
|
3537
|
+
localTools.push(t);
|
|
3538
|
+
}
|
|
3539
|
+
}
|
|
3540
|
+
} else {
|
|
3541
|
+
localTools = byPermission;
|
|
3542
|
+
}
|
|
3543
|
+
} else {
|
|
3544
|
+
const localNames = new Set(allowedTools.filter((n) => !this.mcpRouter.isMcpTool(n)));
|
|
3545
|
+
localTools = allTools.filter((t) => localNames.has(t.name));
|
|
3546
|
+
}
|
|
3547
|
+
const mcpNames = (allowedTools ?? []).filter((n) => this.mcpRouter.isMcpTool(n));
|
|
3548
|
+
const mcpTools = this.mcpRouter.resolveToolDefs(mcpNames);
|
|
3549
|
+
return [...localTools, ...mcpTools];
|
|
3550
|
+
}
|
|
3551
|
+
/**
|
|
3552
|
+
* Compute auto-approval set: non-system tier tools with sensitive permissions
|
|
3553
|
+
* are automatically added to the approval set.
|
|
3554
|
+
*/
|
|
3555
|
+
computeAutoApproval(tools, userApproval) {
|
|
3556
|
+
const auto = /* @__PURE__ */ new Set();
|
|
3557
|
+
for (const tool of tools) {
|
|
3558
|
+
const tier = tool.tier ?? "system";
|
|
3559
|
+
if (tier !== "system" && tool.permissions) {
|
|
3560
|
+
if (tool.permissions.some((p) => SENSITIVE_PERMISSIONS.has(p))) {
|
|
3561
|
+
auto.add(tool.name);
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
3564
|
+
}
|
|
3565
|
+
if (userApproval) {
|
|
3566
|
+
for (const name of userApproval) {
|
|
3567
|
+
auto.add(name);
|
|
3568
|
+
}
|
|
3569
|
+
}
|
|
3570
|
+
return Array.from(auto);
|
|
3571
|
+
}
|
|
3572
|
+
/**
|
|
3573
|
+
* Check permission policy for a tool call using the full permission system.
|
|
3574
|
+
* Returns the policy: 'auto' | 'approval' | 'force-approval' | 'disabled'
|
|
3575
|
+
*/
|
|
3576
|
+
checkToolPermission(skillDef, args, chatOptions, requireApproval) {
|
|
3577
|
+
if (!skillDef) {
|
|
3578
|
+
return requireApproval.has(args.__toolName) ? "force-approval" : "auto";
|
|
3579
|
+
}
|
|
3580
|
+
return resolvePermissionPolicy({
|
|
3581
|
+
skill: skillDef,
|
|
3582
|
+
args,
|
|
3583
|
+
globalMode: this.config.permissionMode ?? "standard",
|
|
3584
|
+
globalOverrides: this.config.permissionOverrides,
|
|
3585
|
+
autoApprove: chatOptions.autoApprove,
|
|
3586
|
+
chatMode: chatOptions.permissionMode,
|
|
3587
|
+
requireApproval
|
|
3588
|
+
});
|
|
3589
|
+
}
|
|
3590
|
+
// ── Parallel tool execution helpers ──
|
|
3591
|
+
planToolExecution(toolCalls, chatOptions, requireApproval) {
|
|
3592
|
+
const items = toolCalls.map((tc) => {
|
|
3593
|
+
const isMcp = this.mcpRouter.isMcpTool(tc.name);
|
|
3594
|
+
const skillDef = this.skillRegistry.get(tc.name);
|
|
3595
|
+
const location = isMcp ? "server" : skillDef?.location === "server" ? "server" : "local";
|
|
3596
|
+
const permPolicy = this.checkToolPermission(skillDef, tc.arguments, chatOptions, requireApproval);
|
|
3597
|
+
const parallelSafe = skillDef?.parallelSafe ?? true;
|
|
3598
|
+
return { toolCall: tc, skillDef, location, permPolicy, parallelSafe };
|
|
3599
|
+
});
|
|
3600
|
+
const canParallelize = items.every((item) => item.parallelSafe);
|
|
3601
|
+
return { canParallelize, items };
|
|
3602
|
+
}
|
|
3603
|
+
async processApprovalQueue(items, sessionId, emit, yieldEvent) {
|
|
3604
|
+
for (const item of items) {
|
|
3605
|
+
if (item.permPolicy === "disabled") {
|
|
3606
|
+
const denyResult = {
|
|
3607
|
+
content: [{ type: "text", text: `Tool "${item.toolCall.name}" is disabled in current permission mode.` }],
|
|
3608
|
+
isError: true
|
|
3609
|
+
};
|
|
3610
|
+
item.resolved = true;
|
|
3611
|
+
item.result = denyResult;
|
|
3612
|
+
this.addToolResult(sessionId, item.toolCall, denyResult);
|
|
3613
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: true, summary: "Permission denied (disabled)", duration: 0 });
|
|
3614
|
+
if (yieldEvent) {
|
|
3615
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: true, summary: "Permission denied (disabled)", duration: 0 });
|
|
3616
|
+
}
|
|
3617
|
+
} else if (item.permPolicy === "approval" || item.permPolicy === "force-approval") {
|
|
3618
|
+
emit("tool:approval", { sessionId, toolName: item.toolCall.name, arguments: item.toolCall.arguments, callId: item.toolCall.id });
|
|
3619
|
+
if (yieldEvent) {
|
|
3620
|
+
yieldEvent({ type: "tool_approval", callId: item.toolCall.id, toolName: item.toolCall.name, arguments: item.toolCall.arguments });
|
|
3621
|
+
}
|
|
3622
|
+
const approved = await this.waitForApproval(item.toolCall.id);
|
|
3623
|
+
if (!approved) {
|
|
3624
|
+
const rejectResult = {
|
|
3625
|
+
content: [{ type: "text", text: "Tool call rejected by user." }],
|
|
3626
|
+
isError: true
|
|
3627
|
+
};
|
|
3628
|
+
item.resolved = true;
|
|
3629
|
+
item.result = rejectResult;
|
|
3630
|
+
this.addToolResult(sessionId, item.toolCall, rejectResult);
|
|
3631
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: true, summary: "Rejected", duration: 0 });
|
|
3632
|
+
if (yieldEvent) {
|
|
3633
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: true, summary: "Rejected", duration: 0 });
|
|
3634
|
+
}
|
|
3635
|
+
}
|
|
3636
|
+
}
|
|
3637
|
+
}
|
|
3638
|
+
}
|
|
3639
|
+
async executeToolBatch(items, sessionId, controller, canParallelize, emit) {
|
|
3640
|
+
const traceEntries = [];
|
|
3641
|
+
for (const item of items) {
|
|
3642
|
+
emit("tool:call", { sessionId, toolName: item.toolCall.name, arguments: item.toolCall.arguments, location: item.location });
|
|
3643
|
+
}
|
|
3644
|
+
for (const item of items) {
|
|
3645
|
+
if (item.resolved) {
|
|
3646
|
+
const summary = item.result?.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ") ?? "";
|
|
3647
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: item.result?.isError ?? true, summary }, duration: 0 });
|
|
3648
|
+
}
|
|
3649
|
+
}
|
|
3650
|
+
const executableItems = items.filter((item) => !item.resolved);
|
|
3651
|
+
if (executableItems.length === 0) return traceEntries;
|
|
3652
|
+
if (executableItems.length === 1) {
|
|
3653
|
+
const item = executableItems[0];
|
|
3654
|
+
const execStart = Date.now();
|
|
3655
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3656
|
+
const duration = Date.now() - execStart;
|
|
3657
|
+
const summary = result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3658
|
+
this.addToolResult(sessionId, item.toolCall, result);
|
|
3659
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: result.isError ?? false, summary, duration });
|
|
3660
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: result.isError ?? false, summary }, duration });
|
|
3661
|
+
return traceEntries;
|
|
3662
|
+
}
|
|
3663
|
+
if (canParallelize) {
|
|
3664
|
+
const results = await Promise.allSettled(
|
|
3665
|
+
executableItems.map(async (item) => {
|
|
3666
|
+
const execStart = Date.now();
|
|
3667
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3668
|
+
const duration = Date.now() - execStart;
|
|
3669
|
+
return { item, result, duration };
|
|
3670
|
+
})
|
|
3671
|
+
);
|
|
3672
|
+
for (let i = 0; i < results.length; i++) {
|
|
3673
|
+
const settled = results[i];
|
|
3674
|
+
const item = executableItems[i];
|
|
3675
|
+
if (settled.status === "fulfilled") {
|
|
3676
|
+
const { result, duration } = settled.value;
|
|
3677
|
+
const summary = result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3678
|
+
this.addToolResult(sessionId, item.toolCall, result);
|
|
3679
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: result.isError ?? false, summary, duration });
|
|
3680
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: result.isError ?? false, summary }, duration });
|
|
3681
|
+
} else {
|
|
3682
|
+
const errResult = { content: [{ type: "text", text: `Error: ${settled.reason?.message ?? "Unknown error"}` }], isError: true };
|
|
3683
|
+
this.addToolResult(sessionId, item.toolCall, errResult);
|
|
3684
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: true, summary: settled.reason?.message ?? "Unknown error", duration: 0 });
|
|
3685
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: true, summary: settled.reason?.message }, duration: 0 });
|
|
3686
|
+
}
|
|
3687
|
+
}
|
|
3688
|
+
} else {
|
|
3689
|
+
for (const item of executableItems) {
|
|
3690
|
+
const execStart = Date.now();
|
|
3691
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3692
|
+
const duration = Date.now() - execStart;
|
|
3693
|
+
const summary = result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3694
|
+
this.addToolResult(sessionId, item.toolCall, result);
|
|
3695
|
+
emit("tool:result", { sessionId, toolName: item.toolCall.name, isError: result.isError ?? false, summary, duration });
|
|
3696
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: result.isError ?? false, summary }, duration });
|
|
3697
|
+
}
|
|
3698
|
+
}
|
|
3699
|
+
return traceEntries;
|
|
3700
|
+
}
|
|
3701
|
+
async executeToolBatchStream(items, sessionId, controller, canParallelize, yieldEvent) {
|
|
3702
|
+
const traceEntries = [];
|
|
3703
|
+
for (const item of items) {
|
|
3704
|
+
yieldEvent({ type: "tool_call", callId: item.toolCall.id, toolName: item.toolCall.name, arguments: item.toolCall.arguments, location: item.location });
|
|
3705
|
+
if (item.resolved) {
|
|
3706
|
+
const summary = item.result?.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ") ?? "";
|
|
3707
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: true, summary, duration: 0 });
|
|
3708
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: true, summary }, duration: 0 });
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
const executableItems = items.filter((item) => !item.resolved);
|
|
3712
|
+
if (executableItems.length === 0) return traceEntries;
|
|
3713
|
+
if (executableItems.length === 1) {
|
|
3714
|
+
const item = executableItems[0];
|
|
3715
|
+
const execStart = Date.now();
|
|
3716
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3717
|
+
const duration = Date.now() - execStart;
|
|
3718
|
+
const summary = result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3719
|
+
this.addToolResult(sessionId, item.toolCall, result);
|
|
3720
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: result.isError ?? false, summary, duration });
|
|
3721
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: result.isError ?? false, summary }, duration });
|
|
3722
|
+
return traceEntries;
|
|
3723
|
+
}
|
|
3724
|
+
if (canParallelize) {
|
|
3725
|
+
const n = executableItems.length;
|
|
3726
|
+
const slots = new Array(n).fill(null);
|
|
3727
|
+
let nextFlush = 0;
|
|
3728
|
+
const tryFlush = () => {
|
|
3729
|
+
while (nextFlush < n && slots[nextFlush] !== null) {
|
|
3730
|
+
const entry = slots[nextFlush];
|
|
3731
|
+
const item = executableItems[nextFlush];
|
|
3732
|
+
const summary = entry.result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3733
|
+
this.addToolResult(sessionId, item.toolCall, entry.result);
|
|
3734
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: entry.result.isError ?? false, summary, duration: entry.duration });
|
|
3735
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: entry.result.isError ?? false, summary }, duration: entry.duration });
|
|
3736
|
+
nextFlush++;
|
|
3737
|
+
}
|
|
3738
|
+
};
|
|
3739
|
+
await Promise.allSettled(
|
|
3740
|
+
executableItems.map(async (item, index) => {
|
|
3741
|
+
const execStart = Date.now();
|
|
3742
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3743
|
+
const duration = Date.now() - execStart;
|
|
3744
|
+
slots[index] = { result, duration };
|
|
3745
|
+
tryFlush();
|
|
3746
|
+
})
|
|
3747
|
+
);
|
|
3748
|
+
tryFlush();
|
|
3749
|
+
} else {
|
|
3750
|
+
for (const item of executableItems) {
|
|
3751
|
+
const execStart = Date.now();
|
|
3752
|
+
const result = await this.executeToolCall(item.toolCall, sessionId, controller);
|
|
3753
|
+
const duration = Date.now() - execStart;
|
|
3754
|
+
const summary = result.content.filter((c) => c.type === "text").map((c) => c.text.slice(0, 100)).join(" ");
|
|
3755
|
+
this.addToolResult(sessionId, item.toolCall, result);
|
|
3756
|
+
yieldEvent({ type: "tool_result", callId: item.toolCall.id, toolName: item.toolCall.name, isError: result.isError ?? false, summary, duration });
|
|
3757
|
+
traceEntries.push({ callId: item.toolCall.id, toolName: item.toolCall.name, location: item.location, arguments: item.toolCall.arguments, result: { isError: result.isError ?? false, summary }, duration });
|
|
3758
|
+
}
|
|
3759
|
+
}
|
|
3760
|
+
return traceEntries;
|
|
3761
|
+
}
|
|
3762
|
+
/**
|
|
3763
|
+
* Execute a tool call, routing mcp: prefixed tools to McpRouter.
|
|
3764
|
+
*/
|
|
3765
|
+
async executeToolCall(toolCall, sessionId, controller) {
|
|
3766
|
+
const execStart = Date.now();
|
|
3767
|
+
if (this.mcpRouter.isMcpTool(toolCall.name)) {
|
|
3768
|
+
try {
|
|
3769
|
+
const result = await this.mcpRouter.call(toolCall.name, toolCall.arguments);
|
|
3770
|
+
return { content: [{ type: "text", text: typeof result === "string" ? result : JSON.stringify(result) }] };
|
|
3771
|
+
} catch (err) {
|
|
3772
|
+
return { content: [{ type: "text", text: `MCP error: ${err.message}` }], isError: true };
|
|
3773
|
+
}
|
|
3774
|
+
}
|
|
3775
|
+
const skillDef = this.skillRegistry.get(toolCall.name);
|
|
3776
|
+
const location = skillDef?.location === "server" ? "server" : "local";
|
|
3777
|
+
try {
|
|
3778
|
+
if (location === "server" && this.transport instanceof HttpTransport) {
|
|
3779
|
+
return await this.executeServerSkill(toolCall);
|
|
3780
|
+
} else {
|
|
3781
|
+
const invokeFn = (skillName, params) => this.skillExecutor.invokeDirect(skillName, params, {
|
|
3782
|
+
sessionId,
|
|
3783
|
+
agent: this,
|
|
3784
|
+
signal: controller.signal,
|
|
3785
|
+
depth: 0,
|
|
3786
|
+
invoke: invokeFn
|
|
3787
|
+
});
|
|
3788
|
+
return await this.skillExecutor.execute(toolCall.name, toolCall.arguments, {
|
|
3789
|
+
sessionId,
|
|
3790
|
+
agent: this,
|
|
3791
|
+
signal: controller.signal,
|
|
3792
|
+
depth: 0,
|
|
3793
|
+
invoke: invokeFn
|
|
3794
|
+
});
|
|
3795
|
+
}
|
|
3796
|
+
} catch (err) {
|
|
3797
|
+
return { content: [{ type: "text", text: `Error: ${err.message}` }], isError: true };
|
|
3798
|
+
}
|
|
3799
|
+
}
|
|
3800
|
+
ensureInitialized() {
|
|
3801
|
+
if (!this.initialized) {
|
|
3802
|
+
throw new ACPError(ACPErrorCodes.AGENT_NOT_INITIALIZED, "Agent not initialized. Call init() first.");
|
|
3803
|
+
}
|
|
3804
|
+
}
|
|
3805
|
+
ensureSession() {
|
|
3806
|
+
if (this.currentSessionId) {
|
|
3807
|
+
const existing = this.sessionManager.get(this.currentSessionId);
|
|
3808
|
+
if (existing) return existing;
|
|
3809
|
+
}
|
|
3810
|
+
const session = this.sessionManager.create();
|
|
3811
|
+
this.currentSessionId = session.id;
|
|
3812
|
+
return session;
|
|
3813
|
+
}
|
|
3814
|
+
/** Resolve system prompt — can be overridden by subclasses to inject context */
|
|
3815
|
+
resolveSystemPrompt(sessionId, base) {
|
|
3816
|
+
return base;
|
|
3817
|
+
}
|
|
3818
|
+
buildUserContent(message, attachments) {
|
|
3819
|
+
if (!attachments?.length) return message;
|
|
3820
|
+
const attachmentBlocks = fileInputsToContentBlocks(attachments);
|
|
3821
|
+
if (typeof message === "string") {
|
|
3822
|
+
const textBlock = { type: "text", text: message };
|
|
3823
|
+
return [...attachmentBlocks, textBlock];
|
|
3824
|
+
}
|
|
3825
|
+
return [...attachmentBlocks, ...message];
|
|
3826
|
+
}
|
|
3827
|
+
addToolResult(sessionId, toolCall, result) {
|
|
3828
|
+
const textBlocks = result.content.filter((c) => c.type === "text");
|
|
3829
|
+
const nonTextBlocks = result.content.filter((c) => c.type !== "text");
|
|
3830
|
+
if (nonTextBlocks.length === 0) {
|
|
3831
|
+
const text = textBlocks.map((c) => c.text).join("\n");
|
|
3832
|
+
this.sessionManager.addMessage(sessionId, { role: "tool", content: text, toolCallId: toolCall.id });
|
|
3833
|
+
} else {
|
|
3834
|
+
this.sessionManager.addMessage(sessionId, { role: "tool", content: result.content, toolCallId: toolCall.id });
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
async executeServerSkill(toolCall) {
|
|
3838
|
+
const transport = this.transport;
|
|
3839
|
+
const result = await transport.send("tools/call", { name: toolCall.name, arguments: toolCall.arguments });
|
|
3840
|
+
return result;
|
|
3841
|
+
}
|
|
3842
|
+
};
|
|
3843
|
+
export {
|
|
3844
|
+
ACPError,
|
|
3845
|
+
ACPErrorCodes,
|
|
3846
|
+
ContextManager,
|
|
3847
|
+
GraphExecutor,
|
|
3848
|
+
GraphPlanner,
|
|
3849
|
+
HttpTransport,
|
|
3850
|
+
Ldoing,
|
|
3851
|
+
LocalTransport,
|
|
3852
|
+
McpRouter,
|
|
3853
|
+
MemoryPersistence,
|
|
3854
|
+
OpenAIAdapter,
|
|
3855
|
+
OpenAIContentAdapter,
|
|
3856
|
+
PERMISSION_MODE_DEFAULTS,
|
|
3857
|
+
PlanTracker,
|
|
3858
|
+
SENSITIVE_PERMISSIONS,
|
|
3859
|
+
SessionManager,
|
|
3860
|
+
SkillExecutor,
|
|
3861
|
+
SkillRegistry,
|
|
3862
|
+
SubAgent,
|
|
3863
|
+
TaskGraph,
|
|
3864
|
+
TaskPlanner,
|
|
3865
|
+
contentToPreview,
|
|
3866
|
+
contentToString,
|
|
3867
|
+
detectRuntime,
|
|
3868
|
+
estimateContentTokens,
|
|
3869
|
+
estimateMessageTokens,
|
|
3870
|
+
estimateRequestTokens,
|
|
3871
|
+
estimateTextTokens,
|
|
3872
|
+
estimateToolDefTokens,
|
|
3873
|
+
fileInputsToContentBlocks,
|
|
3874
|
+
interpolateInstruction,
|
|
3875
|
+
interpolateTemplate,
|
|
3876
|
+
resolveModelCapabilities,
|
|
3877
|
+
resolveModelContextLength,
|
|
3878
|
+
resolvePermissionPolicy
|
|
3879
|
+
};
|