@dudko.dev/agent 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,244 +1,13 @@
1
- 'use strict';
2
-
3
- var index_js = require('@modelcontextprotocol/sdk/client/index.js');
4
- var streamableHttp_js = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
5
- var ai = require('ai');
6
- var url = require('url');
7
- var anthropic = require('@ai-sdk/anthropic');
8
- var google = require('@ai-sdk/google');
9
- var openai = require('@ai-sdk/openai');
10
- var openaiCompatible = require('@ai-sdk/openai-compatible');
11
- var crypto = require('crypto');
12
- var async_hooks = require('async_hooks');
13
- var zod = require('zod');
14
-
15
- // src/mcp.ts
16
- var connectMcpServers = async (servers, log, clientName, outputSanitizer) => {
17
- const clients = [];
18
- const tools = {};
19
- const catalog = [];
20
- const results = [];
21
- for (const [name, cfg] of Object.entries(servers)) {
22
- if (cfg.headers && cfg.getHeaders) {
23
- throw new Error(`MCP server "${name}": specify either headers or getHeaders, not both`);
24
- }
25
- try {
26
- const headers = cfg.getHeaders ? await cfg.getHeaders() : cfg.headers;
27
- const transport = new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(cfg.url), {
28
- requestInit: headers ? { headers } : void 0,
29
- // Built-in reconnect for transient SSE drops. Defaults are conservative;
30
- // production deployments should tune via direct transport access if needed.
31
- reconnectionOptions: {
32
- maxReconnectionDelay: 3e4,
33
- initialReconnectionDelay: 1e3,
34
- reconnectionDelayGrowFactor: 1.5,
35
- maxRetries: 5
36
- }
37
- });
38
- transport.onerror = (err) => log("warn", `[mcp] ${name}: transport error - ${err.message}`);
39
- transport.onclose = () => log("warn", `[mcp] ${name}: transport closed`);
40
- const client = new index_js.Client({ name: clientName, version: "0.0.0" });
41
- await client.connect(transport);
42
- clients.push(client);
43
- const listed = await client.listTools();
44
- let mounted = 0;
45
- for (const t of listed.tools) {
46
- const prefixed = `${name}__${t.name}`;
47
- const description = t.description ?? "";
48
- tools[prefixed] = ai.dynamicTool({
49
- description,
50
- inputSchema: ai.jsonSchema(t.inputSchema),
51
- execute: async (args, opts) => {
52
- const result = await client.callTool(
53
- {
54
- name: t.name,
55
- arguments: args ?? {}
56
- },
57
- void 0,
58
- opts?.abortSignal ? { signal: opts.abortSignal } : void 0
59
- );
60
- const flat = flattenContent(result.content);
61
- if (!outputSanitizer) {
62
- return flat;
63
- }
64
- try {
65
- return await outputSanitizer(prefixed, flat);
66
- } catch (err) {
67
- log(
68
- "warn",
69
- `[mcp] ${prefixed}: outputSanitizer threw - ${err.message}; output replaced with placeholder`
70
- );
71
- return "[output redacted: sanitizer failed]";
72
- }
73
- }
74
- });
75
- catalog.push({ name: prefixed, description, server: name });
76
- mounted++;
77
- }
78
- log("info", `[mcp] ${name}: connected, ${mounted} tools`);
79
- results.push({ name, connected: true });
80
- } catch (err) {
81
- const message = err.message;
82
- log("error", `[mcp] ${name}: failed to connect - ${message}`);
83
- results.push({ name, connected: false, error: message });
84
- }
85
- }
86
- return {
87
- tools,
88
- catalog,
89
- results,
90
- close: async () => {
91
- await Promise.allSettled(clients.map((c) => c.close()));
92
- }
93
- };
94
- };
95
- var flattenContent = (content) => {
96
- if (!Array.isArray(content)) {
97
- return content;
98
- }
99
- const parts = content;
100
- const allText = parts.length > 0 && parts.every((p) => p?.type === "text" && typeof p.text === "string");
101
- if (allText) {
102
- return parts.map((p) => p.text).join("\n");
103
- }
104
- return parts.map((p) => {
105
- if (p?.type === "text" && typeof p.text === "string") {
106
- return p.text;
107
- }
108
- return p;
109
- });
110
- };
111
- var filterTools = (tools, catalog, available, excluded) => {
112
- const allow = available?.length ? new Set(available) : null;
113
- const deny = excluded?.length ? new Set(excluded) : null;
114
- const result = {};
115
- const filteredCatalog = [];
116
- for (const entry of catalog) {
117
- if (allow && !allow.has(entry.name)) {
118
- continue;
119
- }
120
- if (!allow && deny?.has(entry.name)) {
121
- continue;
122
- }
123
- const t = tools[entry.name];
124
- if (!t) {
125
- continue;
126
- }
127
- result[entry.name] = t;
128
- filteredCatalog.push(entry);
129
- }
130
- return { tools: result, catalog: filteredCatalog };
131
- };
132
- var buildModel = (config, modelId) => {
133
- switch (config.providerType) {
134
- case "openai": {
135
- const provider = openai.createOpenAI({
136
- baseURL: config.baseURL || void 0,
137
- apiKey: config.apiKey
138
- });
139
- return provider(modelId);
140
- }
141
- case "anthropic": {
142
- const provider = anthropic.createAnthropic({
143
- baseURL: config.baseURL || void 0,
144
- apiKey: config.apiKey
145
- });
146
- return provider(modelId);
147
- }
148
- case "openai-compatible": {
149
- if (!config.baseURL) {
150
- throw new Error("openai-compatible provider requires baseURL");
151
- }
152
- const provider = openaiCompatible.createOpenAICompatible({
153
- name: config.clientName,
154
- baseURL: config.baseURL,
155
- apiKey: config.apiKey
156
- });
157
- return provider(modelId);
158
- }
159
- case "google": {
160
- const provider = google.createGoogleGenerativeAI({
161
- baseURL: config.baseURL || void 0,
162
- apiKey: config.apiKey
163
- });
164
- return provider(modelId);
165
- }
166
- }
167
- };
168
- var runContext = new async_hooks.AsyncLocalStorage();
169
- var getCurrentRunId = () => runContext.getStore()?.runId;
170
- var HISTORY_CONTENT_LIMIT = 1500;
171
- var renderHistory = (history) => {
172
- if (!history?.length) {
173
- return "(no prior conversation)";
174
- }
175
- const tail = history.slice(-8);
176
- const skipped = history.length - tail.length;
177
- const lines = [];
178
- if (skipped > 0) {
179
- lines.push(`(${skipped} earlier turns omitted)`);
180
- }
181
- for (const t of tail) {
182
- const content = t.content.length > HISTORY_CONTENT_LIMIT ? `${t.content.slice(0, HISTORY_CONTENT_LIMIT)}... [truncated]` : t.content;
183
- lines.push(`${t.role}: ${content}`);
184
- }
185
- return lines.join("\n");
186
- };
187
- var CATALOG_BUDGETS = {
188
- full: { tools: 80, descChars: 240 },
189
- compact: { tools: 200, descChars: 80 }
190
- };
191
- var renderToolCatalog = (catalog, mode = "full") => {
192
- if (catalog.length === 0) {
193
- return "(no tools available)";
194
- }
195
- const { tools: toolLimit, descChars } = CATALOG_BUDGETS[mode];
196
- const sliced = catalog.slice(0, toolLimit);
197
- const rest = catalog.length - sliced.length;
198
- const lines = sliced.map((t) => {
199
- const desc = (t.description || "").replace(/\s+/g, " ").trim().slice(0, descChars);
200
- return `- ${t.name}: ${desc}`;
201
- });
202
- if (rest > 0) {
203
- lines.push(`... and ${rest} more tools`);
204
- }
205
- return lines.join("\n");
206
- };
207
- var TOOL_OUTPUT_BUDGET = 1500;
208
- var truncateOutput = (output) => {
209
- let s;
210
- try {
211
- s = typeof output === "string" ? output : JSON.stringify(output);
212
- } catch {
213
- s = String(output);
214
- }
215
- return s.length > TOOL_OUTPUT_BUDGET ? `${s.slice(0, TOOL_OUTPUT_BUDGET)}... [truncated, ${s.length - TOOL_OUTPUT_BUDGET} chars]` : s;
216
- };
217
- var renderTraceEntry = (r, idx) => {
218
- const calls = r.toolCalls.length ? r.toolCalls.map((c) => ` - ${c.name} ${c.ok ? "ok" : "fail"}: ${truncateOutput(c.output)}`).join("\n") : " (no tool calls)";
219
- return [
220
- `Step ${idx + 1}: ${r.step.description}`,
221
- ` Result: ${r.summary}`,
222
- ` Tool calls:`,
223
- calls
224
- ].join("\n");
225
- };
226
- var renderTrace = (trace) => {
227
- if (trace.length === 0) {
228
- return "(no steps executed yet)";
229
- }
230
- return trace.map(renderTraceEntry).join("\n");
231
- };
232
- var renderPlan = (plan) => [
233
- `Plan thought: ${plan.thought}`,
234
- "Steps:",
235
- ...plan.steps.map(
236
- (s, i) => ` ${i + 1}. [${s.id}] ${s.description}
237
- expected: ${s.expectedOutcome}` + (s.suggestedTools?.length ? `
238
- suggested tools: ${s.suggestedTools.join(", ")}` : "")
239
- )
240
- ].join("\n");
241
- var PLANNER_SYSTEM_BASE = `You are the Planner of a multi-step agent system.
1
+ 'use strict';var index_js=require('@modelcontextprotocol/sdk/client/index.js'),streamableHttp_js=require('@modelcontextprotocol/sdk/client/streamableHttp.js'),ai=require('ai'),url=require('url'),anthropic=require('@ai-sdk/anthropic'),google=require('@ai-sdk/google'),openai=require('@ai-sdk/openai'),openaiCompatible=require('@ai-sdk/openai-compatible'),crypto=require('crypto'),async_hooks=require('async_hooks'),zod=require('zod');var oe=Object.defineProperty;var r=(e,t)=>oe(e,"name",{value:t,configurable:true});var Y=r(async(e,t,n,o)=>{let s=[],i={},u=[],c=[];for(let[a,p]of Object.entries(e)){if(p.headers&&p.getHeaders)throw new Error(`MCP server "${a}": specify either headers or getHeaders, not both`);try{let d=p.getHeaders?await p.getHeaders():p.headers,g=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(p.url),{requestInit:d?{headers:d}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});g.onerror=m=>t("warn",`[mcp] ${a}: transport error - ${m.message}`),g.onclose=()=>t("warn",`[mcp] ${a}: transport closed`);let y=new index_js.Client({name:n,version:"0.0.0"});await y.connect(g),s.push(y);let I=await y.listTools(),w=0;for(let m of I.tools){let h=`${a}__${m.name}`,l=m.description??"";i[h]=ai.dynamicTool({description:l,inputSchema:ai.jsonSchema(m.inputSchema),execute:r(async(f,x)=>{let _=await y.callTool({name:m.name,arguments:f??{}},void 0,x?.abortSignal?{signal:x.abortSignal}:void 0),T=ce(_.content);if(!o)return T;try{return await o(h,T)}catch(A){return t("warn",`[mcp] ${h}: outputSanitizer threw - ${A.message}; output replaced with placeholder`),"[output redacted: sanitizer failed]"}},"execute")}),u.push({name:h,description:l,server:a}),w++;}t("info",`[mcp] ${a}: connected, ${w} tools`),c.push({name:a,connected:!0});}catch(d){let g=d.message;t("error",`[mcp] ${a}: failed to connect - ${g}`),c.push({name:a,connected:false,error:g});}}return {tools:i,catalog:u,results:c,close:r(async()=>{await Promise.allSettled(s.map(a=>a.close()));},"close")}},"connectMcpServers"),ce=r(e=>{if(!Array.isArray(e))return e;let t=e;return t.length>0&&t.every(o=>o?.type==="text"&&typeof o.text=="string")?t.map(o=>o.text).join(`
2
+ `):t.map(o=>o?.type==="text"&&typeof o.text=="string"?o.text:o)},"flattenContent"),z=r((e,t,n,o)=>{let s=n?.length?new Set(n):null,i=o?.length?new Set(o):null,u={},c=[];for(let a of t){if(s&&!s.has(a.name)||!s&&i?.has(a.name))continue;let p=e[a.name];p&&(u[a.name]=p,c.push(a));}return {tools:u,catalog:c}},"filterTools");var v=r((e,t)=>{switch(e.providerType){case "openai":return openai.createOpenAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "anthropic":return anthropic.createAnthropic({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "openai-compatible":{if(!e.baseURL)throw new Error("openai-compatible provider requires baseURL");return openaiCompatible.createOpenAICompatible({name:e.clientName,baseURL:e.baseURL,apiKey:e.apiKey})(t)}case "google":return google.createGoogleGenerativeAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t)}},"buildModel");var k=new async_hooks.AsyncLocalStorage,he=r(()=>k.getStore()?.runId,"getCurrentRunId");var M=r(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),n=e.length-t.length,o=[];n>0&&o.push(`(${n} earlier turns omitted)`);for(let s of t){let i=s.content.length>1500?`${s.content.slice(0,1500)}... [truncated]`:s.content;o.push(`${s.role}: ${i}`);}return o.join(`
3
+ `)},"renderHistory"),fe={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},q=r((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:n,descChars:o}=fe[t],s=e.slice(0,n),i=e.length-s.length,u=s.map(c=>{let a=(c.description||"").replace(/\s+/g," ").trim().slice(0,o);return `- ${c.name}: ${a}`});return i>0&&u.push(`... and ${i} more tools`),u.join(`
4
+ `)},"renderToolCatalog"),O=1500,ye=r(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>O?`${t.slice(0,O)}... [truncated, ${t.length-O} chars]`:t},"truncateOutput"),we=r((e,t)=>{let n=e.toolCalls.length?e.toolCalls.map(o=>` - ${o.name} ${o.ok?"ok":"fail"}: ${ye(o.output)}`).join(`
5
+ `):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",n].join(`
6
+ `)},"renderTraceEntry"),$=r(e=>e.length===0?"(no steps executed yet)":e.map(we).join(`
7
+ `),"renderTrace"),N=r(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,n)=>` ${n+1}. [${t.id}] ${t.description}
8
+ expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
9
+ suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
10
+ `),"renderPlan"),H=`You are the Planner of a multi-step agent system.
242
11
 
