@dudko.dev/agent 0.0.1
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/LICENSE +21 -0
- package/README.md +173 -0
- package/dist/cli.js +1447 -0
- package/dist/cli.js.map +1 -0
- package/dist/index.cjs +1056 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +172 -0
- package/dist/index.d.ts +172 -0
- package/dist/index.js +1052 -0
- package/dist/index.js.map +1 -0
- package/package.json +78 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1447 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'util';
|
|
3
|
+
import { stdout, stdin } from 'process';
|
|
4
|
+
import { createInterface } from 'readline/promises';
|
|
5
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
6
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
7
|
+
import { dynamicTool, jsonSchema, generateObject, streamObject, streamText, stepCountIs } from 'ai';
|
|
8
|
+
import { URL } from 'url';
|
|
9
|
+
import { createAnthropic } from '@ai-sdk/anthropic';
|
|
10
|
+
import { createGoogleGenerativeAI } from '@ai-sdk/google';
|
|
11
|
+
import { createOpenAI } from '@ai-sdk/openai';
|
|
12
|
+
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';
|
|
13
|
+
import { randomUUID } from 'crypto';
|
|
14
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
|
|
17
|
+
var HELP = `Usage: dd-agent [options]
|
|
18
|
+
|
|
19
|
+
Options:
|
|
20
|
+
--env-file=<path> Load env vars from a dotenv file before starting
|
|
21
|
+
-h, --help Show this help
|
|
22
|
+
|
|
23
|
+
Required env vars (set directly or via --env-file):
|
|
24
|
+
AGENT_PROVIDER_TYPE one of: openai | anthropic | openai-compatible | google
|
|
25
|
+
AGENT_API_KEY provider API key
|
|
26
|
+
AGENT_MODEL model id
|
|
27
|
+
MCP_SERVERS JSON: { "<name>": { "url": "...", "headers"?: {...} } }
|
|
28
|
+
|
|
29
|
+
Commands inside the REPL:
|
|
30
|
+
/status, /tools, /history, /reset, /reconnect, /exit
|
|
31
|
+
`;
|
|
32
|
+
var parseCliArgs = (argv) => {
|
|
33
|
+
const { values } = parseArgs({
|
|
34
|
+
args: argv,
|
|
35
|
+
options: {
|
|
36
|
+
"env-file": { type: "string" },
|
|
37
|
+
help: { type: "boolean", short: "h" }
|
|
38
|
+
},
|
|
39
|
+
strict: true,
|
|
40
|
+
allowPositionals: false
|
|
41
|
+
});
|
|
42
|
+
return {
|
|
43
|
+
envFile: values["env-file"],
|
|
44
|
+
help: Boolean(values.help)
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
var connectMcpServers = async (servers, log, clientName, outputSanitizer) => {
|
|
48
|
+
const clients = [];
|
|
49
|
+
const tools = {};
|
|
50
|
+
const catalog = [];
|
|
51
|
+
const results = [];
|
|
52
|
+
for (const [name, cfg] of Object.entries(servers)) {
|
|
53
|
+
if (cfg.headers && cfg.getHeaders) {
|
|
54
|
+
throw new Error(`MCP server "${name}": specify either headers or getHeaders, not both`);
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
const headers = cfg.getHeaders ? await cfg.getHeaders() : cfg.headers;
|
|
58
|
+
const transport = new StreamableHTTPClientTransport(new URL(cfg.url), {
|
|
59
|
+
requestInit: headers ? { headers } : void 0,
|
|
60
|
+
// Built-in reconnect for transient SSE drops. Defaults are conservative;
|
|
61
|
+
// production deployments should tune via direct transport access if needed.
|
|
62
|
+
reconnectionOptions: {
|
|
63
|
+
maxReconnectionDelay: 3e4,
|
|
64
|
+
initialReconnectionDelay: 1e3,
|
|
65
|
+
reconnectionDelayGrowFactor: 1.5,
|
|
66
|
+
maxRetries: 5
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
transport.onerror = (err) => log("warn", `[mcp] ${name}: transport error - ${err.message}`);
|
|
70
|
+
transport.onclose = () => log("warn", `[mcp] ${name}: transport closed`);
|
|
71
|
+
const client = new Client({ name: clientName, version: "0.0.0" });
|
|
72
|
+
await client.connect(transport);
|
|
73
|
+
clients.push(client);
|
|
74
|
+
const listed = await client.listTools();
|
|
75
|
+
let mounted = 0;
|
|
76
|
+
for (const t of listed.tools) {
|
|
77
|
+
const prefixed = `${name}__${t.name}`;
|
|
78
|
+
const description = t.description ?? "";
|
|
79
|
+
tools[prefixed] = dynamicTool({
|
|
80
|
+
description,
|
|
81
|
+
inputSchema: jsonSchema(t.inputSchema),
|
|
82
|
+
execute: async (args, opts) => {
|
|
83
|
+
const result = await client.callTool(
|
|
84
|
+
{
|
|
85
|
+
name: t.name,
|
|
86
|
+
arguments: args ?? {}
|
|
87
|
+
},
|
|
88
|
+
void 0,
|
|
89
|
+
opts?.abortSignal ? { signal: opts.abortSignal } : void 0
|
|
90
|
+
);
|
|
91
|
+
const flat = flattenContent(result.content);
|
|
92
|
+
if (!outputSanitizer) {
|
|
93
|
+
return flat;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
return await outputSanitizer(prefixed, flat);
|
|
97
|
+
} catch (err) {
|
|
98
|
+
log(
|
|
99
|
+
"warn",
|
|
100
|
+
`[mcp] ${prefixed}: outputSanitizer threw - ${err.message}; output replaced with placeholder`
|
|
101
|
+
);
|
|
102
|
+
return "[output redacted: sanitizer failed]";
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
catalog.push({ name: prefixed, description, server: name });
|
|
107
|
+
mounted++;
|
|
108
|
+
}
|
|
109
|
+
log("info", `[mcp] ${name}: connected, ${mounted} tools`);
|
|
110
|
+
results.push({ name, connected: true });
|
|
111
|
+
} catch (err) {
|
|
112
|
+
const message = err.message;
|
|
113
|
+
log("error", `[mcp] ${name}: failed to connect - ${message}`);
|
|
114
|
+
results.push({ name, connected: false, error: message });
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
tools,
|
|
119
|
+
catalog,
|
|
120
|
+
results,
|
|
121
|
+
close: async () => {
|
|
122
|
+
await Promise.allSettled(clients.map((c) => c.close()));
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
};
|
|
126
|
+
var flattenContent = (content) => {
|
|
127
|
+
if (!Array.isArray(content)) {
|
|
128
|
+
return content;
|
|
129
|
+
}
|
|
130
|
+
const parts = content;
|
|
131
|
+
const allText = parts.length > 0 && parts.every((p) => p?.type === "text" && typeof p.text === "string");
|
|
132
|
+
if (allText) {
|
|
133
|
+
return parts.map((p) => p.text).join("\n");
|
|
134
|
+
}
|
|
135
|
+
return parts.map((p) => {
|
|
136
|
+
if (p?.type === "text" && typeof p.text === "string") {
|
|
137
|
+
return p.text;
|
|
138
|
+
}
|
|
139
|
+
return p;
|
|
140
|
+
});
|
|
141
|
+
};
|
|
142
|
+
var filterTools = (tools, catalog, available, excluded) => {
|
|
143
|
+
const allow = available?.length ? new Set(available) : null;
|
|
144
|
+
const deny = excluded?.length ? new Set(excluded) : null;
|
|
145
|
+
const result = {};
|
|
146
|
+
const filteredCatalog = [];
|
|
147
|
+
for (const entry of catalog) {
|
|
148
|
+
if (allow && !allow.has(entry.name)) {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
if (!allow && deny?.has(entry.name)) {
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const t = tools[entry.name];
|
|
155
|
+
if (!t) {
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
result[entry.name] = t;
|
|
159
|
+
filteredCatalog.push(entry);
|
|
160
|
+
}
|
|
161
|
+
return { tools: result, catalog: filteredCatalog };
|
|
162
|
+
};
|
|
163
|
+
var buildModel = (config, modelId) => {
|
|
164
|
+
switch (config.providerType) {
|
|
165
|
+
case "openai": {
|
|
166
|
+
const provider = createOpenAI({
|
|
167
|
+
baseURL: config.baseURL || void 0,
|
|
168
|
+
apiKey: config.apiKey
|
|
169
|
+
});
|
|
170
|
+
return provider(modelId);
|
|
171
|
+
}
|
|
172
|
+
case "anthropic": {
|
|
173
|
+
const provider = createAnthropic({
|
|
174
|
+
baseURL: config.baseURL || void 0,
|
|
175
|
+
apiKey: config.apiKey
|
|
176
|
+
});
|
|
177
|
+
return provider(modelId);
|
|
178
|
+
}
|
|
179
|
+
case "openai-compatible": {
|
|
180
|
+
if (!config.baseURL) {
|
|
181
|
+
throw new Error("openai-compatible provider requires baseURL");
|
|
182
|
+
}
|
|
183
|
+
const provider = createOpenAICompatible({
|
|
184
|
+
name: config.clientName,
|
|
185
|
+
baseURL: config.baseURL,
|
|
186
|
+
apiKey: config.apiKey
|
|
187
|
+
});
|
|
188
|
+
return provider(modelId);
|
|
189
|
+
}
|
|
190
|
+
case "google": {
|
|
191
|
+
const provider = createGoogleGenerativeAI({
|
|
192
|
+
baseURL: config.baseURL || void 0,
|
|
193
|
+
apiKey: config.apiKey
|
|
194
|
+
});
|
|
195
|
+
return provider(modelId);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
};
|
|
199
|
+
var runContext = new AsyncLocalStorage();
|
|
200
|
+
var HISTORY_CONTENT_LIMIT = 1500;
|
|
201
|
+
var renderHistory = (history) => {
|
|
202
|
+
if (!history?.length) {
|
|
203
|
+
return "(no prior conversation)";
|
|
204
|
+
}
|
|
205
|
+
const tail = history.slice(-8);
|
|
206
|
+
const skipped = history.length - tail.length;
|
|
207
|
+
const lines = [];
|
|
208
|
+
if (skipped > 0) {
|
|
209
|
+
lines.push(`(${skipped} earlier turns omitted)`);
|
|
210
|
+
}
|
|
211
|
+
for (const t of tail) {
|
|
212
|
+
const content = t.content.length > HISTORY_CONTENT_LIMIT ? `${t.content.slice(0, HISTORY_CONTENT_LIMIT)}... [truncated]` : t.content;
|
|
213
|
+
lines.push(`${t.role}: ${content}`);
|
|
214
|
+
}
|
|
215
|
+
return lines.join("\n");
|
|
216
|
+
};
|
|
217
|
+
var CATALOG_BUDGETS = {
|
|
218
|
+
full: { tools: 80, descChars: 240 },
|
|
219
|
+
compact: { tools: 200, descChars: 80 }
|
|
220
|
+
};
|
|
221
|
+
var renderToolCatalog = (catalog, mode = "full") => {
|
|
222
|
+
if (catalog.length === 0) {
|
|
223
|
+
return "(no tools available)";
|
|
224
|
+
}
|
|
225
|
+
const { tools: toolLimit, descChars } = CATALOG_BUDGETS[mode];
|
|
226
|
+
const sliced = catalog.slice(0, toolLimit);
|
|
227
|
+
const rest = catalog.length - sliced.length;
|
|
228
|
+
const lines = sliced.map((t) => {
|
|
229
|
+
const desc = (t.description || "").replace(/\s+/g, " ").trim().slice(0, descChars);
|
|
230
|
+
return `- ${t.name}: ${desc}`;
|
|
231
|
+
});
|
|
232
|
+
if (rest > 0) {
|
|
233
|
+
lines.push(`... and ${rest} more tools`);
|
|
234
|
+
}
|
|
235
|
+
return lines.join("\n");
|
|
236
|
+
};
|
|
237
|
+
var TOOL_OUTPUT_BUDGET = 1500;
|
|
238
|
+
var truncateOutput = (output2) => {
|
|
239
|
+
let s;
|
|
240
|
+
try {
|
|
241
|
+
s = typeof output2 === "string" ? output2 : JSON.stringify(output2);
|
|
242
|
+
} catch {
|
|
243
|
+
s = String(output2);
|
|
244
|
+
}
|
|
245
|
+
return s.length > TOOL_OUTPUT_BUDGET ? `${s.slice(0, TOOL_OUTPUT_BUDGET)}... [truncated, ${s.length - TOOL_OUTPUT_BUDGET} chars]` : s;
|
|
246
|
+
};
|
|
247
|
+
var renderTraceEntry = (r, idx) => {
|
|
248
|
+
const calls = r.toolCalls.length ? r.toolCalls.map((c) => ` - ${c.name} ${c.ok ? "ok" : "fail"}: ${truncateOutput(c.output)}`).join("\n") : " (no tool calls)";
|
|
249
|
+
return [
|
|
250
|
+
`Step ${idx + 1}: ${r.step.description}`,
|
|
251
|
+
` Result: ${r.summary}`,
|
|
252
|
+
` Tool calls:`,
|
|
253
|
+
calls
|
|
254
|
+
].join("\n");
|
|
255
|
+
};
|
|
256
|
+
var renderTrace = (trace) => {
|
|
257
|
+
if (trace.length === 0) {
|
|
258
|
+
return "(no steps executed yet)";
|
|
259
|
+
}
|
|
260
|
+
return trace.map(renderTraceEntry).join("\n");
|
|
261
|
+
};
|
|
262
|
+
var renderPlan = (plan) => [
|
|
263
|
+
`Plan thought: ${plan.thought}`,
|
|
264
|
+
"Steps:",
|
|
265
|
+
...plan.steps.map(
|
|
266
|
+
(s, i) => ` ${i + 1}. [${s.id}] ${s.description}
|
|
267
|
+
expected: ${s.expectedOutcome}` + (s.suggestedTools?.length ? `
|
|
268
|
+
suggested tools: ${s.suggestedTools.join(", ")}` : "")
|
|
269
|
+
)
|
|
270
|
+
].join("\n");
|
|
271
|
+
var PLANNER_SYSTEM_BASE = `You are the Planner of a multi-step agent system.
|
|
272
|
+
|
|
273
|
+
Your only job is to decompose the user's request into a short ordered list of concrete actionable steps that a tool-using Executor can perform one at a time.
|
|
274
|
+
|
|
275
|
+
Rules:
|
|
276
|
+
1. Produce 1-5 steps for typical requests (hard cap is 8). Prefer FEWER, larger steps over many micro-steps. If the task is trivial and needs no tools, output a single step "Answer the user directly".
|
|
277
|
+
2. Each step must be self-contained, action-oriented, and verifiable. State what should be done and what the expected outcome is.
|
|
278
|
+
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
279
|
+
4. If the request asks for information that is likely retrievable via the available tools, plan to use them. If no tool fits, plan to answer from general knowledge.
|
|
280
|
+
5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
|
|
281
|
+
6. Output strict JSON matching the requested schema. No prose outside JSON.`;
|
|
282
|
+
var PLANNER_NARROWED_ADDENDUM = `
|
|
283
|
+
|
|
284
|
+
ADDITIONAL RULE (tool-narrowed mode):
|
|
285
|
+
The agent narrows the active tool set per-step using suggestedTools. You MUST set suggestedTools to the EXACT tool names the executor will use for that step. If a step is reasoning-only and needs no tools, leave suggestedTools empty. Missing or wrong suggestedTools will leave the executor without the tools it needs.`;
|
|
286
|
+
var buildPlannerSystem = (mode) => mode === "compact" ? PLANNER_SYSTEM_BASE + PLANNER_NARROWED_ADDENDUM : PLANNER_SYSTEM_BASE;
|
|
287
|
+
var buildPlannerUserPrompt = (input2, toolCatalog, history, catalogMode = "full") => [
|
|
288
|
+
history?.length ? `Conversation history:
|
|
289
|
+
${renderHistory(history)}
|
|
290
|
+
` : "",
|
|
291
|
+
`User request:
|
|
292
|
+
${input2}`,
|
|
293
|
+
"",
|
|
294
|
+
`Available tools:
|
|
295
|
+
${renderToolCatalog(toolCatalog, catalogMode)}`,
|
|
296
|
+
"",
|
|
297
|
+
"Produce the plan now."
|
|
298
|
+
].filter(Boolean).join("\n");
|
|
299
|
+
var EXECUTOR_SYSTEM = `You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
|
|
300
|
+
|
|
301
|
+
Rules:
|
|
302
|
+
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
303
|
+
2. Use the available tools when they help. Call them with valid arguments. Read prior step results in the trace before re-fetching the same data.
|
|
304
|
+
3. When the step is complete, write a short concrete "step result" describing what you found / did. Include identifiers, names, or key data the next step might need.
|
|
305
|
+
4. If the step is impossible with the available tools, or if you are otherwise blocked, explain the blocker briefly and end your reply with the literal token [BLOCKER] on its own line. The system uses this token (language-independent) to invoke the Replanner. Do not fabricate data.
|
|
306
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`;
|
|
307
|
+
var buildExecutorUserPrompt = (input2, plan, step, trace, history) => [
|
|
308
|
+
history?.length ? `Conversation history:
|
|
309
|
+
${renderHistory(history)}
|
|
310
|
+
` : "",
|
|
311
|
+
`Original user request:
|
|
312
|
+
${input2}`,
|
|
313
|
+
"",
|
|
314
|
+
`Overall plan:
|
|
315
|
+
${renderPlan(plan)}`,
|
|
316
|
+
"",
|
|
317
|
+
`Trace so far:
|
|
318
|
+
${renderTrace(trace)}`,
|
|
319
|
+
"",
|
|
320
|
+
`CURRENT STEP to execute (id=${step.id}): ${step.description}`,
|
|
321
|
+
`Expected outcome: ${step.expectedOutcome}`,
|
|
322
|
+
step.suggestedTools?.length ? `Suggested tools: ${step.suggestedTools.join(", ")}` : "",
|
|
323
|
+
"",
|
|
324
|
+
"Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."
|
|
325
|
+
].filter(Boolean).join("\n");
|
|
326
|
+
var REPLANNER_SYSTEM = `You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
|
|
327
|
+
|
|
328
|
+
You have three options:
|
|
329
|
+
- "continue": the next planned step is still appropriate.
|
|
330
|
+
- "revise": the plan is wrong or incomplete given what we now know - produce a NEW plan covering only the REMAINING work (do not include already-completed steps). The new plan must follow the same rules as the original Planner.
|
|
331
|
+
- "finish": we already have enough information to answer the user. The system will then synthesize the final answer from the trace.
|
|
332
|
+
|
|
333
|
+
Rules:
|
|
334
|
+
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
335
|
+
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
336
|
+
3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
|
|
337
|
+
4. Output strict JSON matching the schema. No prose outside JSON.`;
|
|
338
|
+
var buildReplannerUserPrompt = (input2, plan, trace, nextStep, toolCatalog, catalogMode = "full") => [
|
|
339
|
+
`Original user request:
|
|
340
|
+
${input2}`,
|
|
341
|
+
"",
|
|
342
|
+
`Current plan:
|
|
343
|
+
${renderPlan(plan)}`,
|
|
344
|
+
"",
|
|
345
|
+
`Completed steps:
|
|
346
|
+
${renderTrace(trace)}`,
|
|
347
|
+
"",
|
|
348
|
+
nextStep ? `Next planned step: [${nextStep.id}] ${nextStep.description}` : "There is no next step in the current plan.",
|
|
349
|
+
"",
|
|
350
|
+
`Available tools (for revise option):
|
|
351
|
+
${renderToolCatalog(toolCatalog, catalogMode)}`,
|
|
352
|
+
"",
|
|
353
|
+
"Decide now: continue, revise, or finish."
|
|
354
|
+
].join("\n");
|
|
355
|
+
var SYNTHESIZER_SYSTEM = `You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
356
|
+
|
|
357
|
+
Rules:
|
|
358
|
+
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
359
|
+
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
360
|
+
3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
|
|
361
|
+
4. Use the user's language.`;
|
|
362
|
+
var buildSynthesizerUserPrompt = (input2, plan, trace, history) => [
|
|
363
|
+
history?.length ? `Conversation history:
|
|
364
|
+
${renderHistory(history)}
|
|
365
|
+
` : "",
|
|
366
|
+
`User request:
|
|
367
|
+
${input2}`,
|
|
368
|
+
"",
|
|
369
|
+
`Plan that was executed:
|
|
370
|
+
${renderPlan(plan)}`,
|
|
371
|
+
"",
|
|
372
|
+
`Execution trace:
|
|
373
|
+
${renderTrace(trace)}`,
|
|
374
|
+
"",
|
|
375
|
+
"Write the final answer for the user now."
|
|
376
|
+
].filter(Boolean).join("\n");
|
|
377
|
+
|
|
378
|
+
// src/utils.ts
|
|
379
|
+
var isRetriable = (err, seen = /* @__PURE__ */ new Set()) => {
|
|
380
|
+
if (!err || typeof err !== "object") {
|
|
381
|
+
return false;
|
|
382
|
+
}
|
|
383
|
+
if (seen.has(err)) {
|
|
384
|
+
return false;
|
|
385
|
+
}
|
|
386
|
+
seen.add(err);
|
|
387
|
+
const e = err;
|
|
388
|
+
if (e.name === "AbortError") {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
const status = e.statusCode ?? e.status;
|
|
392
|
+
if (typeof status === "number") {
|
|
393
|
+
return status === 429 || status >= 500;
|
|
394
|
+
}
|
|
395
|
+
if (e.name === "TypeError") {
|
|
396
|
+
return true;
|
|
397
|
+
}
|
|
398
|
+
if (e.cause && typeof e.cause === "object") {
|
|
399
|
+
return isRetriable(e.cause, seen);
|
|
400
|
+
}
|
|
401
|
+
return false;
|
|
402
|
+
};
|
|
403
|
+
var withRetry = async (fn, opts) => {
|
|
404
|
+
const base = opts.baseDelayMs ?? 500;
|
|
405
|
+
let lastErr;
|
|
406
|
+
for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
|
|
407
|
+
if (opts.signal?.aborted) {
|
|
408
|
+
throw new DOMException("Aborted", "AbortError");
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
return await fn();
|
|
412
|
+
} catch (err) {
|
|
413
|
+
lastErr = err;
|
|
414
|
+
if (attempt === opts.maxRetries || !isRetriable(err)) {
|
|
415
|
+
throw err;
|
|
416
|
+
}
|
|
417
|
+
opts.onRetry?.(attempt + 1, err);
|
|
418
|
+
const delay = base * 2 ** attempt + Math.random() * 250;
|
|
419
|
+
await sleep(delay, opts.signal);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
throw lastErr;
|
|
423
|
+
};
|
|
424
|
+
var sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
425
|
+
if (signal?.aborted) {
|
|
426
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
const timer = setTimeout(() => {
|
|
430
|
+
signal?.removeEventListener("abort", onAbort);
|
|
431
|
+
resolve();
|
|
432
|
+
}, ms);
|
|
433
|
+
const onAbort = () => {
|
|
434
|
+
clearTimeout(timer);
|
|
435
|
+
reject(new DOMException("Aborted", "AbortError"));
|
|
436
|
+
};
|
|
437
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
438
|
+
});
|
|
439
|
+
var combineSignals = (signals) => {
|
|
440
|
+
const filtered = signals.filter((s) => Boolean(s));
|
|
441
|
+
if (filtered.length === 0) {
|
|
442
|
+
return new AbortController().signal;
|
|
443
|
+
}
|
|
444
|
+
if (filtered.length === 1) {
|
|
445
|
+
return filtered[0];
|
|
446
|
+
}
|
|
447
|
+
return AbortSignal.any(filtered);
|
|
448
|
+
};
|
|
449
|
+
var withTimeout = (signal, timeoutMs) => {
|
|
450
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
|
|
451
|
+
return signal ?? new AbortController().signal;
|
|
452
|
+
}
|
|
453
|
+
return combineSignals([signal, AbortSignal.timeout(timeoutMs)]);
|
|
454
|
+
};
|
|
455
|
+
|
|
456
|
+
// src/executor.ts
|
|
457
|
+
var buildActiveToolSet = (ctx, step) => {
|
|
458
|
+
if (ctx.config.toolSelectionStrategy !== "plan-narrowed") {
|
|
459
|
+
return ctx.tools;
|
|
460
|
+
}
|
|
461
|
+
const allowed = new Set(step.suggestedTools ?? []);
|
|
462
|
+
if (allowed.size === 0) {
|
|
463
|
+
if (step.requiresTools) {
|
|
464
|
+
return ctx.tools;
|
|
465
|
+
}
|
|
466
|
+
return {};
|
|
467
|
+
}
|
|
468
|
+
const filtered = {};
|
|
469
|
+
for (const name of allowed) {
|
|
470
|
+
const tool = ctx.tools[name];
|
|
471
|
+
if (tool) {
|
|
472
|
+
filtered[name] = tool;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return filtered;
|
|
476
|
+
};
|
|
477
|
+
var BLOCKER_SENTINEL = "[BLOCKER]";
|
|
478
|
+
var splitBlockerSentinel = (raw) => {
|
|
479
|
+
const idx = raw.indexOf(BLOCKER_SENTINEL);
|
|
480
|
+
if (idx === -1) {
|
|
481
|
+
return { summary: raw, blocked: false };
|
|
482
|
+
}
|
|
483
|
+
const cleaned = (raw.slice(0, idx) + raw.slice(idx + BLOCKER_SENTINEL.length)).trim();
|
|
484
|
+
return { summary: cleaned, blocked: true };
|
|
485
|
+
};
|
|
486
|
+
var SUMMARY_MAX_CHARS = 4e3;
|
|
487
|
+
var truncateForTrace = (s) => s.length > SUMMARY_MAX_CHARS ? `${s.slice(0, SUMMARY_MAX_CHARS)}... [truncated, ${s.length - SUMMARY_MAX_CHARS} chars]` : s;
|
|
488
|
+
var executeStep = async (input2, plan, step, trace, history, ctx, signal) => {
|
|
489
|
+
const startedAt = Date.now();
|
|
490
|
+
const outcome = await withRetry(() => runOnce(input2, plan, step, trace, history, ctx, signal), {
|
|
491
|
+
maxRetries: ctx.config.llmMaxRetries ?? 2,
|
|
492
|
+
signal,
|
|
493
|
+
onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "execute", attempt, error: err.message })
|
|
494
|
+
});
|
|
495
|
+
ctx.emit({ type: "usage", phase: "execute", usage: outcome.usage });
|
|
496
|
+
return {
|
|
497
|
+
step,
|
|
498
|
+
summary: outcome.summary,
|
|
499
|
+
toolCalls: outcome.toolCalls,
|
|
500
|
+
durationMs: Date.now() - startedAt,
|
|
501
|
+
blocked: outcome.blocked
|
|
502
|
+
};
|
|
503
|
+
};
|
|
504
|
+
var runOnce = async (input2, plan, step, trace, history, ctx, signal) => {
|
|
505
|
+
const toolCalls = [];
|
|
506
|
+
const toolInputs = /* @__PURE__ */ new Map();
|
|
507
|
+
const activeTools = buildActiveToolSet(ctx, step);
|
|
508
|
+
const narrowed = ctx.config.toolSelectionStrategy === "plan-narrowed";
|
|
509
|
+
const result = streamText({
|
|
510
|
+
model: ctx.executorModel,
|
|
511
|
+
tools: activeTools,
|
|
512
|
+
// Defence-in-depth: explicitly tell the SDK which tools are callable in
|
|
513
|
+
// this step. Only worth it in narrowed mode; in 'all' mode it's just a
|
|
514
|
+
// copy of every key, equivalent to omitting the field.
|
|
515
|
+
...narrowed ? { activeTools: Object.keys(activeTools) } : {},
|
|
516
|
+
stopWhen: stepCountIs(ctx.config.maxStepsPerTask),
|
|
517
|
+
system: ctx.config.systemPrompt ? `${EXECUTOR_SYSTEM}
|
|
518
|
+
|
|
519
|
+
Domain context:
|
|
520
|
+
${ctx.config.systemPrompt}` : EXECUTOR_SYSTEM,
|
|
521
|
+
prompt: buildExecutorUserPrompt(input2, plan, step, trace, history),
|
|
522
|
+
abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
|
|
523
|
+
});
|
|
524
|
+
for await (const part of result.fullStream) {
|
|
525
|
+
switch (part.type) {
|
|
526
|
+
case "text-delta":
|
|
527
|
+
if (part.text) {
|
|
528
|
+
ctx.emit({ type: "step.text-delta", step, delta: part.text });
|
|
529
|
+
}
|
|
530
|
+
break;
|
|
531
|
+
case "tool-call": {
|
|
532
|
+
toolInputs.set(part.toolCallId, { name: part.toolName, input: part.input });
|
|
533
|
+
ctx.emit({ type: "step.tool-call", step, name: part.toolName, input: part.input });
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
case "tool-result": {
|
|
537
|
+
const known = toolInputs.get(part.toolCallId);
|
|
538
|
+
toolCalls.push({
|
|
539
|
+
name: part.toolName,
|
|
540
|
+
input: known?.input ?? part.input,
|
|
541
|
+
output: part.output,
|
|
542
|
+
ok: true
|
|
543
|
+
});
|
|
544
|
+
ctx.emit({
|
|
545
|
+
type: "step.tool-result",
|
|
546
|
+
step,
|
|
547
|
+
name: part.toolName,
|
|
548
|
+
output: part.output,
|
|
549
|
+
ok: true
|
|
550
|
+
});
|
|
551
|
+
toolInputs.delete(part.toolCallId);
|
|
552
|
+
break;
|
|
553
|
+
}
|
|
554
|
+
case "tool-error": {
|
|
555
|
+
const known = toolInputs.get(part.toolCallId);
|
|
556
|
+
toolCalls.push({
|
|
557
|
+
name: part.toolName,
|
|
558
|
+
input: known?.input ?? part.input,
|
|
559
|
+
output: part.error,
|
|
560
|
+
ok: false
|
|
561
|
+
});
|
|
562
|
+
ctx.emit({
|
|
563
|
+
type: "step.tool-result",
|
|
564
|
+
step,
|
|
565
|
+
name: part.toolName,
|
|
566
|
+
output: part.error,
|
|
567
|
+
ok: false
|
|
568
|
+
});
|
|
569
|
+
toolInputs.delete(part.toolCallId);
|
|
570
|
+
break;
|
|
571
|
+
}
|
|
572
|
+
case "error": {
|
|
573
|
+
const error = part.error;
|
|
574
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
const [text, usage] = await Promise.all([result.text, result.usage]);
|
|
579
|
+
const { summary: cleaned, blocked } = splitBlockerSentinel(text.trim());
|
|
580
|
+
const summary = cleaned.length > 0 ? truncateForTrace(cleaned) : toolCalls.length > 0 ? `Executed ${toolCalls.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.` : "Step produced no output.";
|
|
581
|
+
return {
|
|
582
|
+
summary,
|
|
583
|
+
toolCalls,
|
|
584
|
+
blocked,
|
|
585
|
+
usage: {
|
|
586
|
+
inputTokens: usage.inputTokens ?? 0,
|
|
587
|
+
outputTokens: usage.outputTokens ?? 0,
|
|
588
|
+
totalTokens: usage.totalTokens ?? 0
|
|
589
|
+
}
|
|
590
|
+
};
|
|
591
|
+
};
|
|
592
|
+
var PlanStepSchema = z.object({
|
|
593
|
+
id: z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),
|
|
594
|
+
description: z.string().min(1).describe("Concrete action to perform"),
|
|
595
|
+
expectedOutcome: z.string().min(1).describe("What state/data should exist after this step"),
|
|
596
|
+
suggestedTools: z.array(z.string()).optional().describe("Tool names from the available list, if any")
|
|
597
|
+
});
|
|
598
|
+
var PlanSchema = z.object({
|
|
599
|
+
thought: z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),
|
|
600
|
+
steps: z.array(PlanStepSchema).min(1).max(8)
|
|
601
|
+
});
|
|
602
|
+
var createInitialPlan = async (input2, history, ctx, signal) => {
|
|
603
|
+
const validNames = new Set(ctx.toolCatalog.map((t) => t.name));
|
|
604
|
+
const catalogMode = ctx.config.toolSelectionStrategy === "plan-narrowed" ? "compact" : "full";
|
|
605
|
+
const { object, usage } = await withRetry(
|
|
606
|
+
() => streamPlanOnce(input2, history, catalogMode, ctx, signal),
|
|
607
|
+
{
|
|
608
|
+
maxRetries: ctx.config.llmMaxRetries ?? 2,
|
|
609
|
+
signal,
|
|
610
|
+
onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "plan", attempt, error: err.message })
|
|
611
|
+
}
|
|
612
|
+
);
|
|
613
|
+
ctx.emit({ type: "usage", phase: "plan", usage });
|
|
614
|
+
return {
|
|
615
|
+
thought: object.thought,
|
|
616
|
+
steps: object.steps.map((s) => {
|
|
617
|
+
if (!s.suggestedTools?.length) {
|
|
618
|
+
return s;
|
|
619
|
+
}
|
|
620
|
+
const filtered = s.suggestedTools.filter((n) => validNames.has(n));
|
|
621
|
+
const dropped = s.suggestedTools.length - filtered.length;
|
|
622
|
+
if (dropped > 0) {
|
|
623
|
+
ctx.emit({
|
|
624
|
+
type: "log",
|
|
625
|
+
level: "warn",
|
|
626
|
+
message: `[plan] step "${s.id}" had ${dropped} unknown suggestedTools, stripped`
|
|
627
|
+
});
|
|
628
|
+
}
|
|
629
|
+
if (filtered.length === 0) {
|
|
630
|
+
ctx.emit({
|
|
631
|
+
type: "log",
|
|
632
|
+
level: "warn",
|
|
633
|
+
message: `[plan] step "${s.id}" had no valid suggestedTools left; falling back to full toolset`
|
|
634
|
+
});
|
|
635
|
+
return { ...s, suggestedTools: void 0, requiresTools: true };
|
|
636
|
+
}
|
|
637
|
+
return { ...s, suggestedTools: filtered };
|
|
638
|
+
})
|
|
639
|
+
};
|
|
640
|
+
};
|
|
641
|
+
var streamPlanOnce = async (input2, history, catalogMode, ctx, signal) => {
|
|
642
|
+
const result = streamObject({
|
|
643
|
+
model: ctx.plannerModel,
|
|
644
|
+
schema: PlanSchema,
|
|
645
|
+
system: ctx.config.systemPrompt ? `${buildPlannerSystem(catalogMode)}
|
|
646
|
+
|
|
647
|
+
Domain context:
|
|
648
|
+
${ctx.config.systemPrompt}` : buildPlannerSystem(catalogMode),
|
|
649
|
+
prompt: buildPlannerUserPrompt(input2, ctx.toolCatalog, history, catalogMode),
|
|
650
|
+
abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
|
|
651
|
+
});
|
|
652
|
+
let lastThought = "";
|
|
653
|
+
let warnedRewrite = false;
|
|
654
|
+
for await (const partial of result.partialObjectStream) {
|
|
655
|
+
const t = partial?.thought;
|
|
656
|
+
if (typeof t !== "string" || t === lastThought) {
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
if (t.startsWith(lastThought)) {
|
|
660
|
+
ctx.emit({ type: "plan.thought-delta", delta: t.slice(lastThought.length) });
|
|
661
|
+
} else if (!warnedRewrite) {
|
|
662
|
+
ctx.emit({
|
|
663
|
+
type: "log",
|
|
664
|
+
level: "warn",
|
|
665
|
+
message: "[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"
|
|
666
|
+
});
|
|
667
|
+
warnedRewrite = true;
|
|
668
|
+
}
|
|
669
|
+
lastThought = t;
|
|
670
|
+
}
|
|
671
|
+
const [object, rawUsage] = await Promise.all([result.object, result.usage]);
|
|
672
|
+
return {
|
|
673
|
+
object,
|
|
674
|
+
usage: {
|
|
675
|
+
inputTokens: rawUsage.inputTokens ?? 0,
|
|
676
|
+
outputTokens: rawUsage.outputTokens ?? 0,
|
|
677
|
+
totalTokens: rawUsage.totalTokens ?? 0
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
};
|
|
681
|
+
var DecisionSchema = z.discriminatedUnion("mode", [
|
|
682
|
+
z.object({
|
|
683
|
+
mode: z.literal("continue"),
|
|
684
|
+
reason: z.string().min(1).describe("Why the next step is still appropriate")
|
|
685
|
+
}),
|
|
686
|
+
z.object({
|
|
687
|
+
mode: z.literal("finish"),
|
|
688
|
+
reason: z.string().min(1).describe("Why no more steps are needed")
|
|
689
|
+
}),
|
|
690
|
+
z.object({
|
|
691
|
+
mode: z.literal("revise"),
|
|
692
|
+
reason: z.string().min(1).describe("Why the plan must change"),
|
|
693
|
+
newPlan: PlanSchema.describe("Plan covering ONLY the remaining work")
|
|
694
|
+
})
|
|
695
|
+
]);
|
|
696
|
+
var decideNextAction = async (input2, plan, trace, nextStep, ctx, signal) => {
|
|
697
|
+
const catalogMode = ctx.config.toolSelectionStrategy === "plan-narrowed" ? "compact" : "full";
|
|
698
|
+
const { object, usage } = await withRetry(
|
|
699
|
+
async () => {
|
|
700
|
+
const r = await generateObject({
|
|
701
|
+
model: ctx.plannerModel,
|
|
702
|
+
schema: DecisionSchema,
|
|
703
|
+
system: REPLANNER_SYSTEM,
|
|
704
|
+
prompt: buildReplannerUserPrompt(
|
|
705
|
+
input2,
|
|
706
|
+
plan,
|
|
707
|
+
trace,
|
|
708
|
+
nextStep,
|
|
709
|
+
ctx.toolCatalog,
|
|
710
|
+
catalogMode
|
|
711
|
+
),
|
|
712
|
+
abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
|
|
713
|
+
});
|
|
714
|
+
const usage2 = {
|
|
715
|
+
inputTokens: r.usage.inputTokens ?? 0,
|
|
716
|
+
outputTokens: r.usage.outputTokens ?? 0,
|
|
717
|
+
totalTokens: r.usage.totalTokens ?? 0
|
|
718
|
+
};
|
|
719
|
+
return { object: r.object, usage: usage2 };
|
|
720
|
+
},
|
|
721
|
+
{
|
|
722
|
+
maxRetries: ctx.config.llmMaxRetries ?? 2,
|
|
723
|
+
signal,
|
|
724
|
+
onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "replan", attempt, error: err.message })
|
|
725
|
+
}
|
|
726
|
+
);
|
|
727
|
+
ctx.emit({ type: "usage", phase: "replan", usage });
|
|
728
|
+
return object;
|
|
729
|
+
};
|
|
730
|
+
var synthesizeAnswer = async (input2, plan, trace, history, ctx, signal) => {
|
|
731
|
+
const { text, usage } = await withRetry(
|
|
732
|
+
() => streamOnce(input2, plan, trace, history, ctx, signal),
|
|
733
|
+
{
|
|
734
|
+
maxRetries: ctx.config.llmMaxRetries ?? 2,
|
|
735
|
+
signal,
|
|
736
|
+
onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "synthesize", attempt, error: err.message })
|
|
737
|
+
}
|
|
738
|
+
);
|
|
739
|
+
ctx.emit({ type: "usage", phase: "synthesize", usage });
|
|
740
|
+
return text;
|
|
741
|
+
};
|
|
742
|
+
var streamOnce = async (input2, plan, trace, history, ctx, signal) => {
|
|
743
|
+
const result = streamText({
|
|
744
|
+
model: ctx.synthesizerModel,
|
|
745
|
+
system: SYNTHESIZER_SYSTEM,
|
|
746
|
+
prompt: buildSynthesizerUserPrompt(input2, plan, trace, history),
|
|
747
|
+
abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
|
|
748
|
+
});
|
|
749
|
+
for await (const part of result.fullStream) {
|
|
750
|
+
if (part.type === "text-delta") {
|
|
751
|
+
if (part.text) {
|
|
752
|
+
ctx.emit({ type: "final.text-delta", delta: part.text });
|
|
753
|
+
}
|
|
754
|
+
} else if (part.type === "error") {
|
|
755
|
+
const error = part.error;
|
|
756
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
const [text, rawUsage] = await Promise.all([result.text, result.usage]);
|
|
760
|
+
return {
|
|
761
|
+
text,
|
|
762
|
+
usage: {
|
|
763
|
+
inputTokens: rawUsage.inputTokens ?? 0,
|
|
764
|
+
outputTokens: rawUsage.outputTokens ?? 0,
|
|
765
|
+
totalTokens: rawUsage.totalTokens ?? 0
|
|
766
|
+
}
|
|
767
|
+
};
|
|
768
|
+
};
|
|
769
|
+
|
|
770
|
+
// src/runner.ts
|
|
771
|
+
var shouldCallReplanner = (result) => {
|
|
772
|
+
if (result.blocked) {
|
|
773
|
+
return true;
|
|
774
|
+
}
|
|
775
|
+
if (result.toolCalls.some((c) => !c.ok)) {
|
|
776
|
+
return true;
|
|
777
|
+
}
|
|
778
|
+
return false;
|
|
779
|
+
};
|
|
780
|
+
var isAbortError = (err) => Boolean(err) && typeof err === "object" && err.name === "AbortError";
|
|
781
|
+
var runAgentLoop = async (ctx, options) => {
|
|
782
|
+
const runId = randomUUID();
|
|
783
|
+
return runContext.run({ runId, startedAt: Date.now() }, () => runAgentLoopInner(ctx, options));
|
|
784
|
+
};
|
|
785
|
+
var runAgentLoopInner = async (ctx, options) => {
|
|
786
|
+
const { input: input2, signal } = options;
|
|
787
|
+
const history = options.history ? [...options.history] : void 0;
|
|
788
|
+
const onEvent = options.onEvent ?? (() => {
|
|
789
|
+
});
|
|
790
|
+
const totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
791
|
+
const proxiedCtx = {
|
|
792
|
+
...ctx,
|
|
793
|
+
emit: (event) => {
|
|
794
|
+
if (event.type === "usage") {
|
|
795
|
+
totalUsage.inputTokens += event.usage.inputTokens;
|
|
796
|
+
totalUsage.outputTokens += event.usage.outputTokens;
|
|
797
|
+
totalUsage.totalTokens += event.usage.totalTokens;
|
|
798
|
+
}
|
|
799
|
+
const tagged = { ...event, runId: runContext.getStore()?.runId };
|
|
800
|
+
try {
|
|
801
|
+
onEvent(tagged);
|
|
802
|
+
} catch {
|
|
803
|
+
}
|
|
804
|
+
try {
|
|
805
|
+
ctx.emit(tagged);
|
|
806
|
+
} catch {
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
};
|
|
810
|
+
let plan;
|
|
811
|
+
try {
|
|
812
|
+
plan = await createInitialPlan(input2, history, proxiedCtx, signal);
|
|
813
|
+
} catch (err) {
|
|
814
|
+
proxiedCtx.emit({ type: "error", error: asError(err), phase: "plan" });
|
|
815
|
+
if (isAbortError(err) || signal?.aborted) {
|
|
816
|
+
throw err;
|
|
817
|
+
}
|
|
818
|
+
plan = {
|
|
819
|
+
thought: "Planner failed; answering directly without tool use.",
|
|
820
|
+
steps: [
|
|
821
|
+
{
|
|
822
|
+
id: "fallback",
|
|
823
|
+
description: "Answer the user directly using prior conversation and general knowledge.",
|
|
824
|
+
expectedOutcome: "A direct answer to the user request."
|
|
825
|
+
}
|
|
826
|
+
]
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
proxiedCtx.emit({ type: "plan.created", plan });
|
|
830
|
+
const trace = [];
|
|
831
|
+
let currentPlan = plan;
|
|
832
|
+
let stepIndex = 0;
|
|
833
|
+
let iterations = 0;
|
|
834
|
+
let revisions = 0;
|
|
835
|
+
const maxRevisions = ctx.config.maxRevisions ?? 2;
|
|
836
|
+
const tokenCap = ctx.config.maxTotalTokens;
|
|
837
|
+
while (iterations < ctx.config.maxIterations) {
|
|
838
|
+
iterations++;
|
|
839
|
+
if (signal?.aborted) {
|
|
840
|
+
throw new DOMException("Aborted", "AbortError");
|
|
841
|
+
}
|
|
842
|
+
if (stepIndex >= currentPlan.steps.length) {
|
|
843
|
+
break;
|
|
844
|
+
}
|
|
845
|
+
if (tokenCap && totalUsage.totalTokens >= tokenCap) {
|
|
846
|
+
proxiedCtx.emit({ type: "budget.exceeded", tokens: totalUsage.totalTokens, cap: tokenCap });
|
|
847
|
+
break;
|
|
848
|
+
}
|
|
849
|
+
const step = currentPlan.steps[stepIndex];
|
|
850
|
+
proxiedCtx.emit({ type: "step.start", step, index: stepIndex });
|
|
851
|
+
let result;
|
|
852
|
+
try {
|
|
853
|
+
result = await executeStep(input2, currentPlan, step, trace, history, proxiedCtx, signal);
|
|
854
|
+
} catch (err) {
|
|
855
|
+
proxiedCtx.emit({ type: "error", error: asError(err), phase: "execute" });
|
|
856
|
+
throw err;
|
|
857
|
+
}
|
|
858
|
+
trace.push(result);
|
|
859
|
+
proxiedCtx.emit({ type: "step.complete", step, result });
|
|
860
|
+
const nextStep = currentPlan.steps[stepIndex + 1] ?? null;
|
|
861
|
+
const isLastPlannedStep = nextStep === null;
|
|
862
|
+
if (isLastPlannedStep) {
|
|
863
|
+
proxiedCtx.emit({
|
|
864
|
+
type: "replan.decision",
|
|
865
|
+
mode: "finish",
|
|
866
|
+
reason: "last planned step reached",
|
|
867
|
+
cause: "last-step"
|
|
868
|
+
});
|
|
869
|
+
break;
|
|
870
|
+
}
|
|
871
|
+
if (!shouldCallReplanner(result)) {
|
|
872
|
+
proxiedCtx.emit({
|
|
873
|
+
type: "replan.decision",
|
|
874
|
+
mode: "continue",
|
|
875
|
+
reason: "step succeeded cleanly, skipping LLM replanner",
|
|
876
|
+
cause: "clean-step"
|
|
877
|
+
});
|
|
878
|
+
stepIndex++;
|
|
879
|
+
continue;
|
|
880
|
+
}
|
|
881
|
+
let decision;
|
|
882
|
+
try {
|
|
883
|
+
decision = await decideNextAction(input2, currentPlan, trace, nextStep, proxiedCtx, signal);
|
|
884
|
+
} catch (err) {
|
|
885
|
+
proxiedCtx.emit({ type: "error", error: asError(err), phase: "replan" });
|
|
886
|
+
throw err;
|
|
887
|
+
}
|
|
888
|
+
proxiedCtx.emit({
|
|
889
|
+
type: "replan.decision",
|
|
890
|
+
mode: decision.mode,
|
|
891
|
+
reason: decision.reason,
|
|
892
|
+
cause: "llm-decision"
|
|
893
|
+
});
|
|
894
|
+
if (decision.mode === "finish") {
|
|
895
|
+
break;
|
|
896
|
+
}
|
|
897
|
+
if (decision.mode === "revise") {
|
|
898
|
+
if (revisions >= maxRevisions) {
|
|
899
|
+
proxiedCtx.emit({ type: "revisions.exceeded", cap: maxRevisions });
|
|
900
|
+
break;
|
|
901
|
+
}
|
|
902
|
+
revisions++;
|
|
903
|
+
currentPlan = decision.newPlan;
|
|
904
|
+
proxiedCtx.emit({ type: "plan.revised", plan: currentPlan, reason: decision.reason });
|
|
905
|
+
stepIndex = 0;
|
|
906
|
+
continue;
|
|
907
|
+
}
|
|
908
|
+
stepIndex++;
|
|
909
|
+
}
|
|
910
|
+
let text;
|
|
911
|
+
try {
|
|
912
|
+
text = await synthesizeAnswer(input2, currentPlan, trace, history, proxiedCtx, signal);
|
|
913
|
+
} catch (err) {
|
|
914
|
+
proxiedCtx.emit({ type: "error", error: asError(err), phase: "synthesize" });
|
|
915
|
+
throw err;
|
|
916
|
+
}
|
|
917
|
+
proxiedCtx.emit({ type: "final", text });
|
|
918
|
+
return { text, plan: currentPlan, trace, iterations, usage: totalUsage };
|
|
919
|
+
};
|
|
920
|
+
var asError = (err) => err instanceof Error ? err : new Error(typeof err === "string" ? err : JSON.stringify(err));
|
|
921
|
+
|
|
922
|
+
// src/index.ts
|
|
923
|
+
var LEVEL_RANK = {
|
|
924
|
+
none: 0,
|
|
925
|
+
error: 1,
|
|
926
|
+
warn: 2,
|
|
927
|
+
info: 3,
|
|
928
|
+
debug: 4
|
|
929
|
+
};
|
|
930
|
+
var createAgent = async (config, baseEventHandler) => {
|
|
931
|
+
const debugMode = LEVEL_RANK[config.logLevel] >= LEVEL_RANK.debug;
|
|
932
|
+
const emit = (event) => {
|
|
933
|
+
if (baseEventHandler) {
|
|
934
|
+
try {
|
|
935
|
+
baseEventHandler(event);
|
|
936
|
+
} catch (err) {
|
|
937
|
+
if (debugMode) {
|
|
938
|
+
console.error("[agent] event handler threw:", err);
|
|
939
|
+
}
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
};
|
|
943
|
+
const log = (level, message) => {
|
|
944
|
+
if (LEVEL_RANK[config.logLevel] >= LEVEL_RANK[level]) {
|
|
945
|
+
emit({ type: "log", level, message });
|
|
946
|
+
}
|
|
947
|
+
};
|
|
948
|
+
const connect = async () => {
|
|
949
|
+
const c = await connectMcpServers(
|
|
950
|
+
config.mcpServers,
|
|
951
|
+
log,
|
|
952
|
+
config.clientName,
|
|
953
|
+
config.outputSanitizer
|
|
954
|
+
);
|
|
955
|
+
const f = filterTools(c.tools, c.catalog, config.availableTools, config.excludedTools);
|
|
956
|
+
return { connection: c, tools: f.tools, catalog: f.catalog };
|
|
957
|
+
};
|
|
958
|
+
let connected;
|
|
959
|
+
try {
|
|
960
|
+
connected = await connect();
|
|
961
|
+
} catch (err) {
|
|
962
|
+
emit({
|
|
963
|
+
type: "error",
|
|
964
|
+
error: err instanceof Error ? err : new Error(String(err)),
|
|
965
|
+
phase: "init"
|
|
966
|
+
});
|
|
967
|
+
throw err;
|
|
968
|
+
}
|
|
969
|
+
const configuredServers = Object.keys(config.mcpServers).length;
|
|
970
|
+
if (config.failOnNoTools && configuredServers > 0) {
|
|
971
|
+
const anyConnected = connected.connection.results.some((r) => r.connected);
|
|
972
|
+
if (!anyConnected) {
|
|
973
|
+
const reasons = connected.connection.results.filter((r) => !r.connected).map((r) => `${r.name}: ${r.error ?? "unknown"}`).join("; ");
|
|
974
|
+
await connected.connection.close().catch(() => {
|
|
975
|
+
});
|
|
976
|
+
const err = new Error(
|
|
977
|
+
`All ${configuredServers} configured MCP server(s) failed to connect [${reasons}]`
|
|
978
|
+
);
|
|
979
|
+
emit({ type: "error", error: err, phase: "init" });
|
|
980
|
+
throw err;
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
const executorModel = buildModel(config, config.model);
|
|
984
|
+
const plannerModel = buildModel(config, config.plannerModel ?? config.model);
|
|
985
|
+
const synthesizerModel = buildModel(config, config.synthesizerModel ?? config.model);
|
|
986
|
+
const ctx = {
|
|
987
|
+
config,
|
|
988
|
+
executorModel,
|
|
989
|
+
plannerModel,
|
|
990
|
+
synthesizerModel,
|
|
991
|
+
tools: connected.tools,
|
|
992
|
+
toolCatalog: connected.catalog.map((c) => ({ name: c.name, description: c.description })),
|
|
993
|
+
emit
|
|
994
|
+
};
|
|
995
|
+
let activeRuns = 0;
|
|
996
|
+
let closed = false;
|
|
997
|
+
let reconnecting = false;
|
|
998
|
+
return {
|
|
999
|
+
run: async (options) => {
|
|
1000
|
+
if (closed) {
|
|
1001
|
+
throw new Error("Agent is closed");
|
|
1002
|
+
}
|
|
1003
|
+
if (reconnecting) {
|
|
1004
|
+
throw new Error("Agent is reconnecting; retry shortly");
|
|
1005
|
+
}
|
|
1006
|
+
activeRuns++;
|
|
1007
|
+
try {
|
|
1008
|
+
return await runAgentLoop(ctx, options);
|
|
1009
|
+
} finally {
|
|
1010
|
+
activeRuns--;
|
|
1011
|
+
}
|
|
1012
|
+
},
|
|
1013
|
+
listTools: () => ctx.toolCatalog.slice(),
|
|
1014
|
+
reconnect: async () => {
|
|
1015
|
+
if (closed) {
|
|
1016
|
+
throw new Error("Agent is closed");
|
|
1017
|
+
}
|
|
1018
|
+
if (reconnecting) {
|
|
1019
|
+
throw new Error("Already reconnecting");
|
|
1020
|
+
}
|
|
1021
|
+
if (activeRuns > 0) {
|
|
1022
|
+
throw new Error(`Cannot reconnect with ${activeRuns} active run(s)`);
|
|
1023
|
+
}
|
|
1024
|
+
reconnecting = true;
|
|
1025
|
+
try {
|
|
1026
|
+
const oldConnection = connected.connection;
|
|
1027
|
+
const fresh = await connect();
|
|
1028
|
+
for (const k of Object.keys(ctx.tools)) {
|
|
1029
|
+
delete ctx.tools[k];
|
|
1030
|
+
}
|
|
1031
|
+
Object.assign(ctx.tools, fresh.tools);
|
|
1032
|
+
ctx.toolCatalog = fresh.catalog.map((c) => ({ name: c.name, description: c.description }));
|
|
1033
|
+
connected = fresh;
|
|
1034
|
+
await oldConnection.close().catch(() => {
|
|
1035
|
+
});
|
|
1036
|
+
} finally {
|
|
1037
|
+
reconnecting = false;
|
|
1038
|
+
}
|
|
1039
|
+
},
|
|
1040
|
+
close: async (options) => {
|
|
1041
|
+
closed = true;
|
|
1042
|
+
const waitForRuns = options?.waitForRuns ?? false;
|
|
1043
|
+
const timeoutMs = options?.timeoutMs ?? 3e4;
|
|
1044
|
+
if (waitForRuns && activeRuns > 0) {
|
|
1045
|
+
const start = Date.now();
|
|
1046
|
+
while (activeRuns > 0 && Date.now() - start < timeoutMs) {
|
|
1047
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
if (activeRuns > 0) {
|
|
1051
|
+
emit({
|
|
1052
|
+
type: "log",
|
|
1053
|
+
level: "warn",
|
|
1054
|
+
message: `[agent] close called with ${activeRuns} active run(s); they will fail mid-flight`
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
await connected.connection.close().catch(() => {
|
|
1058
|
+
});
|
|
1059
|
+
},
|
|
1060
|
+
activeRuns: () => activeRuns
|
|
1061
|
+
};
|
|
1062
|
+
};
|
|
1063
|
+
|
|
1064
|
+
// src/cli/config.ts
|
|
1065
|
+
var PROVIDERS = ["openai", "anthropic", "openai-compatible", "google"];
|
|
1066
|
+
var LOG_LEVELS = ["none", "error", "warn", "info", "debug"];
|
|
1067
|
+
var TOOL_STRATEGIES = ["all", "plan-narrowed"];
|
|
1068
|
+
var loadConfig = () => {
|
|
1069
|
+
const providerType = process.env.AGENT_PROVIDER_TYPE ?? "openai";
|
|
1070
|
+
if (!PROVIDERS.includes(providerType)) {
|
|
1071
|
+
throw new Error(`AGENT_PROVIDER_TYPE must be ${PROVIDERS.join(" | ")}, got: ${providerType}`);
|
|
1072
|
+
}
|
|
1073
|
+
const logLevel = process.env.AGENT_LOG_LEVEL ?? "info";
|
|
1074
|
+
if (!LOG_LEVELS.includes(logLevel)) {
|
|
1075
|
+
throw new Error(`AGENT_LOG_LEVEL must be ${LOG_LEVELS.join(" | ")}, got: ${logLevel}`);
|
|
1076
|
+
}
|
|
1077
|
+
const baseURL = providerType === "openai-compatible" ? required("AGENT_BASE_URL") : process.env.AGENT_BASE_URL?.trim() || void 0;
|
|
1078
|
+
return {
|
|
1079
|
+
clientName: process.env.AGENT_CLIENT_NAME ?? "vercel-mcp-test",
|
|
1080
|
+
providerType,
|
|
1081
|
+
baseURL,
|
|
1082
|
+
apiKey: required("AGENT_API_KEY"),
|
|
1083
|
+
model: required("AGENT_MODEL"),
|
|
1084
|
+
plannerModel: process.env.AGENT_PLANNER_MODEL?.trim() || void 0,
|
|
1085
|
+
synthesizerModel: process.env.AGENT_SYNTHESIZER_MODEL?.trim() || void 0,
|
|
1086
|
+
mcpServers: parseMcpServers(process.env.MCP_SERVERS),
|
|
1087
|
+
availableTools: parseList(process.env.AGENT_AVAILABLE_TOOLS),
|
|
1088
|
+
excludedTools: parseList(process.env.AGENT_EXCLUDED_TOOLS),
|
|
1089
|
+
maxIterations: parsePositiveInt(process.env.AGENT_MAX_ITERATIONS, 10),
|
|
1090
|
+
maxStepsPerTask: parsePositiveInt(process.env.AGENT_MAX_STEPS_PER_TASK, 8),
|
|
1091
|
+
maxRevisions: parseOptionalInt(process.env.AGENT_MAX_REVISIONS),
|
|
1092
|
+
maxTotalTokens: parseOptionalInt(process.env.AGENT_MAX_TOTAL_TOKENS),
|
|
1093
|
+
llmTimeoutMs: parseOptionalInt(process.env.AGENT_LLM_TIMEOUT_MS),
|
|
1094
|
+
llmMaxRetries: parseOptionalInt(process.env.AGENT_LLM_MAX_RETRIES),
|
|
1095
|
+
toolSelectionStrategy: parseToolStrategy(process.env.AGENT_TOOL_SELECTION_STRATEGY),
|
|
1096
|
+
logLevel
|
|
1097
|
+
};
|
|
1098
|
+
};
|
|
1099
|
+
var parseToolStrategy = (raw) => {
|
|
1100
|
+
const v = raw?.trim();
|
|
1101
|
+
if (!v) {
|
|
1102
|
+
return void 0;
|
|
1103
|
+
}
|
|
1104
|
+
if (!TOOL_STRATEGIES.includes(v)) {
|
|
1105
|
+
throw new Error(
|
|
1106
|
+
`AGENT_TOOL_SELECTION_STRATEGY must be ${TOOL_STRATEGIES.join(" | ")}, got: ${v}`
|
|
1107
|
+
);
|
|
1108
|
+
}
|
|
1109
|
+
return v;
|
|
1110
|
+
};
|
|
1111
|
+
var parseOptionalInt = (raw) => {
|
|
1112
|
+
if (!raw?.trim()) {
|
|
1113
|
+
return void 0;
|
|
1114
|
+
}
|
|
1115
|
+
const n = Number(raw);
|
|
1116
|
+
if (!Number.isFinite(n) || n < 0) {
|
|
1117
|
+
throw new Error(`Expected non-negative number, got: ${raw}`);
|
|
1118
|
+
}
|
|
1119
|
+
return Math.floor(n);
|
|
1120
|
+
};
|
|
1121
|
+
var required = (name) => {
|
|
1122
|
+
const v = process.env[name]?.trim();
|
|
1123
|
+
if (!v) {
|
|
1124
|
+
throw new Error(`Missing required env var: ${name}`);
|
|
1125
|
+
}
|
|
1126
|
+
return v;
|
|
1127
|
+
};
|
|
1128
|
+
var parseList = (raw) => {
|
|
1129
|
+
const t = raw?.trim();
|
|
1130
|
+
if (!t) {
|
|
1131
|
+
return void 0;
|
|
1132
|
+
}
|
|
1133
|
+
return t.split(",").map((s) => s.trim()).filter(Boolean);
|
|
1134
|
+
};
|
|
1135
|
+
var parsePositiveInt = (raw, fallback) => {
|
|
1136
|
+
if (!raw?.trim()) {
|
|
1137
|
+
return fallback;
|
|
1138
|
+
}
|
|
1139
|
+
const n = Number(raw);
|
|
1140
|
+
if (!Number.isFinite(n) || n <= 0) {
|
|
1141
|
+
throw new Error(`Expected positive number, got: ${raw}`);
|
|
1142
|
+
}
|
|
1143
|
+
return Math.floor(n);
|
|
1144
|
+
};
|
|
1145
|
+
var parseMcpServers = (raw) => {
|
|
1146
|
+
if (!raw?.trim()) {
|
|
1147
|
+
return {};
|
|
1148
|
+
}
|
|
1149
|
+
let parsed;
|
|
1150
|
+
try {
|
|
1151
|
+
parsed = JSON.parse(raw);
|
|
1152
|
+
} catch (err) {
|
|
1153
|
+
throw new Error(`MCP_SERVERS must be valid JSON: ${err.message}`);
|
|
1154
|
+
}
|
|
1155
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
1156
|
+
throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? }>");
|
|
1157
|
+
}
|
|
1158
|
+
const result = {};
|
|
1159
|
+
for (const [name, value] of Object.entries(parsed)) {
|
|
1160
|
+
if (!value || typeof value !== "object") {
|
|
1161
|
+
throw new Error(`MCP_SERVERS.${name} must be an object`);
|
|
1162
|
+
}
|
|
1163
|
+
const v = value;
|
|
1164
|
+
if (typeof v.url !== "string" || !v.url) {
|
|
1165
|
+
throw new Error(`MCP_SERVERS.${name}.url must be a non-empty string`);
|
|
1166
|
+
}
|
|
1167
|
+
const headers = v.headers && typeof v.headers === "object" && !Array.isArray(v.headers) ? v.headers : void 0;
|
|
1168
|
+
result[name] = { url: v.url, headers };
|
|
1169
|
+
}
|
|
1170
|
+
return result;
|
|
1171
|
+
};
|
|
1172
|
+
|
|
1173
|
+
// src/cli/run.ts
|
|
1174
|
+
var HISTORY_LIMIT = 16;
|
|
1175
|
+
var truncate = (s, n = 240) => {
|
|
1176
|
+
const flat = s.replace(/\s+/g, " ").trim();
|
|
1177
|
+
return flat.length > n ? `${flat.slice(0, n)}...` : flat;
|
|
1178
|
+
};
|
|
1179
|
+
var formatJson = (v) => {
|
|
1180
|
+
try {
|
|
1181
|
+
return truncate(JSON.stringify(v));
|
|
1182
|
+
} catch {
|
|
1183
|
+
return String(v);
|
|
1184
|
+
}
|
|
1185
|
+
};
|
|
1186
|
+
var runRepl = async () => {
|
|
1187
|
+
const config = loadConfig();
|
|
1188
|
+
const mcpNames = Object.keys(config.mcpServers);
|
|
1189
|
+
console.log(
|
|
1190
|
+
`[session] model=${config.model} planner=${config.plannerModel ?? config.model} synth=${config.synthesizerModel ?? config.model} provider=${config.providerType}`
|
|
1191
|
+
);
|
|
1192
|
+
console.log(
|
|
1193
|
+
`[session] maxIterations=${config.maxIterations} maxStepsPerTask=${config.maxStepsPerTask} timeoutMs=${config.llmTimeoutMs ?? "none"} retries=${config.llmMaxRetries ?? 2}`
|
|
1194
|
+
);
|
|
1195
|
+
console.log(`[mcp] servers=${mcpNames.length ? mcpNames.join(", ") : "(none)"}`);
|
|
1196
|
+
console.log("[hint] commands: /status, /tools, /history, /reset, /reconnect, /exit\n");
|
|
1197
|
+
let streamingFinal = false;
|
|
1198
|
+
let streamingThought = false;
|
|
1199
|
+
const onEvent = (event) => {
|
|
1200
|
+
switch (event.type) {
|
|
1201
|
+
case "log":
|
|
1202
|
+
console.log(`[${event.level}] ${event.message}`);
|
|
1203
|
+
break;
|
|
1204
|
+
case "plan.thought-delta":
|
|
1205
|
+
if (!streamingThought) {
|
|
1206
|
+
process.stdout.write("\n[plan] ");
|
|
1207
|
+
streamingThought = true;
|
|
1208
|
+
}
|
|
1209
|
+
process.stdout.write(event.delta);
|
|
1210
|
+
break;
|
|
1211
|
+
case "plan.created":
|
|
1212
|
+
if (streamingThought) {
|
|
1213
|
+
process.stdout.write("\n");
|
|
1214
|
+
streamingThought = false;
|
|
1215
|
+
} else {
|
|
1216
|
+
console.log(`
|
|
1217
|
+
[plan] ${event.plan.thought}`);
|
|
1218
|
+
}
|
|
1219
|
+
for (const [i, s] of event.plan.steps.entries()) {
|
|
1220
|
+
const tools2 = s.suggestedTools?.length ? ` (tools: ${s.suggestedTools.join(", ")})` : "";
|
|
1221
|
+
console.log(` ${i + 1}. ${s.description}${tools2}`);
|
|
1222
|
+
}
|
|
1223
|
+
break;
|
|
1224
|
+
case "plan.revised":
|
|
1225
|
+
console.log(`
|
|
1226
|
+
[replan] reason=${event.reason}`);
|
|
1227
|
+
for (const [i, s] of event.plan.steps.entries()) {
|
|
1228
|
+
console.log(` ${i + 1}. ${s.description}`);
|
|
1229
|
+
}
|
|
1230
|
+
break;
|
|
1231
|
+
case "step.start":
|
|
1232
|
+
console.log(`
|
|
1233
|
+
[step ${event.index + 1}] ${event.step.description}`);
|
|
1234
|
+
break;
|
|
1235
|
+
case "step.tool-call":
|
|
1236
|
+
console.log(` -> ${event.name} ${formatJson(event.input)}`);
|
|
1237
|
+
break;
|
|
1238
|
+
case "step.tool-result": {
|
|
1239
|
+
const status = event.ok ? "ok" : "fail";
|
|
1240
|
+
console.log(` <- ${event.name} ${status} ${formatJson(event.output)}`);
|
|
1241
|
+
break;
|
|
1242
|
+
}
|
|
1243
|
+
case "step.complete":
|
|
1244
|
+
console.log(
|
|
1245
|
+
` = ${truncate(event.result.summary, 400)} (${event.result.durationMs}ms, ${event.result.toolCalls.length} tool calls)`
|
|
1246
|
+
);
|
|
1247
|
+
break;
|
|
1248
|
+
case "replan.decision":
|
|
1249
|
+
if (event.mode !== "continue") {
|
|
1250
|
+
console.log(`[replan] ${event.mode} (${event.cause}): ${event.reason}`);
|
|
1251
|
+
}
|
|
1252
|
+
break;
|
|
1253
|
+
case "usage":
|
|
1254
|
+
break;
|
|
1255
|
+
case "retry":
|
|
1256
|
+
if (event.phase === "plan" && streamingThought) {
|
|
1257
|
+
process.stdout.write("\n");
|
|
1258
|
+
streamingThought = false;
|
|
1259
|
+
}
|
|
1260
|
+
console.log(`[retry] ${event.phase} attempt=${event.attempt}: ${event.error}`);
|
|
1261
|
+
break;
|
|
1262
|
+
case "budget.exceeded":
|
|
1263
|
+
console.log(`[budget] token cap reached: ${event.tokens}/${event.cap} - finishing early`);
|
|
1264
|
+
break;
|
|
1265
|
+
case "revisions.exceeded":
|
|
1266
|
+
console.log(`[budget] max ${event.cap} replan-revisions reached - finishing early`);
|
|
1267
|
+
break;
|
|
1268
|
+
case "final.text-delta":
|
|
1269
|
+
if (!streamingFinal) {
|
|
1270
|
+
process.stdout.write("\nassistant> ");
|
|
1271
|
+
streamingFinal = true;
|
|
1272
|
+
}
|
|
1273
|
+
process.stdout.write(event.delta);
|
|
1274
|
+
break;
|
|
1275
|
+
case "final":
|
|
1276
|
+
if (streamingFinal) {
|
|
1277
|
+
process.stdout.write("\n\n");
|
|
1278
|
+
streamingFinal = false;
|
|
1279
|
+
} else {
|
|
1280
|
+
console.log(`
|
|
1281
|
+
assistant> ${event.text}
|
|
1282
|
+
`);
|
|
1283
|
+
}
|
|
1284
|
+
break;
|
|
1285
|
+
case "error":
|
|
1286
|
+
if (event.phase === "plan" && streamingThought) {
|
|
1287
|
+
process.stdout.write("\n");
|
|
1288
|
+
streamingThought = false;
|
|
1289
|
+
}
|
|
1290
|
+
console.error(`[error] (${event.phase}) ${event.error.message}`);
|
|
1291
|
+
break;
|
|
1292
|
+
}
|
|
1293
|
+
};
|
|
1294
|
+
const agent = await createAgent(config, onEvent);
|
|
1295
|
+
const tools = agent.listTools();
|
|
1296
|
+
console.log(
|
|
1297
|
+
`[tools] available=${tools.length}${tools.length ? `: ${tools.map((t) => t.name).join(", ")}` : ""}`
|
|
1298
|
+
);
|
|
1299
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
1300
|
+
const history = [];
|
|
1301
|
+
let abortController = null;
|
|
1302
|
+
const onSigInt = () => {
|
|
1303
|
+
if (abortController) {
|
|
1304
|
+
console.log("\n[abort] cancelling current run...");
|
|
1305
|
+
abortController.abort();
|
|
1306
|
+
} else {
|
|
1307
|
+
rl.close();
|
|
1308
|
+
}
|
|
1309
|
+
};
|
|
1310
|
+
process.on("SIGINT", onSigInt);
|
|
1311
|
+
try {
|
|
1312
|
+
while (true) {
|
|
1313
|
+
let prompt;
|
|
1314
|
+
try {
|
|
1315
|
+
prompt = (await rl.question("\nyou> ")).trim();
|
|
1316
|
+
} catch {
|
|
1317
|
+
break;
|
|
1318
|
+
}
|
|
1319
|
+
if (!prompt) {
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
if (prompt === "/exit" || prompt === "/quit") {
|
|
1323
|
+
break;
|
|
1324
|
+
}
|
|
1325
|
+
if (prompt === "/tools") {
|
|
1326
|
+
if (tools.length === 0) {
|
|
1327
|
+
console.log("[tools] (none)");
|
|
1328
|
+
} else {
|
|
1329
|
+
for (const t of tools) {
|
|
1330
|
+
console.log(` - ${t.name}: ${truncate(t.description, 200)}`);
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
if (prompt === "/status") {
|
|
1336
|
+
console.log(`[status] model=${config.model} planner=${config.plannerModel ?? config.model}`);
|
|
1337
|
+
console.log(
|
|
1338
|
+
`[status] tools=${tools.length} mcp=${mcpNames.join(", ") || "(none)"} historyTurns=${history.length}`
|
|
1339
|
+
);
|
|
1340
|
+
continue;
|
|
1341
|
+
}
|
|
1342
|
+
if (prompt === "/history") {
|
|
1343
|
+
if (history.length === 0) {
|
|
1344
|
+
console.log("[history] (empty)");
|
|
1345
|
+
} else {
|
|
1346
|
+
for (const t of history) {
|
|
1347
|
+
console.log(` ${t.role}: ${truncate(t.content, 200)}`);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
continue;
|
|
1351
|
+
}
|
|
1352
|
+
if (prompt === "/reset") {
|
|
1353
|
+
history.length = 0;
|
|
1354
|
+
console.log("[history] cleared");
|
|
1355
|
+
continue;
|
|
1356
|
+
}
|
|
1357
|
+
if (prompt === "/reconnect") {
|
|
1358
|
+
try {
|
|
1359
|
+
await agent.reconnect();
|
|
1360
|
+
const fresh = agent.listTools();
|
|
1361
|
+
tools.length = 0;
|
|
1362
|
+
for (const t of fresh) {
|
|
1363
|
+
tools.push(t);
|
|
1364
|
+
}
|
|
1365
|
+
console.log(`[mcp] reconnected, ${tools.length} tools available`);
|
|
1366
|
+
} catch (err) {
|
|
1367
|
+
console.error("[error] reconnect failed:", err.message);
|
|
1368
|
+
}
|
|
1369
|
+
continue;
|
|
1370
|
+
}
|
|
1371
|
+
streamingFinal = false;
|
|
1372
|
+
streamingThought = false;
|
|
1373
|
+
abortController = new AbortController();
|
|
1374
|
+
try {
|
|
1375
|
+
const result = await agent.run({
|
|
1376
|
+
input: prompt,
|
|
1377
|
+
history,
|
|
1378
|
+
signal: abortController.signal
|
|
1379
|
+
});
|
|
1380
|
+
history.push({ role: "user", content: prompt });
|
|
1381
|
+
history.push({ role: "assistant", content: result.text });
|
|
1382
|
+
while (history.length > HISTORY_LIMIT) {
|
|
1383
|
+
history.shift();
|
|
1384
|
+
}
|
|
1385
|
+
console.log(
|
|
1386
|
+
`[meta] iterations=${result.iterations} steps=${result.trace.length} tokens=${result.usage.totalTokens} (in=${result.usage.inputTokens} out=${result.usage.outputTokens})`
|
|
1387
|
+
);
|
|
1388
|
+
} catch (err) {
|
|
1389
|
+
if (err?.name === "AbortError") {
|
|
1390
|
+
console.log("[abort] run cancelled");
|
|
1391
|
+
} else {
|
|
1392
|
+
console.error("[error]", err.message);
|
|
1393
|
+
}
|
|
1394
|
+
} finally {
|
|
1395
|
+
abortController = null;
|
|
1396
|
+
}
|
|
1397
|
+
}
|
|
1398
|
+
} finally {
|
|
1399
|
+
process.off("SIGINT", onSigInt);
|
|
1400
|
+
rl.close();
|
|
1401
|
+
await agent.close().catch((err) => console.error("[cleanup] agent", err));
|
|
1402
|
+
}
|
|
1403
|
+
};
|
|
1404
|
+
|
|
1405
|
+
// src/cli/start.ts
|
|
1406
|
+
var main = async () => {
|
|
1407
|
+
let args;
|
|
1408
|
+
try {
|
|
1409
|
+
args = parseCliArgs(process.argv.slice(2));
|
|
1410
|
+
} catch (err) {
|
|
1411
|
+
console.error(err.message);
|
|
1412
|
+
console.error("\nRun `dd-agent --help` for usage.");
|
|
1413
|
+
process.exit(2);
|
|
1414
|
+
}
|
|
1415
|
+
if (args.help) {
|
|
1416
|
+
process.stdout.write(HELP);
|
|
1417
|
+
return;
|
|
1418
|
+
}
|
|
1419
|
+
if (args.envFile) {
|
|
1420
|
+
try {
|
|
1421
|
+
process.loadEnvFile(args.envFile);
|
|
1422
|
+
} catch (err) {
|
|
1423
|
+
console.error(`Failed to load env file ${args.envFile}: ${err.message}`);
|
|
1424
|
+
process.exit(2);
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
try {
|
|
1428
|
+
await runRepl();
|
|
1429
|
+
} catch (err) {
|
|
1430
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1431
|
+
if (msg.startsWith("Missing required env var")) {
|
|
1432
|
+
console.error(
|
|
1433
|
+
`${msg}
|
|
1434
|
+
|
|
1435
|
+
Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`
|
|
1436
|
+
);
|
|
1437
|
+
process.exit(2);
|
|
1438
|
+
}
|
|
1439
|
+
throw err;
|
|
1440
|
+
}
|
|
1441
|
+
};
|
|
1442
|
+
main().catch((err) => {
|
|
1443
|
+
console.error(err);
|
|
1444
|
+
process.exit(1);
|
|
1445
|
+
});
|
|
1446
|
+
//# sourceMappingURL=cli.js.map
|
|
1447
|
+
//# sourceMappingURL=cli.js.map
|