@dudko.dev/agent 0.0.1 → 0.0.3
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/README.md +68 -4
- package/dist/cli.js +74 -1404
- package/dist/index.cjs +39 -1023
- package/dist/index.d.cts +61 -2
- package/dist/index.d.ts +61 -2
- package/dist/index.js +39 -1019
- package/package.json +25 -2
- package/dist/cli.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -1,274 +1,43 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
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]
|
|
2
|
+
import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {dynamicTool,jsonSchema,generateObject,streamObject,streamText,stepCountIs}from'ai';import {randomUUID}from'crypto';import {rm,mkdir,writeFile}from'fs/promises';import Pe from'path';import {URL}from'url';import {AsyncLocalStorage}from'async_hooks';import {SpanStatusCode,trace}from'@opentelemetry/api';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {createOpenAI}from'@ai-sdk/openai';import {createOpenAICompatible}from'@ai-sdk/openai-compatible';import {tmpdir}from'os';import {z as z$1}from'zod';var Ke=Object.defineProperty;var i=(e,t)=>Ke(e,"name",{value:t,configurable:true});var le=`Usage: dd-agent [options]
|
|
18
3
|
|
|
19
4
|
Options:
|
|
20
|
-
--env-file=<path>
|
|
21
|
-
|
|
5
|
+
--env-file=<path> Load env vars from a dotenv file before starting
|
|
6
|
+
--provider=<type> AGENT_PROVIDER_TYPE (openai|anthropic|google|openai-compatible)
|
|
7
|
+
--model=<id> AGENT_MODEL
|
|
8
|
+
--planner-model=<id> AGENT_PLANNER_MODEL
|
|
9
|
+
--synthesizer-model=<id> AGENT_SYNTHESIZER_MODEL
|
|
10
|
+
--base-url=<url> AGENT_BASE_URL
|
|
11
|
+
--log-level=<level> AGENT_LOG_LEVEL (none|error|warn|info|debug)
|
|
12
|
+
--max-iterations=<n> AGENT_MAX_ITERATIONS
|
|
13
|
+
--max-steps-per-task=<n> AGENT_MAX_STEPS_PER_TASK
|
|
14
|
+
--tool-strategy=<v> AGENT_TOOL_SELECTION_STRATEGY (all|plan-narrowed)
|
|
15
|
+
-h, --help Show this help
|
|
16
|
+
|
|
17
|
+
API keys are still read from env (AGENT_API_KEY etc.) - we deliberately do
|
|
18
|
+
not accept them as flags so they don't end up in shell history.
|
|
22
19
|
|
|
23
20
|
Required env vars (set directly or via --env-file):
|
|
24
21
|
AGENT_PROVIDER_TYPE one of: openai | anthropic | openai-compatible | google
|
|
25
22
|
AGENT_API_KEY provider API key
|
|
26
23
|
AGENT_MODEL model id
|
|
27
|
-
MCP_SERVERS JSON: { "<name>": { "url": "...", "headers"?: {...} } }
|
|
24
|
+
MCP_SERVERS JSON: { "<name>": { "url": "...", "headers"?: {...} } | { "command": "...", "args"?: [], "env"?: {} } }
|
|
28
25
|
|
|
29
26
|
Commands inside the REPL:
|
|
30
27
|
/status, /tools, /history, /reset, /reconnect, /exit
|
|
31
|
-
`;
|
|
32
|
-
var
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
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.
|
|
28
|
+
`,He={provider:"AGENT_PROVIDER_TYPE",model:"AGENT_MODEL","planner-model":"AGENT_PLANNER_MODEL","synthesizer-model":"AGENT_SYNTHESIZER_MODEL","base-url":"AGENT_BASE_URL","log-level":"AGENT_LOG_LEVEL","max-iterations":"AGENT_MAX_ITERATIONS","max-steps-per-task":"AGENT_MAX_STEPS_PER_TASK","tool-strategy":"AGENT_TOOL_SELECTION_STRATEGY"},ce=i(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"},provider:{type:"string"},model:{type:"string"},"planner-model":{type:"string"},"synthesizer-model":{type:"string"},"base-url":{type:"string"},"log-level":{type:"string"},"max-iterations":{type:"string"},"max-steps-per-task":{type:"string"},"tool-strategy":{type:"string"}},strict:true,allowPositionals:false}),o={},n=t;for(let[s,r]of Object.entries(He)){let g=n[s];typeof g=="string"&&g.length>0&&(o[r]=g);}return {envFile:t["env-file"],help:!!t.help,overrides:o}},"parseCliArgs");var z={version:"0.0.3"};var j=new AsyncLocalStorage;var W=i(()=>j.getStore()?.sandboxDir,"getCurrentRunSandbox");var Xe="@dudko.dev/agent",We=z.version,J,Je=i(()=>(J||(J=trace.getTracer(Xe,We)),J),"tracer"),R={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},C=i(async(e,t,o)=>Je().startActiveSpan(e,async n=>{for(let[s,r]of Object.entries(t))r!==void 0&&n.setAttribute(s,r);try{let s=await o(n);return n.end(),s}catch(s){let r=s instanceof Error?s:new Error(String(s));throw n.recordException(r),n.setStatus({code:SpanStatusCode.ERROR,message:r.message}),n.end(),s}}),"withSpan");var pt=i(e=>"command"in e&&!!e.command,"isStdioConfig"),ut=i(e=>"url"in e&&!!e.url,"isHttpConfig"),dt=z.version,pe=64,me=i(async(e,t,o,n,s,r)=>{let g=new Map,d={},c=[],p=[],a=i(async(f,h)=>{for(let T of Object.keys(d))T.startsWith(`${f}__`)&&delete d[T];for(let T=c.length-1;T>=0;T--)c[T].server===f&&c.splice(T,1);let l=await h.listTools(),m=0,E=0;for(let T of l.tools){let I=`${f}__${T.name}`;if(I.length>pe){t("warn",`[mcp] ${f}: tool "${T.name}" prefixed name (${I.length} chars) exceeds the ${pe}-char limit enforced by major LLM providers; skipping`),E++;continue}let y=T.description??"";d[I]=dynamicTool({description:y,inputSchema:jsonSchema(T.inputSchema),execute:i(async(v,k)=>C("agent.tool_call",{[R.TOOL_NAME]:I},async A=>{let P=v??{};if(r)try{let S=await r(I,P);P=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${I}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),P={_redacted:"inputSanitizer failed"};}let _;try{_=await h.callTool({name:T.name,arguments:P},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw A.setAttribute(R.TOOL_OK,false),S}let u=_.content;if(n)try{u=await n(I,u);}catch(S){return t("warn",`[mcp] ${I}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),A.setAttribute(R.TOOL_OK,false),"[output redacted: sanitizer failed]"}let w=await ft(u,{toolName:I,sandboxDir:W()});return A.setAttribute(R.TOOL_OK,true),w}),"execute")}),c.push({name:I,description:y,server:f}),m++;}E>0?t("info",`[mcp] ${f}: ${m} tools mounted, ${E} skipped (length cap)`):t("info",`[mcp] ${f}: ${m} tools mounted`);},"registerServerTools");for(let[f,h]of Object.entries(e))try{let l;if(pt(h)){let E=h.env?{...getDefaultEnvironment(),...h.env}:void 0;l=new StdioClientTransport({command:h.command,args:h.args,env:E,cwd:h.cwd});}else if(ut(h)){if(h.headers&&h.getHeaders)throw new Error(`MCP server "${f}": specify either headers or getHeaders, not both`);let E=h.getHeaders?await h.getHeaders():h.headers;l=new StreamableHTTPClientTransport(new URL(h.url),{requestInit:E?{headers:E}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${f}": config must specify either { url } (HTTP) or { command } (stdio)`);l.onerror=E=>t("warn",`[mcp] ${f}: transport error - ${E.message}`),l.onclose=()=>t("warn",`[mcp] ${f}: transport closed`);let m=new Client({name:o,version:dt});await m.connect(l),g.set(f,m),s&&m.setNotificationHandler(ToolListChangedNotificationSchema,()=>{s(f);}),await a(f,m),p.push({name:f,connected:!0});}catch(l){let m=l.message;t("error",`[mcp] ${f}: failed to connect - ${m}`),p.push({name:f,connected:false,error:m});}return {tools:d,catalog:c,results:p,close:i(async()=>{await Promise.allSettled([...g.values()].map(f=>f.close()));},"close"),refreshServer:i(async f=>{let h=g.get(f);if(!h)throw new Error(`MCP server "${f}" is not connected`);await a(f,h);},"refreshServer")}},"connectMcpServers"),ue={image:".bin",audio:".bin",resource:".bin"},mt=i((e,t)=>{if(!e)return ue[t];let o=e.indexOf("/"),s=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !s||/[^a-z0-9.+-]/.test(s)?ue[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[s]??`.${s.replace(/\+/g,"-")}`},"extFromMime"),gt=/[^a-zA-Z0-9_-]/g,de=i(async(e,t,o,n,s,r)=>{await r();let g=mt(t,o),d=n.replace(gt,"_").slice(0,32)||"tool",c=randomUUID().slice(0,8),p=Pe.join(s,`${o}-${d}-${c}${g}`),a=Buffer.from(e,"base64");return await writeFile(p,a),{type:"file",kind:o,path:p,mimeType:t,bytes:a.byteLength}},"spillBase64"),ft=i(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
|
|
29
|
+
`);let s=t?.sandboxDir,r=t?.toolName??"tool",g,d=i(()=>s?(g||(g=mkdir(s,{recursive:true}).then(()=>{})),g):Promise.resolve(),"ensureDir"),c=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){c.push(p.text);continue}if(s&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let a=await de(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,r,s,d);c.push(a);continue}if(s&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let a=p.resource;if(typeof a.blob=="string"){let f=await de(a.blob,typeof a.mimeType=="string"?a.mimeType:void 0,"resource",r,s,d);typeof a.uri=="string"&&(f.uri=a.uri),c.push(f);continue}if(typeof a.text=="string"){c.push(a.text);continue}}c.push(p);}return c},"flattenContent"),Z=i((e,t,o,n)=>{let s=o?.length?new Set(o):null,r=n?.length?new Set(n):null,g={},d=[];for(let c of t){if(s&&!s.has(c.name)||!s&&r?.has(c.name))continue;let p=e[c.name];p&&(g[c.name]=p,d.push(c));}return {tools:g,catalog:d}},"filterTools");var K=i((e,t,o,n)=>{let s=t?.providerType??e.providerType,r=t?.apiKey??e.apiKey,g=t?.baseURL??e.baseURL,d=t?.model??o??e.model;if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(s==="openai-compatible"&&!g)throw new Error(`${n}: provider "openai-compatible" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:s,baseURL:g,apiKey:r,model:d}},"resolveStage"),Y=i((e,t)=>{switch(t.providerType){case "openai":return createOpenAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "anthropic":return createAnthropic({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");return createOpenAICompatible({name:e,baseURL:t.baseURL,apiKey:t.apiKey})(t.model)}case "google":return createGoogleGenerativeAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model)}},"buildModelFromStage");var ee=i(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),o=e.length-t.length,n=[];o>0&&n.push(`(${o} earlier turns omitted)`);for(let s of t){let r=s.content.length>1500?`${s.content.slice(0,1500)}... [truncated]`:s.content;n.push(`${s.role}: ${r}`);}return n.join(`
|
|
30
|
+
`)},"renderHistory"),Et={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},fe=i((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=Et[t],s=e.slice(0,o),r=e.length-s.length,g=s.map(d=>{let c=(d.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${d.name}: ${c}`});return r>0&&g.push(`... and ${r} more tools`),g.join(`
|
|
31
|
+
`)},"renderToolCatalog"),Q=1500,St=i(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>Q?`${t.slice(0,Q)}... [truncated, ${t.length-Q} chars]`:t},"truncateOutput"),bt=i((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${St(n.output)}`).join(`
|
|
32
|
+
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
|
|
33
|
+
`)},"renderTraceEntry"),te=i(e=>e.length===0?"(no steps executed yet)":e.map(bt).join(`
|
|
34
|
+
`),"renderTrace"),oe=i(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
|
|
35
|
+
expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
|
|
36
|
+
suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
|
|
37
|
+
`),"renderPlan"),L=i((e,t)=>t?`${e}
|
|
38
|
+
|
|
39
|
+
Domain context:
|
|
40
|
+
${t}`:e,"withDomainContext"),ge=`You are the Planner of a multi-step agent system.
|
|
272
41
|
|
|
273
42
|
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
43
|
|
|
@@ -278,52 +47,28 @@ Rules:
|
|
|
278
47
|
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
279
48
|
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
49
|
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 = `
|
|
50
|
+
6. Output strict JSON matching the requested schema. No prose outside JSON.`,It=`
|
|
283
51
|
|
|
284
52
|
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
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
${
|
|
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.
|
|
53
|
+
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.`,he=i(e=>e==="compact"?ge+It:ge,"buildPlannerSystem"),ye=i((e,t,o,n="full")=>[o?.length?`Conversation history:
|
|
54
|
+
${ee(o)}
|
|
55
|
+
`:"",`User request:
|
|
56
|
+
${e}`,"",`Available tools:
|
|
57
|
+
${fe(t,n)}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
58
|
+
`),"buildPlannerUserPrompt"),Te=`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
59
|
|
|
301
60
|
Rules:
|
|
302
61
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
303
62
|
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
63
|
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
64
|
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
|
-
|
|
308
|
-
|
|
309
|
-
${
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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.
|
|
65
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,we=i((e,t,o,n,s)=>[s?.length?`Conversation history:
|
|
66
|
+
${ee(s)}
|
|
67
|
+
`:"",`Original user request:
|
|
68
|
+
${e}`,"",`Overall plan:
|
|
69
|
+
${oe(t)}`,"",`Trace so far:
|
|
70
|
+
${te(n)}`,"",`CURRENT STEP to execute (id=${o.id}): ${o.description}`,`Expected outcome: ${o.expectedOutcome}`,o.suggestedTools?.length?`Suggested tools: ${o.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
|
|
71
|
+
`),"buildExecutorUserPrompt"),Ee=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
|
|
327
72
|
|
|
328
73
|
You have three options:
|
|
329
74
|
- "continue": the next planned step is still appropriate.
|
|
@@ -334,1114 +79,39 @@ Rules:
|
|
|
334
79
|
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
335
80
|
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
336
81
|
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
|
-
|
|
339
|
-
|
|
340
|
-
${
|
|
341
|
-
|
|
342
|
-
|
|
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.
|
|
82
|
+
4. Output strict JSON matching the schema. No prose outside JSON.`,Se=i((e,t,o,n,s,r="full")=>[`Original user request:
|
|
83
|
+
${e}`,"",`Current plan:
|
|
84
|
+
${oe(t)}`,"",`Completed steps:
|
|
85
|
+
${te(o)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
|
|
86
|
+
${fe(s,r)}`,"","Decide now: continue, revise, or finish."].join(`
|
|
87
|
+
`),"buildReplannerUserPrompt"),be=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
356
88
|
|
|
357
89
|
Rules:
|
|
358
90
|
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
359
91
|
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
360
92
|
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
|
-
|
|
363
|
-
|
|
364
|
-
${
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
${input2}`,
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
${
|
|
371
|
-
|
|
372
|
-
`
|
|
373
|
-
|
|
374
|
-
"",
|
|
375
|
-
"
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
if (
|
|
384
|
-
|
|
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
|
|
93
|
+
4. Use the user's language.`,Ie=i((e,t,o,n)=>[n?.length?`Conversation history:
|
|
94
|
+
${ee(n)}
|
|
95
|
+
`:"",`User request:
|
|
96
|
+
${e}`,"",`Plan that was executed:
|
|
97
|
+
${oe(t)}`,"",`Execution trace:
|
|
98
|
+
${te(o)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
99
|
+
`),"buildSynthesizerUserPrompt");var Re=i((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let o=e;if(o.name==="AbortError")return false;let n=o.statusCode??o.status;return typeof n=="number"?n===429||n>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?Re(o.cause,t):false},"isRetriable"),M=i(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(r){if(n=r,s===t.maxRetries||!Re(r))throw r;t.onRetry?.(s+1,r);let g=o*2**s+Math.random()*250;await Rt(g,t.signal);}}throw n},"withRetry"),Rt=i((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",r),o();},e),r=i(()=>{clearTimeout(s),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",r,{once:true});}),"sleep"),ne=i(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),U=i((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:ne([e,AbortSignal.timeout(t)]),"withTimeout");var kt=i((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let o=new Set(t.suggestedTools??[]);if(o.size===0)return t.requiresTools?e.tools:{};let n={};for(let s of o){let r=e.tools[s];r&&(n[s]=r);}return n},"buildActiveToolSet"),ve="[BLOCKER]",xt=i(e=>e.includes(ve)?{summary:e.split(ve).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),re=4e3,Ct=i(e=>e.length>re?`${e.slice(0,re)}... [truncated, ${e.length-re} chars]`:e,"truncateForTrace"),Ae=i(async(e,t,o,n,s,r,g)=>C("agent.execute_step",{[R.PHASE]:"execute",[R.STEP_ID]:o.id},async d=>{let c=Date.now(),p=await M(()=>Pt(e,t,o,n,s,r,g),{maxRetries:r.config.llmMaxRetries??2,signal:g,onRetry:i((a,f)=>r.emit({type:"retry",phase:"execute",attempt:a,error:f.message}),"onRetry")});return r.emit({type:"usage",phase:"execute",usage:p.usage}),d.setAttribute(R.USAGE_TOTAL_TOKENS,p.usage.totalTokens),d.setAttribute(R.STEP_BLOCKED,p.blocked),d.setAttribute(R.TOOL_COUNT,p.toolCalls.length),{step:o,summary:p.summary,toolCalls:p.toolCalls,durationMs:Date.now()-c,blocked:p.blocked}}),"executeStep"),Pt=i(async(e,t,o,n,s,r,g)=>{let d=[],c=new Map,p=kt(r,o),a=r.config.toolSelectionStrategy==="plan-narrowed",f=i(async(y,v)=>{let k=r.config.inputSanitizer;if(!k)return v;try{return await k(y,v)}catch(A){return r.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${y} - ${A.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),h=streamText({model:r.executorModel,tools:p,...a?{activeTools:Object.keys(p)}:{},stopWhen:stepCountIs(r.config.maxStepsPerTask),system:L(Te,r.config.systemPrompt),prompt:we(e,t,o,n,s),abortSignal:U(g,r.config.llmTimeoutMs??0)});for await(let y of h.fullStream)switch(y.type){case "text-delta":y.text&&r.emit({type:"step.text-delta",step:o,delta:y.text});break;case "tool-call":{let v=await f(y.toolName,y.input);c.set(y.toolCallId,{name:y.toolName,input:v}),r.emit({type:"step.tool-call",step:o,name:y.toolName,input:v});break}case "tool-result":{let k=c.get(y.toolCallId)?.input??await f(y.toolName,y.input);d.push({name:y.toolName,input:k,output:y.output,ok:true}),r.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.output,ok:true}),c.delete(y.toolCallId);break}case "tool-error":{let k=c.get(y.toolCallId)?.input??await f(y.toolName,y.input);d.push({name:y.toolName,input:k,output:y.error,ok:false}),r.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.error,ok:false}),c.delete(y.toolCallId);break}case "error":{let v=y.error;throw v instanceof Error?v:new Error(String(v))}}let[l,m]=await Promise.all([h.text,h.usage]),{summary:E,blocked:T}=xt(l.trim());return {summary:E.length>0?Ct(E):d.length>0?`Executed ${d.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:d,blocked:T,usage:{inputTokens:m.inputTokens??0,outputTokens:m.outputTokens??0,totalTokens:m.totalTokens??0}}},"runOnce");var Ot=z$1.object({id:z$1.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z$1.string().min(1).describe("Concrete action to perform"),expectedOutcome:z$1.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z$1.array(z$1.string()).optional().describe("Tool names from the available list, if any")}),se=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array(Ot).min(1).max(8)}),ke=i(async(e,t,o,n)=>C("agent.plan",{[R.PHASE]:"plan"},async s=>{let r=new Set(o.toolCatalog.map(p=>p.name)),g=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:d,usage:c}=await M(()=>$t(e,t,g,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:i((p,a)=>o.emit({type:"retry",phase:"plan",attempt:p,error:a.message}),"onRetry")});return o.emit({type:"usage",phase:"plan",usage:c}),s.setAttribute(R.USAGE_TOTAL_TOKENS,c.totalTokens),{thought:d.thought,steps:d.steps.map(p=>{if(!p.suggestedTools?.length)return p;let a=p.suggestedTools.filter(h=>r.has(h)),f=p.suggestedTools.length-a.length;return f>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${p.id}" had ${f} unknown suggestedTools, stripped`}),a.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${p.id}" had no valid suggestedTools left; falling back to full toolset`}),{...p,suggestedTools:void 0,requiresTools:true}):{...p,suggestedTools:a}})}}),"createInitialPlan"),$t=i(async(e,t,o,n,s)=>{let r=streamObject({model:n.plannerModel,schema:se,system:L(he(o),n.config.systemPrompt),prompt:ye(e,n.toolCatalog,t,o),abortSignal:U(s,n.config.llmTimeoutMs??0)}),g="",d=false,c=0;for await(let f of r.partialObjectStream){let h=f?.thought;typeof h=="string"&&h!==g&&(h.startsWith(g)?n.emit({type:"plan.thought-delta",delta:h.slice(g.length)}):d||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),d=true),g=h);let l=f?.steps;if(Array.isArray(l)&&l.length>c)for(;c<l.length;){let m=l[c];if(!m||typeof m.description!="string"||!m.description.length)break;let E={id:typeof m.id=="string"&&m.id?m.id:`s${c+1}`,description:m.description,expectedOutcome:typeof m.expectedOutcome=="string"?m.expectedOutcome:"",suggestedTools:Array.isArray(m.suggestedTools)?m.suggestedTools.filter(T=>typeof T=="string"):void 0};n.emit({type:"plan.step-added",step:E,index:c}),c++;}}let[p,a]=await Promise.all([r.object,r.usage]);return {object:p,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamPlanOnce");var Lt=z$1.discriminatedUnion("mode",[z$1.object({mode:z$1.literal("continue"),reason:z$1.string().min(1).describe("Why the next step is still appropriate")}),z$1.object({mode:z$1.literal("finish"),reason:z$1.string().min(1).describe("Why no more steps are needed")}),z$1.object({mode:z$1.literal("revise"),reason:z$1.string().min(1).describe("Why the plan must change"),newPlan:se.describe("Plan covering ONLY the remaining work")})]),xe=i(async(e,t,o,n,s,r)=>C("agent.replan",{[R.PHASE]:"replan"},async g=>{let d=s.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:p}=await M(async()=>{let a=await generateObject({model:s.plannerModel,schema:Lt,system:L(Ee,s.config.systemPrompt),prompt:Se(e,t,o,n,s.toolCatalog,d),abortSignal:U(r,s.config.llmTimeoutMs??0)}),f={inputTokens:a.usage.inputTokens??0,outputTokens:a.usage.outputTokens??0,totalTokens:a.usage.totalTokens??0};return {object:a.object,usage:f}},{maxRetries:s.config.llmMaxRetries??2,signal:r,onRetry:i((a,f)=>s.emit({type:"retry",phase:"replan",attempt:a,error:f.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:p}),g.setAttribute(R.REPLAN_MODE,c.mode),g.setAttribute(R.USAGE_TOTAL_TOKENS,p.totalTokens),c}),"decideNextAction");var Ce=i(async(e,t,o,n,s,r)=>C("agent.synthesize",{[R.PHASE]:"synthesize"},async g=>{let{text:d,usage:c}=await M(()=>Ut(e,t,o,n,s,r),{maxRetries:s.config.llmMaxRetries??2,signal:r,onRetry:i((p,a)=>s.emit({type:"retry",phase:"synthesize",attempt:p,error:a.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:c}),g.setAttribute(R.USAGE_TOTAL_TOKENS,c.totalTokens),d}),"synthesizeAnswer"),Ut=i(async(e,t,o,n,s,r)=>{let g=streamText({model:s.synthesizerModel,system:L(be,s.config.systemPrompt),prompt:Ie(e,t,o,n),abortSignal:U(r,s.config.llmTimeoutMs??0)});for await(let p of g.fullStream)if(p.type==="text-delta")p.text&&s.emit({type:"final.text-delta",delta:p.text});else if(p.type==="error"){let a=p.error;throw a instanceof Error?a:new Error(String(a))}let[d,c]=await Promise.all([g.text,g.usage]);return {text:d,usage:{inputTokens:c.inputTokens??0,outputTokens:c.outputTokens??0,totalTokens:c.totalTokens??0}}},"streamOnce");var zt=i(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),H=i(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Kt=i((e,t)=>{let o=e.config.sandboxRoot?.trim()||Pe.join(tmpdir(),"agent-sandbox");return Pe.join(o,t)},"resolveSandboxDir"),_e=/^[a-zA-Z0-9_-]{1,128}$/,ie=i((e,t)=>{if(!_e.test(e))throw new Error(`Unsafe runId from ${t}: must match ${_e}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Yt=i(async(e,t)=>{if(!t.resumeFromRunId)return;if(ie(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await e.config.persistence.loadRun(t.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(ie(o.runId,"snapshot.runId"),o.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Oe=i(async(e,t)=>{let o=await Yt(e,t),n=o?.runId??randomUUID();ie(n,"runId");let s=o?.startedAt??Date.now(),r=Kt(e,n);return j.run({runId:n,startedAt:s,sandboxDir:r},async()=>C("agent.run",{[R.RUN_ID]:n,[R.PROVIDER]:e.config.providerType,[R.MODEL]:e.config.model},async g=>{try{let d=await Ht(e,t,o);return g.setAttribute(R.ITERATIONS,d.iterations),g.setAttribute(R.USAGE_TOTAL_TOKENS,d.usage.totalTokens),g.setAttribute(R.USAGE_INPUT_TOKENS,d.usage.inputTokens),g.setAttribute(R.USAGE_OUTPUT_TOKENS,d.usage.outputTokens),d}finally{e.config.keepSandbox||await rm(r,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Ht=i(async(e,t,o)=>{let{signal:n}=t,s=o?.input??t.input,r=o?.history?[...o.history]:t.history?[...t.history]:void 0,g=t.onEvent??(()=>{}),d=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},c=j.getStore()?.startedAt??Date.now(),p=j.getStore()?.runId??"<unknown>",a={...e,emit:i(u=>{u.type==="usage"&&(d.inputTokens+=u.usage.inputTokens,d.outputTokens+=u.usage.outputTokens,d.totalTokens+=u.usage.totalTokens);let w={...u,runId:j.getStore()?.runId};try{g(w);}catch{}try{e.emit(w);}catch{}},"emit")},f=e.config.persistence,h=i(async(u,w)=>{let S=f?.[u];if(S)try{await S(w);}catch(b){a.emit({type:"log",level:"warn",message:`[persistence] ${u} threw: ${b.message}`});}},"callPersistence"),l;if(o)l=o.plan,a.emit({type:"log",level:"info",message:`[resume] continuing run ${p} from step ${o.stepIndex}/${l.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),a.emit({type:"plan.created",plan:l});else {try{l=await ke(s,r,a,n);}catch(u){if(a.emit({type:"error",error:G(u),phase:"plan"}),H(u)||n?.aborted)throw await h("onRunComplete",{runId:p,startedAt:c,status:"cancelled",input:s,history:r,trace:[],usage:d,stepIndex:0,iterations:0,revisions:0,error:u.message,completedAt:Date.now()}),u;l={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}a.emit({type:"plan.created",plan:l});}let m=o?[...o.trace]:[],E=l,T=o?.stepIndex??0,I=o?.iterations??0,y=o?.revisions??0,v=e.config.maxRevisions??2,k=e.config.maxTotalTokens,A=i((u,w={})=>({runId:p,startedAt:c,status:u,input:s,history:r,plan:E,trace:m,usage:d,stepIndex:T,iterations:I,revisions:y,...w}),"buildSnapshot");o||await h("onRunStart",A("executing"));let P=i(async()=>{await h("onStepComplete",A("executing"));},"persistCheckpoint");for(;I<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(T>=E.steps.length)break;if(k&&d.totalTokens>=k){a.emit({type:"budget.exceeded",tokens:d.totalTokens,cap:k});break}I++;let u=E.steps[T];a.emit({type:"step.start",step:u,index:T});let w=new AbortController;if(t.onStepStart)try{t.onStepStart({step:u,index:T,abort:i(()=>w.abort(),"abort")});}catch(x){a.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${x.message}`});}let S=ne([n,w.signal]),b;try{b=await Ae(s,E,u,m,r,a,S);}catch(x){if(n?.aborted)throw a.emit({type:"error",error:G(x),phase:"execute"}),await h("onRunComplete",A("cancelled",{error:x.message,completedAt:Date.now()})),x;if(w.signal.aborted&&H(x))a.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),b={step:u,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw a.emit({type:"error",error:G(x),phase:"execute"}),await h("onRunComplete",A("failed",{error:x.message,completedAt:Date.now()})),x}m.push(b),a.emit({type:"step.complete",step:u,result:b});let O=E.steps[T+1]??null;if(O===null){a.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!zt(b)){a.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),T++,await P();continue}let D;try{D=await xe(s,E,m,O,a,n);}catch(x){throw a.emit({type:"error",error:G(x),phase:"replan"}),await h("onRunComplete",A(H(x)||n?.aborted?"cancelled":"failed",{error:x.message,completedAt:Date.now()})),x}if(a.emit({type:"replan.decision",mode:D.mode,reason:D.reason,cause:"llm-decision"}),D.mode==="finish")break;if(D.mode==="revise"){if(y>=v){a.emit({type:"revisions.exceeded",cap:v});break}y++,E=D.newPlan,a.emit({type:"plan.revised",plan:E,reason:D.reason}),T=0,await P();continue}T++,await P();}let _;try{_=await Ce(s,E,m,r,a,n);}catch(u){throw a.emit({type:"error",error:G(u),phase:"synthesize"}),await h("onRunComplete",A(H(u)||n?.aborted?"cancelled":"failed",{error:u.message,completedAt:Date.now()})),u}return a.emit({type:"final",text:_}),await h("onRunComplete",A("complete",{text:_,completedAt:Date.now()})),{text:_,plan:E,trace:m,iterations:I,usage:d}},"runAgentLoopInner"),G=i(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var F={none:0,error:1,warn:2,info:3,debug:4},$e=i(async(e,t)=>{let o=F[e.logLevel]>=F.debug,n=i(u=>{if(t)try{t(u);}catch(w){o&&console.error("[agent] event handler threw:",w);}},"emit"),s=i((u,w)=>{F[e.logLevel]>=F[u]&&n({type:"log",level:u,message:w});},"log"),r,g=i((u,w)=>{if(!e.tools)return u;let S=[];for(let[b,O]of Object.entries(e.tools)){if(u.tools[b]&&w(b),e.availableTools?.length&&!e.availableTools.includes(b)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(b))continue;u.tools[b]=O;let X=typeof O=="object"&&O&&"description"in O?O.description:"";S.push({name:b,description:typeof X=="string"?X:"",server:"<native>"});}return {tools:u.tools,catalog:[...u.catalog,...S]}},"mergeNativeTools"),d=i(async()=>{let u=await me(e.mcpServers,s,e.clientName,e.outputSanitizer,b=>r?.(b),e.inputSanitizer),w=Z(u.tools,u.catalog,e.availableTools,e.excludedTools),S=g(w,b=>{throw u.close().catch(()=>{}),new Error(`Native tool "${b}" collides with an MCP-registered tool of the same name`)});return {connection:u,tools:S.tools,catalog:S.catalog}},"connect"),c;try{c=await d();}catch(u){throw n({type:"error",error:u instanceof Error?u:new Error(String(u)),phase:"init"}),u}let p=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&p>0&&!c.connection.results.some(w=>w.connected)){let w=c.connection.results.filter(b=>!b.connected).map(b=>`${b.name}: ${b.error??"unknown"}`).join("; ");await c.connection.close().catch(()=>{});let S=new Error(`All ${p} configured MCP server(s) failed to connect [${w}]`);throw n({type:"error",error:S,phase:"init"}),S}let a=K(e,void 0,void 0,"executor"),f=K(e,e.planner,e.plannerModel,"planner"),h=K(e,e.synthesizer,e.synthesizerModel,"synthesizer"),l=Y(e.clientName,a),m=Y(e.clientName,f),E=Y(e.clientName,h),T={config:e,executorModel:l,plannerModel:m,synthesizerModel:E,tools:c.tools,toolCatalog:c.catalog.map(u=>({name:u.name,description:u.description})),emit:n},I=0,y=false,v=false,k=false,A=new Set,P=i(async u=>{await c.connection.refreshServer(u);let w=Z(c.connection.tools,c.connection.catalog,e.availableTools,e.excludedTools),S=g(w,b=>{throw new Error(`Native tool "${b}" collides with an MCP-registered tool of the same name`)});for(let b of Object.keys(T.tools))delete T.tools[b];Object.assign(T.tools,S.tools),T.toolCatalog=S.catalog.map(b=>({name:b.name,description:b.description})),s("info",`[mcp] ${u}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),_=i(async()=>{if(!(k||y||v)&&!(I>0||A.size===0)){k=true;try{for(;A.size>0&&I===0&&!y&&!v;){let u=A.values().next().value;A.delete(u);try{await P(u);}catch(w){s("warn",`[mcp] ${u}: refresh failed - ${w.message}`);}}}finally{k=false;}}},"drainPendingRefreshes");return r=i(u=>{A.add(u),_();},"onToolsChanged"),{run:i(async u=>{if(y)throw new Error("Agent is closed");if(v)throw new Error("Agent is reconnecting; retry shortly");if(k)throw new Error("Agent is refreshing tools; retry shortly");let w=e.maxConcurrentRuns;if(typeof w=="number"&&w>0&&I>=w)throw new Error(`maxConcurrentRuns reached (${I}/${w}); rate-limit on the caller side or raise the cap`);I++;try{return await Oe(T,u)}finally{I--,_();}},"run"),listTools:i(()=>T.toolCatalog.slice(),"listTools"),reconnect:i(async()=>{if(y)throw new Error("Agent is closed");if(v)throw new Error("Already reconnecting");if(k)throw new Error("Agent is refreshing tools; retry shortly");if(I>0)throw new Error(`Cannot reconnect with ${I} active run(s)`);v=true;try{let u=c.connection;A.clear();let w=await d();for(let S of Object.keys(T.tools))delete T.tools[S];Object.assign(T.tools,w.tools),T.toolCatalog=w.catalog.map(S=>({name:S.name,description:S.description})),c=w,await u.close().catch(()=>{});}finally{v=false;}},"reconnect"),close:i(async u=>{y=true;let w=u?.waitForRuns??false,S=u?.timeoutMs??3e4;if(w&&I>0){let b=Date.now();for(;I>0&&Date.now()-b<S;)await new Promise(O=>setTimeout(O,50));}I>0&&n({type:"log",level:"warn",message:`[agent] close called with ${I} active run(s); they will fail mid-flight`}),await c.connection.close().catch(()=>{});},"close"),activeRuns:i(()=>I,"activeRuns")}},"createAgent");var B=["openai","anthropic","openai-compatible","google"],Ne=["none","error","warn","info","debug"],Le=["all","plan-narrowed"],je=i(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!B.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${B.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!Ne.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${Ne.join(" | ")}, got: ${t}`);let o=e==="openai-compatible"?ae("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:ae("AGENT_API_KEY"),model:ae("AGENT_MODEL"),planner:Me("AGENT_PLANNER"),synthesizer:Me("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:Vt(process.env.MCP_SERVERS),availableTools:Ue(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:Ue(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:De(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:De(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:V(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:V(process.env.AGENT_MAX_TOTAL_TOKENS),llmTimeoutMs:V(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:V(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:Ft(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),Me=i(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),n=process.env[`${e}_API_KEY`]?.trim();if(!(!t&&!o&&!n)){if(t&&!B.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${B.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:n||void 0}}},"parseStageOverride"),Ft=i(e=>{let t=e?.trim();if(t){if(!Le.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${Le.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),V=i(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),ae=i(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),Ue=i(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),De=i((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),Vt=i(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(n){throw new Error(`MCP_SERVERS must be valid JSON: ${n.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[n,s]of Object.entries(t)){if(!s||typeof s!="object")throw new Error(`MCP_SERVERS.${n} must be an object`);let r=s,g=typeof r.url=="string"&&r.url.length>0,d=typeof r.command=="string"&&r.command.length>0;if(g&&d)throw new Error(`MCP_SERVERS.${n}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!g&&!d)throw new Error(`MCP_SERVERS.${n}: must specify "url" (HTTP) or "command" (stdio)`);if(g){let c=r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)?r.headers:void 0;o[n]={url:r.url,headers:c};continue}if(r.args!==void 0&&!Array.isArray(r.args))throw new Error(`MCP_SERVERS.${n}.args must be a string array`);if(r.env!==void 0&&(!r.env||typeof r.env!="object"||Array.isArray(r.env)))throw new Error(`MCP_SERVERS.${n}.env must be a string-to-string map`);if(r.cwd!==void 0&&typeof r.cwd!="string")throw new Error(`MCP_SERVERS.${n}.cwd must be a string`);o[n]={command:r.command,args:r.args,env:r.env,cwd:r.cwd};}return o},"parseMcpServers");var Wt=16,q=i((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),Ge=i(e=>{try{return q(JSON.stringify(e))}catch{return String(e)}},"formatJson"),ze=i(async()=>{let e=je(),t=Object.keys(e.mcpServers),o=e.planner?.model??e.plannerModel??e.model,n=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${o} synth=${n} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[mcp] servers=${t.length?t.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /reconnect, /exit
|
|
100
|
+
`);let s=false,r=false,d=await $e(e,i(l=>{switch(l.type){case "log":console.log(`[${l.level}] ${l.message}`);break;case "plan.thought-delta":r||(process.stdout.write(`
|
|
101
|
+
[plan] `),r=true),process.stdout.write(l.delta);break;case "plan.step-added":r&&(process.stdout.write(`
|
|
102
|
+
`),r=false),console.log(` ${l.index+1}. ${l.step.description}`);break;case "plan.created":r?(process.stdout.write(`
|
|
103
|
+
`),r=false):console.log(`
|
|
104
|
+
[plan] ${l.plan.thought}`);for(let[m,E]of l.plan.steps.entries()){let T=E.suggestedTools?.length?` (tools: ${E.suggestedTools.join(", ")})`:"";console.log(` ${m+1}. ${E.description}${T}`);}break;case "plan.revised":console.log(`
|
|
105
|
+
[replan] reason=${l.reason}`);for(let[m,E]of l.plan.steps.entries())console.log(` ${m+1}. ${E.description}`);break;case "step.start":console.log(`
|
|
106
|
+
[step ${l.index+1}] ${l.step.description}`);break;case "step.tool-call":console.log(` -> ${l.name} ${Ge(l.input)}`);break;case "step.tool-result":{let m=l.ok?"ok":"fail";console.log(` <- ${l.name} ${m} ${Ge(l.output)}`);break}case "step.complete":console.log(` = ${q(l.result.summary,400)} (${l.result.durationMs}ms, ${l.result.toolCalls.length} tool calls)`);break;case "replan.decision":l.mode!=="continue"&&console.log(`[replan] ${l.mode} (${l.cause}): ${l.reason}`);break;case "usage":break;case "retry":l.phase==="plan"&&r&&(process.stdout.write(`
|
|
107
|
+
`),r=false),console.log(`[retry] ${l.phase} attempt=${l.attempt}: ${l.error}`);break;case "budget.exceeded":console.log(`[budget] token cap reached: ${l.tokens}/${l.cap} - finishing early`);break;case "revisions.exceeded":console.log(`[budget] max ${l.cap} replan-revisions reached - finishing early`);break;case "final.text-delta":s||(process.stdout.write(`
|
|
108
|
+
assistant> `),s=true),process.stdout.write(l.delta);break;case "final":s?(process.stdout.write(`
|
|
109
|
+
|
|
110
|
+
`),s=false):console.log(`
|
|
111
|
+
assistant> ${l.text}
|
|
112
|
+
`);break;case "error":l.phase==="plan"&&r&&(process.stdout.write(`
|
|
113
|
+
`),r=false),console.error(`[error] (${l.phase}) ${l.error.message}`);break}},"onEvent")),c=d.listTools();console.log(`[tools] available=${c.length}${c.length?`: ${c.map(l=>l.name).join(", ")}`:""}`);let p=createInterface({input:stdin,output:stdout}),a=[],f=null,h=i(()=>{f?(console.log(`
|
|
114
|
+
[abort] cancelling current run...`),f.abort()):p.close();},"onSigInt");process.on("SIGINT",h);try{for(;;){let l;try{l=(await p.question(`
|
|
115
|
+
you> `)).trim();}catch{break}if(l){if(l==="/exit"||l==="/quit")break;if(l==="/tools"){if(c.length===0)console.log("[tools] (none)");else for(let m of c)console.log(` - ${m.name}: ${q(m.description,200)}`);continue}if(l==="/status"){console.log(`[status] model=${e.model} planner=${o} synth=${n}`),console.log(`[status] tools=${c.length} mcp=${t.join(", ")||"(none)"} historyTurns=${a.length}`);continue}if(l==="/history"){if(a.length===0)console.log("[history] (empty)");else for(let m of a)console.log(` ${m.role}: ${q(m.content,200)}`);continue}if(l==="/reset"){a.length=0,console.log("[history] cleared");continue}if(l==="/reconnect"){try{await d.reconnect();let m=d.listTools();c.length=0;for(let E of m)c.push(E);console.log(`[mcp] reconnected, ${c.length} tools available`);}catch(m){console.error("[error] reconnect failed:",m.message);}continue}s=!1,r=!1,f=new AbortController;try{let m=await d.run({input:l,history:a,signal:f.signal});for(a.push({role:"user",content:l}),a.push({role:"assistant",content:m.text});a.length>Wt;)a.shift();console.log(`[meta] iterations=${m.iterations} steps=${m.trace.length} tokens=${m.usage.totalTokens} (in=${m.usage.inputTokens} out=${m.usage.outputTokens})`);}catch(m){m?.name==="AbortError"?console.log("[abort] run cancelled"):console.error("[error]",m.message);}finally{f=null;}}}}finally{process.off("SIGINT",h),p.close(),await d.close().catch(l=>console.error("[cleanup] agent",l));}},"runRepl");var Jt=i(async()=>{let e;try{e=ce(process.argv.slice(2));}catch(t){console.error(t.message),console.error("\nRun `dd-agent --help` for usage."),process.exit(2);}if(e.help){process.stdout.write(le);return}if(e.envFile)try{process.loadEnvFile(e.envFile);}catch(t){console.error(`Failed to load env file ${e.envFile}: ${t.message}`),process.exit(2);}for(let[t,o]of Object.entries(e.overrides))process.env[t]=o;try{await ze();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
|
|
116
|
+
|
|
117
|
+
Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");Jt().catch(e=>{console.error(e),process.exit(1);});
|