243
12
  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.
244
13
 
@@ -248,52 +17,28 @@ Rules:
248
17
  3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
249
18
  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.
250
19
  5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
251
- 6. Output strict JSON matching the requested schema. No prose outside JSON.`;
252
- var PLANNER_NARROWED_ADDENDUM = `
20
+ 6. Output strict JSON matching the requested schema. No prose outside JSON.`,Ie=`
253
21
 
254
22
  ADDITIONAL RULE (tool-narrowed mode):
255
- 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.`;
256
- var buildPlannerSystem = (mode) => mode === "compact" ? PLANNER_SYSTEM_BASE + PLANNER_NARROWED_ADDENDUM : PLANNER_SYSTEM_BASE;
257
- var buildPlannerUserPrompt = (input, toolCatalog, history, catalogMode = "full") => [
258
- history?.length ? `Conversation history:
259
- ${renderHistory(history)}
260
- ` : "",
261
- `User request:
262
- ${input}`,
263
- "",
264
- `Available tools:
265
- ${renderToolCatalog(toolCatalog, catalogMode)}`,
266
- "",
267
- "Produce the plan now."
268
- ].filter(Boolean).join("\n");
269
- 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.
23
+ 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.`,U=r(e=>e==="compact"?H+Ie:H,"buildPlannerSystem"),B=r((e,t,n,o="full")=>[n?.length?`Conversation history:
24
+ ${M(n)}
25
+ `:"",`User request:
26
+ ${e}`,"",`Available tools:
27
+ ${q(t,o)}`,"","Produce the plan now."].filter(Boolean).join(`
28
+ `),"buildPlannerUserPrompt"),L=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
270
29
 
271
30
  Rules:
272
31
  1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
273
32
  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.
274
33
  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.
275
34
  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.
276
- 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`;
277
- var buildExecutorUserPrompt = (input, plan, step, trace, history) => [
278
- history?.length ? `Conversation history:
279
- ${renderHistory(history)}
280
- ` : "",
281
- `Original user request:
282
- ${input}`,
283
- "",
284
- `Overall plan:
285
- ${renderPlan(plan)}`,
286
- "",
287
- `Trace so far:
288
- ${renderTrace(trace)}`,
289
- "",
290
- `CURRENT STEP to execute (id=${step.id}): ${step.description}`,
291
- `Expected outcome: ${step.expectedOutcome}`,
292
- step.suggestedTools?.length ? `Suggested tools: ${step.suggestedTools.join(", ")}` : "",
293
- "",
294
- "Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."
295
- ].filter(Boolean).join("\n");
296
- var REPLANNER_SYSTEM = `You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
35
+ 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,K=r((e,t,n,o,s)=>[s?.length?`Conversation history:
36
+ ${M(s)}
37
+ `:"",`Original user request:
38
+ ${e}`,"",`Overall plan:
39
+ ${N(t)}`,"",`Trace so far:
40
+ ${$(o)}`,"",`CURRENT STEP to execute (id=${n.id}): ${n.description}`,`Expected outcome: ${n.expectedOutcome}`,n.suggestedTools?.length?`Suggested tools: ${n.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(`
41
+ `),"buildExecutorUserPrompt"),W=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
297
42
 
298
43
  You have three options:
299
44
  - "continue": the next planned step is still appropriate.
@@ -304,753 +49,27 @@ Rules:
304
49
  1. Prefer "continue" when the original plan still applies. Revise only when needed.
305
50
  2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
306
51
  3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
307
- 4. Output strict JSON matching the schema. No prose outside JSON.`;
308
- var buildReplannerUserPrompt = (input, plan, trace, nextStep, toolCatalog, catalogMode = "full") => [
309
- `Original user request:
310
- ${input}`,
311
- "",
312
- `Current plan:
313
- ${renderPlan(plan)}`,
314
- "",
315
- `Completed steps:
316
- ${renderTrace(trace)}`,
317
- "",
318
- nextStep ? `Next planned step: [${nextStep.id}] ${nextStep.description}` : "There is no next step in the current plan.",
319
- "",
320
- `Available tools (for revise option):
321
- ${renderToolCatalog(toolCatalog, catalogMode)}`,
322
- "",
323
- "Decide now: continue, revise, or finish."
324
- ].join("\n");
325
- var SYNTHESIZER_SYSTEM = `You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
52
+ 4. Output strict JSON matching the schema. No prose outside JSON.`,G=r((e,t,n,o,s,i="full")=>[`Original user request:
53
+ ${e}`,"",`Current plan:
54
+ ${N(t)}`,"",`Completed steps:
55
+ ${$(n)}`,"",o?`Next planned step: [${o.id}] ${o.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
56
+ ${q(s,i)}`,"","Decide now: continue, revise, or finish."].join(`
57
+ `),"buildReplannerUserPrompt"),F=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
326
58
 
327
59
  Rules:
328
60
  1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
329
61
  2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
330
62
  3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
331
- 4. Use the user's language.`;
332
- var buildSynthesizerUserPrompt = (input, plan, trace, history) => [
333
- history?.length ? `Conversation history:
334
- ${renderHistory(history)}
335
- ` : "",
336
- `User request:
337
- ${input}`,
338
- "",
339
- `Plan that was executed:
340
- ${renderPlan(plan)}`,
341
- "",
342
- `Execution trace:
343
- ${renderTrace(trace)}`,
344
- "",
345
- "Write the final answer for the user now."
346
- ].filter(Boolean).join("\n");
347
-
348
- // src/utils.ts
349
- var isRetriable = (err, seen = /* @__PURE__ */ new Set()) => {
350
- if (!err || typeof err !== "object") {
351
- return false;
352
- }
353
- if (seen.has(err)) {
354
- return false;
355
- }
356
- seen.add(err);
357
- const e = err;
358
- if (e.name === "AbortError") {
359
- return false;
360
- }
361
- const status = e.statusCode ?? e.status;
362
- if (typeof status === "number") {
363
- return status === 429 || status >= 500;
364
- }
365
- if (e.name === "TypeError") {
366
- return true;
367
- }
368
- if (e.cause && typeof e.cause === "object") {
369
- return isRetriable(e.cause, seen);
370
- }
371
- return false;
372
- };
373
- var withRetry = async (fn, opts) => {
374
- const base = opts.baseDelayMs ?? 500;
375
- let lastErr;
376
- for (let attempt = 0; attempt <= opts.maxRetries; attempt++) {
377
- if (opts.signal?.aborted) {
378
- throw new DOMException("Aborted", "AbortError");
379
- }
380
- try {
381
- return await fn();
382
- } catch (err) {
383
- lastErr = err;
384
- if (attempt === opts.maxRetries || !isRetriable(err)) {
385
- throw err;
386
- }
387
- opts.onRetry?.(attempt + 1, err);
388
- const delay = base * 2 ** attempt + Math.random() * 250;
389
- await sleep(delay, opts.signal);
390
- }
391
- }
392
- throw lastErr;
393
- };
394
- var sleep = (ms, signal) => new Promise((resolve, reject) => {
395
- if (signal?.aborted) {
396
- reject(new DOMException("Aborted", "AbortError"));
397
- return;
398
- }
399
- const timer = setTimeout(() => {
400
- signal?.removeEventListener("abort", onAbort);
401
- resolve();
402
- }, ms);
403
- const onAbort = () => {
404
- clearTimeout(timer);
405
- reject(new DOMException("Aborted", "AbortError"));
406
- };
407
- signal?.addEventListener("abort", onAbort, { once: true });
408
- });
409
- var combineSignals = (signals) => {
410
- const filtered = signals.filter((s) => Boolean(s));
411
- if (filtered.length === 0) {
412
- return new AbortController().signal;
413
- }
414
- if (filtered.length === 1) {
415
- return filtered[0];
416
- }
417
- return AbortSignal.any(filtered);
418
- };
419
- var withTimeout = (signal, timeoutMs) => {
420
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
421
- return signal ?? new AbortController().signal;
422
- }
423
- return combineSignals([signal, AbortSignal.timeout(timeoutMs)]);
424
- };
425
- var SECRET_HEADER_KEYS = /* @__PURE__ */ new Set([
426
- "authorization",
427
- "proxy-authorization",
428
- "x-api-key",
429
- "api-key",
430
- "cookie",
431
- "set-cookie"
432
- ]);
433
- var redactHeaders = (headers) => {
434
- if (!headers) {
435
- return headers;
436
- }
437
- const out = {};
438
- for (const [k, v] of Object.entries(headers)) {
439
- out[k] = SECRET_HEADER_KEYS.has(k.toLowerCase()) ? "***redacted***" : v;
440
- }
441
- return out;
442
- };
443
-
444
- // src/executor.ts
445
- var buildActiveToolSet = (ctx, step) => {
446
- if (ctx.config.toolSelectionStrategy !== "plan-narrowed") {
447
- return ctx.tools;
448
- }
449
- const allowed = new Set(step.suggestedTools ?? []);
450
- if (allowed.size === 0) {
451
- if (step.requiresTools) {
452
- return ctx.tools;
453
- }
454
- return {};
455
- }
456
- const filtered = {};
457
- for (const name of allowed) {
458
- const tool = ctx.tools[name];
459
- if (tool) {
460
- filtered[name] = tool;
461
- }
462
- }
463
- return filtered;
464
- };
465
- var BLOCKER_SENTINEL = "[BLOCKER]";
466
- var splitBlockerSentinel = (raw) => {
467
- const idx = raw.indexOf(BLOCKER_SENTINEL);
468
- if (idx === -1) {
469
- return { summary: raw, blocked: false };
470
- }
471
- const cleaned = (raw.slice(0, idx) + raw.slice(idx + BLOCKER_SENTINEL.length)).trim();
472
- return { summary: cleaned, blocked: true };
473
- };
474
- var SUMMARY_MAX_CHARS = 4e3;
475
- var truncateForTrace = (s) => s.length > SUMMARY_MAX_CHARS ? `${s.slice(0, SUMMARY_MAX_CHARS)}... [truncated, ${s.length - SUMMARY_MAX_CHARS} chars]` : s;
476
- var executeStep = async (input, plan, step, trace, history, ctx, signal) => {
477
- const startedAt = Date.now();
478
- const outcome = await withRetry(() => runOnce(input, plan, step, trace, history, ctx, signal), {
479
- maxRetries: ctx.config.llmMaxRetries ?? 2,
480
- signal,
481
- onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "execute", attempt, error: err.message })
482
- });
483
- ctx.emit({ type: "usage", phase: "execute", usage: outcome.usage });
484
- return {
485
- step,
486
- summary: outcome.summary,
487
- toolCalls: outcome.toolCalls,
488
- durationMs: Date.now() - startedAt,
489
- blocked: outcome.blocked
490
- };
491
- };
492
- var runOnce = async (input, plan, step, trace, history, ctx, signal) => {
493
- const toolCalls = [];
494
- const toolInputs = /* @__PURE__ */ new Map();
495
- const activeTools = buildActiveToolSet(ctx, step);
496
- const narrowed = ctx.config.toolSelectionStrategy === "plan-narrowed";
497
- const result = ai.streamText({
498
- model: ctx.executorModel,
499
- tools: activeTools,
500
- // Defence-in-depth: explicitly tell the SDK which tools are callable in
501
- // this step. Only worth it in narrowed mode; in 'all' mode it's just a
502
- // copy of every key, equivalent to omitting the field.
503
- ...narrowed ? { activeTools: Object.keys(activeTools) } : {},
504
- stopWhen: ai.stepCountIs(ctx.config.maxStepsPerTask),
505
- system: ctx.config.systemPrompt ? `${EXECUTOR_SYSTEM}
63
+ 4. Use the user's language.`,J=r((e,t,n,o)=>[o?.length?`Conversation history:
64
+ ${M(o)}
65
+ `:"",`User request:
66
+ ${e}`,"",`Plan that was executed:
67
+ ${N(t)}`,"",`Execution trace:
68
+ ${$(n)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
69
+ `),"buildSynthesizerUserPrompt");var X=r((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let n=e;if(n.name==="AbortError")return false;let o=n.statusCode??n.status;return typeof o=="number"?o===429||o>=500:n.name==="TypeError"?true:n.cause&&typeof n.cause=="object"?X(n.cause,t):false},"isRetriable"),R=r(async(e,t)=>{let n=t.baseDelayMs??500,o;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(o=i,s===t.maxRetries||!X(i))throw i;t.onRetry?.(s+1,i);let u=n*2**s+Math.random()*250;await Te(u,t.signal);}}throw o},"withRetry"),Te=r((e,t)=>new Promise((n,o)=>{if(t?.aborted){o(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",i),n();},e),i=r(()=>{clearTimeout(s),o(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),be=r(e=>{let t=e.filter(n=>!!n);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),C=r((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:be([e,AbortSignal.timeout(t)]),"withTimeout"),Se=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),Re=r(e=>{if(!e)return e;let t={};for(let[n,o]of Object.entries(e))t[n]=Se.has(n.toLowerCase())?"***redacted***":o;return t},"redactHeaders");var Ae=r((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let n=new Set(t.suggestedTools??[]);if(n.size===0)return t.requiresTools?e.tools:{};let o={};for(let s of n){let i=e.tools[s];i&&(o[s]=i);}return o},"buildActiveToolSet"),V="[BLOCKER]",ve=r(e=>{let t=e.indexOf(V);return t===-1?{summary:e,blocked:false}:{summary:(e.slice(0,t)+e.slice(t+V.length)).trim(),blocked:true}},"splitBlockerSentinel"),j=4e3,ke=r(e=>e.length>j?`${e.slice(0,j)}... [truncated, ${e.length-j} chars]`:e,"truncateForTrace"),Z=r(async(e,t,n,o,s,i,u)=>{let c=Date.now(),a=await R(()=>Ee(e,t,n,o,s,i,u),{maxRetries:i.config.llmMaxRetries??2,signal:u,onRetry:r((p,d)=>i.emit({type:"retry",phase:"execute",attempt:p,error:d.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:a.usage}),{step:n,summary:a.summary,toolCalls:a.toolCalls,durationMs:Date.now()-c,blocked:a.blocked}},"executeStep"),Ee=r(async(e,t,n,o,s,i,u)=>{let c=[],a=new Map,p=Ae(i,n),d=i.config.toolSelectionStrategy==="plan-narrowed",g=ai.streamText({model:i.executorModel,tools:p,...d?{activeTools:Object.keys(p)}:{},stopWhen:ai.stepCountIs(i.config.maxStepsPerTask),system:i.config.systemPrompt?`${L}
506
70
 
507
71
  Domain context:
508
- ${ctx.config.systemPrompt}` : EXECUTOR_SYSTEM,
509
- prompt: buildExecutorUserPrompt(input, plan, step, trace, history),
510
- abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
511
- });
512
- for await (const part of result.fullStream) {
513
- switch (part.type) {
514
- case "text-delta":
515
- if (part.text) {
516
- ctx.emit({ type: "step.text-delta", step, delta: part.text });
517
- }
518
- break;
519
- case "tool-call": {
520
- toolInputs.set(part.toolCallId, { name: part.toolName, input: part.input });
521
- ctx.emit({ type: "step.tool-call", step, name: part.toolName, input: part.input });
522
- break;
523
- }
524
- case "tool-result": {
525
- const known = toolInputs.get(part.toolCallId);
526
- toolCalls.push({
527
- name: part.toolName,
528
- input: known?.input ?? part.input,
529
- output: part.output,
530
- ok: true
531
- });
532
- ctx.emit({
533
- type: "step.tool-result",
534
- step,
535
- name: part.toolName,
536
- output: part.output,
537
- ok: true
538
- });
539
- toolInputs.delete(part.toolCallId);
540
- break;
541
- }
542
- case "tool-error": {
543
- const known = toolInputs.get(part.toolCallId);
544
- toolCalls.push({
545
- name: part.toolName,
546
- input: known?.input ?? part.input,
547
- output: part.error,
548
- ok: false
549
- });
550
- ctx.emit({
551
- type: "step.tool-result",
552
- step,
553
- name: part.toolName,
554
- output: part.error,
555
- ok: false
556
- });
557
- toolInputs.delete(part.toolCallId);
558
- break;
559
- }
560
- case "error": {
561
- const error = part.error;
562
- throw error instanceof Error ? error : new Error(String(error));
563
- }
564
- }
565
- }
566
- const [text, usage] = await Promise.all([result.text, result.usage]);
567
- const { summary: cleaned, blocked } = splitBlockerSentinel(text.trim());
568
- 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.";
569
- return {
570
- summary,
571
- toolCalls,
572
- blocked,
573
- usage: {
574
- inputTokens: usage.inputTokens ?? 0,
575
- outputTokens: usage.outputTokens ?? 0,
576
- totalTokens: usage.totalTokens ?? 0
577
- }
578
- };
579
- };
580
- var PlanStepSchema = zod.z.object({
581
- id: zod.z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),
582
- description: zod.z.string().min(1).describe("Concrete action to perform"),
583
- expectedOutcome: zod.z.string().min(1).describe("What state/data should exist after this step"),
584
- suggestedTools: zod.z.array(zod.z.string()).optional().describe("Tool names from the available list, if any")
585
- });
586
- var PlanSchema = zod.z.object({
587
- thought: zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),
588
- steps: zod.z.array(PlanStepSchema).min(1).max(8)
589
- });
590
- var createInitialPlan = async (input, history, ctx, signal) => {
591
- const validNames = new Set(ctx.toolCatalog.map((t) => t.name));
592
- const catalogMode = ctx.config.toolSelectionStrategy === "plan-narrowed" ? "compact" : "full";
593
- const { object, usage } = await withRetry(
594
- () => streamPlanOnce(input, history, catalogMode, ctx, signal),
595
- {
596
- maxRetries: ctx.config.llmMaxRetries ?? 2,
597
- signal,
598
- onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "plan", attempt, error: err.message })
599
- }
600
- );
601
- ctx.emit({ type: "usage", phase: "plan", usage });
602
- return {
603
- thought: object.thought,
604
- steps: object.steps.map((s) => {
605
- if (!s.suggestedTools?.length) {
606
- return s;
607
- }
608
- const filtered = s.suggestedTools.filter((n) => validNames.has(n));
609
- const dropped = s.suggestedTools.length - filtered.length;
610
- if (dropped > 0) {
611
- ctx.emit({
612
- type: "log",
613
- level: "warn",
614
- message: `[plan] step "${s.id}" had ${dropped} unknown suggestedTools, stripped`
615
- });
616
- }
617
- if (filtered.length === 0) {
618
- ctx.emit({
619
- type: "log",
620
- level: "warn",
621
- message: `[plan] step "${s.id}" had no valid suggestedTools left; falling back to full toolset`
622
- });
623
- return { ...s, suggestedTools: void 0, requiresTools: true };
624
- }
625
- return { ...s, suggestedTools: filtered };
626
- })
627
- };
628
- };
629
- var streamPlanOnce = async (input, history, catalogMode, ctx, signal) => {
630
- const result = ai.streamObject({
631
- model: ctx.plannerModel,
632
- schema: PlanSchema,
633
- system: ctx.config.systemPrompt ? `${buildPlannerSystem(catalogMode)}
72
+ ${i.config.systemPrompt}`:L,prompt:K(e,t,n,o,s),abortSignal:C(u,i.config.llmTimeoutMs??0)});for await(let l of g.fullStream)switch(l.type){case "text-delta":l.text&&i.emit({type:"step.text-delta",step:n,delta:l.text});break;case "tool-call":{a.set(l.toolCallId,{name:l.toolName,input:l.input}),i.emit({type:"step.tool-call",step:n,name:l.toolName,input:l.input});break}case "tool-result":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.output,ok:true}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.output,ok:true}),a.delete(l.toolCallId);break}case "tool-error":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.error,ok:false}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.error,ok:false}),a.delete(l.toolCallId);break}case "error":{let f=l.error;throw f instanceof Error?f:new Error(String(f))}}let[y,I]=await Promise.all([g.text,g.usage]),{summary:w,blocked:m}=ve(y.trim());return {summary:w.length>0?ke(w):c.length>0?`Executed ${c.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:c,blocked:m,usage:{inputTokens:I.inputTokens??0,outputTokens:I.outputTokens??0,totalTokens:I.totalTokens??0}}},"runOnce");var Oe=zod.z.object({id:zod.z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:zod.z.string().min(1).describe("Concrete action to perform"),expectedOutcome:zod.z.string().min(1).describe("What state/data should exist after this step"),suggestedTools:zod.z.array(zod.z.string()).optional().describe("Tool names from the available list, if any")}),D=zod.z.object({thought:zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:zod.z.array(Oe).min(1).max(8)}),Q=r(async(e,t,n,o)=>{let s=new Set(n.toolCatalog.map(a=>a.name)),i=n.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:u,usage:c}=await R(()=>Me(e,t,i,n,o),{maxRetries:n.config.llmMaxRetries??2,signal:o,onRetry:r((a,p)=>n.emit({type:"retry",phase:"plan",attempt:a,error:p.message}),"onRetry")});return n.emit({type:"usage",phase:"plan",usage:c}),{thought:u.thought,steps:u.steps.map(a=>{if(!a.suggestedTools?.length)return a;let p=a.suggestedTools.filter(g=>s.has(g)),d=a.suggestedTools.length-p.length;return d>0&&n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had ${d} unknown suggestedTools, stripped`}),p.length===0?(n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had no valid suggestedTools left; falling back to full toolset`}),{...a,suggestedTools:void 0,requiresTools:true}):{...a,suggestedTools:p}})}},"createInitialPlan"),Me=r(async(e,t,n,o,s)=>{let i=ai.streamObject({model:o.plannerModel,schema:D,system:o.config.systemPrompt?`${U(n)}
634
73
 
635
74
  Domain context:
636
- ${ctx.config.systemPrompt}` : buildPlannerSystem(catalogMode),
637
- prompt: buildPlannerUserPrompt(input, ctx.toolCatalog, history, catalogMode),
638
- abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
639
- });
640
- let lastThought = "";
641
- let warnedRewrite = false;
642
- for await (const partial of result.partialObjectStream) {
643
- const t = partial?.thought;
644
- if (typeof t !== "string" || t === lastThought) {
645
- continue;
646
- }
647
- if (t.startsWith(lastThought)) {
648
- ctx.emit({ type: "plan.thought-delta", delta: t.slice(lastThought.length) });
649
- } else if (!warnedRewrite) {
650
- ctx.emit({
651
- type: "log",
652
- level: "warn",
653
- message: "[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"
654
- });
655
- warnedRewrite = true;
656
- }
657
- lastThought = t;
658
- }
659
- const [object, rawUsage] = await Promise.all([result.object, result.usage]);
660
- return {
661
- object,
662
- usage: {
663
- inputTokens: rawUsage.inputTokens ?? 0,
664
- outputTokens: rawUsage.outputTokens ?? 0,
665
- totalTokens: rawUsage.totalTokens ?? 0
666
- }
667
- };
668
- };
669
- var DecisionSchema = zod.z.discriminatedUnion("mode", [
670
- zod.z.object({
671
- mode: zod.z.literal("continue"),
672
- reason: zod.z.string().min(1).describe("Why the next step is still appropriate")
673
- }),
674
- zod.z.object({
675
- mode: zod.z.literal("finish"),
676
- reason: zod.z.string().min(1).describe("Why no more steps are needed")
677
- }),
678
- zod.z.object({
679
- mode: zod.z.literal("revise"),
680
- reason: zod.z.string().min(1).describe("Why the plan must change"),
681
- newPlan: PlanSchema.describe("Plan covering ONLY the remaining work")
682
- })
683
- ]);
684
- var decideNextAction = async (input, plan, trace, nextStep, ctx, signal) => {
685
- const catalogMode = ctx.config.toolSelectionStrategy === "plan-narrowed" ? "compact" : "full";
686
- const { object, usage } = await withRetry(
687
- async () => {
688
- const r = await ai.generateObject({
689
- model: ctx.plannerModel,
690
- schema: DecisionSchema,
691
- system: REPLANNER_SYSTEM,
692
- prompt: buildReplannerUserPrompt(
693
- input,
694
- plan,
695
- trace,
696
- nextStep,
697
- ctx.toolCatalog,
698
- catalogMode
699
- ),
700
- abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
701
- });
702
- const usage2 = {
703
- inputTokens: r.usage.inputTokens ?? 0,
704
- outputTokens: r.usage.outputTokens ?? 0,
705
- totalTokens: r.usage.totalTokens ?? 0
706
- };
707
- return { object: r.object, usage: usage2 };
708
- },
709
- {
710
- maxRetries: ctx.config.llmMaxRetries ?? 2,
711
- signal,
712
- onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "replan", attempt, error: err.message })
713
- }
714
- );
715
- ctx.emit({ type: "usage", phase: "replan", usage });
716
- return object;
717
- };
718
- var synthesizeAnswer = async (input, plan, trace, history, ctx, signal) => {
719
- const { text, usage } = await withRetry(
720
- () => streamOnce(input, plan, trace, history, ctx, signal),
721
- {
722
- maxRetries: ctx.config.llmMaxRetries ?? 2,
723
- signal,
724
- onRetry: (attempt, err) => ctx.emit({ type: "retry", phase: "synthesize", attempt, error: err.message })
725
- }
726
- );
727
- ctx.emit({ type: "usage", phase: "synthesize", usage });
728
- return text;
729
- };
730
- var streamOnce = async (input, plan, trace, history, ctx, signal) => {
731
- const result = ai.streamText({
732
- model: ctx.synthesizerModel,
733
- system: SYNTHESIZER_SYSTEM,
734
- prompt: buildSynthesizerUserPrompt(input, plan, trace, history),
735
- abortSignal: withTimeout(signal, ctx.config.llmTimeoutMs ?? 0)
736
- });
737
- for await (const part of result.fullStream) {
738
- if (part.type === "text-delta") {
739
- if (part.text) {
740
- ctx.emit({ type: "final.text-delta", delta: part.text });
741
- }
742
- } else if (part.type === "error") {
743
- const error = part.error;
744
- throw error instanceof Error ? error : new Error(String(error));
745
- }
746
- }
747
- const [text, rawUsage] = await Promise.all([result.text, result.usage]);
748
- return {
749
- text,
750
- usage: {
751
- inputTokens: rawUsage.inputTokens ?? 0,
752
- outputTokens: rawUsage.outputTokens ?? 0,
753
- totalTokens: rawUsage.totalTokens ?? 0
754
- }
755
- };
756
- };
757
-
758
- // src/runner.ts
759
- var shouldCallReplanner = (result) => {
760
- if (result.blocked) {
761
- return true;
762
- }
763
- if (result.toolCalls.some((c) => !c.ok)) {
764
- return true;
765
- }
766
- return false;
767
- };
768
- var isAbortError = (err) => Boolean(err) && typeof err === "object" && err.name === "AbortError";
769
- var runAgentLoop = async (ctx, options) => {
770
- const runId = crypto.randomUUID();
771
- return runContext.run({ runId, startedAt: Date.now() }, () => runAgentLoopInner(ctx, options));
772
- };
773
- var runAgentLoopInner = async (ctx, options) => {
774
- const { input, signal } = options;
775
- const history = options.history ? [...options.history] : void 0;
776
- const onEvent = options.onEvent ?? (() => {
777
- });
778
- const totalUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
779
- const proxiedCtx = {
780
- ...ctx,
781
- emit: (event) => {
782
- if (event.type === "usage") {
783
- totalUsage.inputTokens += event.usage.inputTokens;
784
- totalUsage.outputTokens += event.usage.outputTokens;
785
- totalUsage.totalTokens += event.usage.totalTokens;
786
- }
787
- const tagged = { ...event, runId: runContext.getStore()?.runId };
788
- try {
789
- onEvent(tagged);
790
- } catch {
791
- }
792
- try {
793
- ctx.emit(tagged);
794
- } catch {
795
- }
796
- }
797
- };
798
- let plan;
799
- try {
800
- plan = await createInitialPlan(input, history, proxiedCtx, signal);
801
- } catch (err) {
802
- proxiedCtx.emit({ type: "error", error: asError(err), phase: "plan" });
803
- if (isAbortError(err) || signal?.aborted) {
804
- throw err;
805
- }
806
- plan = {
807
- thought: "Planner failed; answering directly without tool use.",
808
- steps: [
809
- {
810
- id: "fallback",
811
- description: "Answer the user directly using prior conversation and general knowledge.",
812
- expectedOutcome: "A direct answer to the user request."
813
- }
814
- ]
815
- };
816
- }
817
- proxiedCtx.emit({ type: "plan.created", plan });
818
- const trace = [];
819
- let currentPlan = plan;
820
- let stepIndex = 0;
821
- let iterations = 0;
822
- let revisions = 0;
823
- const maxRevisions = ctx.config.maxRevisions ?? 2;
824
- const tokenCap = ctx.config.maxTotalTokens;
825
- while (iterations < ctx.config.maxIterations) {
826
- iterations++;
827
- if (signal?.aborted) {
828
- throw new DOMException("Aborted", "AbortError");
829
- }
830
- if (stepIndex >= currentPlan.steps.length) {
831
- break;
832
- }
833
- if (tokenCap && totalUsage.totalTokens >= tokenCap) {
834
- proxiedCtx.emit({ type: "budget.exceeded", tokens: totalUsage.totalTokens, cap: tokenCap });
835
- break;
836
- }
837
- const step = currentPlan.steps[stepIndex];
838
- proxiedCtx.emit({ type: "step.start", step, index: stepIndex });
839
- let result;
840
- try {
841
- result = await executeStep(input, currentPlan, step, trace, history, proxiedCtx, signal);
842
- } catch (err) {
843
- proxiedCtx.emit({ type: "error", error: asError(err), phase: "execute" });
844
- throw err;
845
- }
846
- trace.push(result);
847
- proxiedCtx.emit({ type: "step.complete", step, result });
848
- const nextStep = currentPlan.steps[stepIndex + 1] ?? null;
849
- const isLastPlannedStep = nextStep === null;
850
- if (isLastPlannedStep) {
851
- proxiedCtx.emit({
852
- type: "replan.decision",
853
- mode: "finish",
854
- reason: "last planned step reached",
855
- cause: "last-step"
856
- });
857
- break;
858
- }
859
- if (!shouldCallReplanner(result)) {
860
- proxiedCtx.emit({
861
- type: "replan.decision",
862
- mode: "continue",
863
- reason: "step succeeded cleanly, skipping LLM replanner",
864
- cause: "clean-step"
865
- });
866
- stepIndex++;
867
- continue;
868
- }
869
- let decision;
870
- try {
871
- decision = await decideNextAction(input, currentPlan, trace, nextStep, proxiedCtx, signal);
872
- } catch (err) {
873
- proxiedCtx.emit({ type: "error", error: asError(err), phase: "replan" });
874
- throw err;
875
- }
876
- proxiedCtx.emit({
877
- type: "replan.decision",
878
- mode: decision.mode,
879
- reason: decision.reason,
880
- cause: "llm-decision"
881
- });
882
- if (decision.mode === "finish") {
883
- break;
884
- }
885
- if (decision.mode === "revise") {
886
- if (revisions >= maxRevisions) {
887
- proxiedCtx.emit({ type: "revisions.exceeded", cap: maxRevisions });
888
- break;
889
- }
890
- revisions++;
891
- currentPlan = decision.newPlan;
892
- proxiedCtx.emit({ type: "plan.revised", plan: currentPlan, reason: decision.reason });
893
- stepIndex = 0;
894
- continue;
895
- }
896
- stepIndex++;
897
- }
898
- let text;
899
- try {
900
- text = await synthesizeAnswer(input, currentPlan, trace, history, proxiedCtx, signal);
901
- } catch (err) {
902
- proxiedCtx.emit({ type: "error", error: asError(err), phase: "synthesize" });
903
- throw err;
904
- }
905
- proxiedCtx.emit({ type: "final", text });
906
- return { text, plan: currentPlan, trace, iterations, usage: totalUsage };
907
- };
908
- var asError = (err) => err instanceof Error ? err : new Error(typeof err === "string" ? err : JSON.stringify(err));
909
-
910
- // src/index.ts
911
- var LEVEL_RANK = {
912
- none: 0,
913
- error: 1,
914
- warn: 2,
915
- info: 3,
916
- debug: 4
917
- };
918
- var createAgent = async (config, baseEventHandler) => {
919
- const debugMode = LEVEL_RANK[config.logLevel] >= LEVEL_RANK.debug;
920
- const emit = (event) => {
921
- if (baseEventHandler) {
922
- try {
923
- baseEventHandler(event);
924
- } catch (err) {
925
- if (debugMode) {
926
- console.error("[agent] event handler threw:", err);
927
- }
928
- }
929
- }
930
- };
931
- const log = (level, message) => {
932
- if (LEVEL_RANK[config.logLevel] >= LEVEL_RANK[level]) {
933
- emit({ type: "log", level, message });
934
- }
935
- };
936
- const connect = async () => {
937
- const c = await connectMcpServers(
938
- config.mcpServers,
939
- log,
940
- config.clientName,
941
- config.outputSanitizer
942
- );
943
- const f = filterTools(c.tools, c.catalog, config.availableTools, config.excludedTools);
944
- return { connection: c, tools: f.tools, catalog: f.catalog };
945
- };
946
- let connected;
947
- try {
948
- connected = await connect();
949
- } catch (err) {
950
- emit({
951
- type: "error",
952
- error: err instanceof Error ? err : new Error(String(err)),
953
- phase: "init"
954
- });
955
- throw err;
956
- }
957
- const configuredServers = Object.keys(config.mcpServers).length;
958
- if (config.failOnNoTools && configuredServers > 0) {
959
- const anyConnected = connected.connection.results.some((r) => r.connected);
960
- if (!anyConnected) {
961
- const reasons = connected.connection.results.filter((r) => !r.connected).map((r) => `${r.name}: ${r.error ?? "unknown"}`).join("; ");
962
- await connected.connection.close().catch(() => {
963
- });
964
- const err = new Error(
965
- `All ${configuredServers} configured MCP server(s) failed to connect [${reasons}]`
966
- );
967
- emit({ type: "error", error: err, phase: "init" });
968
- throw err;
969
- }
970
- }
971
- const executorModel = buildModel(config, config.model);
972
- const plannerModel = buildModel(config, config.plannerModel ?? config.model);
973
- const synthesizerModel = buildModel(config, config.synthesizerModel ?? config.model);
974
- const ctx = {
975
- config,
976
- executorModel,
977
- plannerModel,
978
- synthesizerModel,
979
- tools: connected.tools,
980
- toolCatalog: connected.catalog.map((c) => ({ name: c.name, description: c.description })),
981
- emit
982
- };
983
- let activeRuns = 0;
984
- let closed = false;
985
- let reconnecting = false;
986
- return {
987
- run: async (options) => {
988
- if (closed) {
989
- throw new Error("Agent is closed");
990
- }
991
- if (reconnecting) {
992
- throw new Error("Agent is reconnecting; retry shortly");
993
- }
994
- activeRuns++;
995
- try {
996
- return await runAgentLoop(ctx, options);
997
- } finally {
998
- activeRuns--;
999
- }
1000
- },
1001
- listTools: () => ctx.toolCatalog.slice(),
1002
- reconnect: async () => {
1003
- if (closed) {
1004
- throw new Error("Agent is closed");
1005
- }
1006
- if (reconnecting) {
1007
- throw new Error("Already reconnecting");
1008
- }
1009
- if (activeRuns > 0) {
1010
- throw new Error(`Cannot reconnect with ${activeRuns} active run(s)`);
1011
- }
1012
- reconnecting = true;
1013
- try {
1014
- const oldConnection = connected.connection;
1015
- const fresh = await connect();
1016
- for (const k of Object.keys(ctx.tools)) {
1017
- delete ctx.tools[k];
1018
- }
1019
- Object.assign(ctx.tools, fresh.tools);
1020
- ctx.toolCatalog = fresh.catalog.map((c) => ({ name: c.name, description: c.description }));
1021
- connected = fresh;
1022
- await oldConnection.close().catch(() => {
1023
- });
1024
- } finally {
1025
- reconnecting = false;
1026
- }
1027
- },
1028
- close: async (options) => {
1029
- closed = true;
1030
- const waitForRuns = options?.waitForRuns ?? false;
1031
- const timeoutMs = options?.timeoutMs ?? 3e4;
1032
- if (waitForRuns && activeRuns > 0) {
1033
- const start = Date.now();
1034
- while (activeRuns > 0 && Date.now() - start < timeoutMs) {
1035
- await new Promise((r) => setTimeout(r, 50));
1036
- }
1037
- }
1038
- if (activeRuns > 0) {
1039
- emit({
1040
- type: "log",
1041
- level: "warn",
1042
- message: `[agent] close called with ${activeRuns} active run(s); they will fail mid-flight`
1043
- });
1044
- }
1045
- await connected.connection.close().catch(() => {
1046
- });
1047
- },
1048
- activeRuns: () => activeRuns
1049
- };
1050
- };
1051
-
1052
- exports.createAgent = createAgent;
1053
- exports.getCurrentRunId = getCurrentRunId;
1054
- exports.redactHeaders = redactHeaders;
1055
- //# sourceMappingURL=index.cjs.map
1056
- //# sourceMappingURL=index.cjs.map
75
+ ${o.config.systemPrompt}`:U(n),prompt:B(e,o.toolCatalog,t,n),abortSignal:C(s,o.config.llmTimeoutMs??0)}),u="",c=false;for await(let d of i.partialObjectStream){let g=d?.thought;typeof g!="string"||g===u||(g.startsWith(u)?o.emit({type:"plan.thought-delta",delta:g.slice(u.length)}):c||(o.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),c=true),u=g);}let[a,p]=await Promise.all([i.object,i.usage]);return {object:a,usage:{inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,totalTokens:p.totalTokens??0}}},"streamPlanOnce");var Ne=zod.z.discriminatedUnion("mode",[zod.z.object({mode:zod.z.literal("continue"),reason:zod.z.string().min(1).describe("Why the next step is still appropriate")}),zod.z.object({mode:zod.z.literal("finish"),reason:zod.z.string().min(1).describe("Why no more steps are needed")}),zod.z.object({mode:zod.z.literal("revise"),reason:zod.z.string().min(1).describe("Why the plan must change"),newPlan:D.describe("Plan covering ONLY the remaining work")})]),ee=r(async(e,t,n,o,s,i)=>{let u=s.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:a}=await R(async()=>{let p=await ai.generateObject({model:s.plannerModel,schema:Ne,system:W,prompt:G(e,t,n,o,s.toolCatalog,u),abortSignal:C(i,s.config.llmTimeoutMs??0)}),d={inputTokens:p.usage.inputTokens??0,outputTokens:p.usage.outputTokens??0,totalTokens:p.usage.totalTokens??0};return {object:p.object,usage:d}},{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((p,d)=>s.emit({type:"retry",phase:"replan",attempt:p,error:d.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:a}),c},"decideNextAction");var te=r(async(e,t,n,o,s,i)=>{let{text:u,usage:c}=await R(()=>Le(e,t,n,o,s,i),{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((a,p)=>s.emit({type:"retry",phase:"synthesize",attempt:a,error:p.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:c}),u},"synthesizeAnswer"),Le=r(async(e,t,n,o,s,i)=>{let u=ai.streamText({model:s.synthesizerModel,system:F,prompt:J(e,t,n,o),abortSignal:C(i,s.config.llmTimeoutMs??0)});for await(let p of u.fullStream)if(p.type==="text-delta")p.text&&s.emit({type:"final.text-delta",delta:p.text});else if(p.type==="error"){let d=p.error;throw d instanceof Error?d:new Error(String(d))}let[c,a]=await Promise.all([u.text,u.usage]);return {text:c,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamOnce");var De=r(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),_e=r(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),ne=r(async(e,t)=>{let n=crypto.randomUUID();return k.run({runId:n,startedAt:Date.now()},()=>Ye(e,t))},"runAgentLoop"),Ye=r(async(e,t)=>{let{input:n,signal:o}=t,s=t.history?[...t.history]:void 0,i=t.onEvent??(()=>{}),u={inputTokens:0,outputTokens:0,totalTokens:0},c={...e,emit:r(l=>{l.type==="usage"&&(u.inputTokens+=l.usage.inputTokens,u.outputTokens+=l.usage.outputTokens,u.totalTokens+=l.usage.totalTokens);let f={...l,runId:k.getStore()?.runId};try{i(f);}catch{}try{e.emit(f);}catch{}},"emit")},a;try{a=await Q(n,s,c,o);}catch(l){if(c.emit({type:"error",error:E(l),phase:"plan"}),_e(l)||o?.aborted)throw l;a={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."}]};}c.emit({type:"plan.created",plan:a});let p=[],d=a,g=0,y=0,I=0,w=e.config.maxRevisions??2,m=e.config.maxTotalTokens;for(;y<e.config.maxIterations;){if(y++,o?.aborted)throw new DOMException("Aborted","AbortError");if(g>=d.steps.length)break;if(m&&u.totalTokens>=m){c.emit({type:"budget.exceeded",tokens:u.totalTokens,cap:m});break}let l=d.steps[g];c.emit({type:"step.start",step:l,index:g});let f;try{f=await Z(n,d,l,p,s,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"execute"}),A}p.push(f),c.emit({type:"step.complete",step:l,result:f});let x=d.steps[g+1]??null;if(x===null){c.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!De(f)){c.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),g++;continue}let T;try{T=await ee(n,d,p,x,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"replan"}),A}if(c.emit({type:"replan.decision",mode:T.mode,reason:T.reason,cause:"llm-decision"}),T.mode==="finish")break;if(T.mode==="revise"){if(I>=w){c.emit({type:"revisions.exceeded",cap:w});break}I++,d=T.newPlan,c.emit({type:"plan.revised",plan:d,reason:T.reason}),g=0;continue}g++;}let h;try{h=await te(n,d,p,s,c,o);}catch(l){throw c.emit({type:"error",error:E(l),phase:"synthesize"}),l}return c.emit({type:"final",text:h}),{text:h,plan:d,trace:p,iterations:y,usage:u}},"runAgentLoopInner"),E=r(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var P={none:0,error:1,warn:2,info:3,debug:4},zt=r(async(e,t)=>{let n=P[e.logLevel]>=P.debug,o=r(m=>{if(t)try{t(m);}catch(h){n&&console.error("[agent] event handler threw:",h);}},"emit"),s=r((m,h)=>{P[e.logLevel]>=P[m]&&o({type:"log",level:m,message:h});},"log"),i=r(async()=>{let m=await Y(e.mcpServers,s,e.clientName,e.outputSanitizer),h=z(m.tools,m.catalog,e.availableTools,e.excludedTools);return {connection:m,tools:h.tools,catalog:h.catalog}},"connect"),u;try{u=await i();}catch(m){throw o({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let c=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&c>0&&!u.connection.results.some(h=>h.connected)){let h=u.connection.results.filter(f=>!f.connected).map(f=>`${f.name}: ${f.error??"unknown"}`).join("; ");await u.connection.close().catch(()=>{});let l=new Error(`All ${c} configured MCP server(s) failed to connect [${h}]`);throw o({type:"error",error:l,phase:"init"}),l}let a=v(e,e.model),p=v(e,e.plannerModel??e.model),d=v(e,e.synthesizerModel??e.model),g={config:e,executorModel:a,plannerModel:p,synthesizerModel:d,tools:u.tools,toolCatalog:u.catalog.map(m=>({name:m.name,description:m.description})),emit:o},y=0,I=false,w=false;return {run:r(async m=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Agent is reconnecting; retry shortly");y++;try{return await ne(g,m)}finally{y--;}},"run"),listTools:r(()=>g.toolCatalog.slice(),"listTools"),reconnect:r(async()=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Already reconnecting");if(y>0)throw new Error(`Cannot reconnect with ${y} active run(s)`);w=true;try{let m=u.connection,h=await i();for(let l of Object.keys(g.tools))delete g.tools[l];Object.assign(g.tools,h.tools),g.toolCatalog=h.catalog.map(l=>({name:l.name,description:l.description})),u=h,await m.close().catch(()=>{});}finally{w=false;}},"reconnect"),close:r(async m=>{I=true;let h=m?.waitForRuns??false,l=m?.timeoutMs??3e4;if(h&&y>0){let f=Date.now();for(;y>0&&Date.now()-f<l;)await new Promise(x=>setTimeout(x,50));}y>0&&o({type:"log",level:"warn",message:`[agent] close called with ${y} active run(s); they will fail mid-flight`}),await u.connection.close().catch(()=>{});},"close"),activeRuns:r(()=>y,"activeRuns")}},"createAgent");exports.createAgent=zt;exports.getCurrentRunId=he;exports.redactHeaders=Re;