@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/index.cjs
CHANGED
|
@@ -1,244 +1,16 @@
|
|
|
1
|
-
'use strict';
|
|
1
|
+
'use strict';var index_js=require('@modelcontextprotocol/sdk/client/index.js'),stdio_js=require('@modelcontextprotocol/sdk/client/stdio.js'),streamableHttp_js=require('@modelcontextprotocol/sdk/client/streamableHttp.js'),types_js=require('@modelcontextprotocol/sdk/types.js'),ai=require('ai'),crypto=require('crypto'),promises=require('fs/promises'),ve=require('path'),url=require('url'),async_hooks=require('async_hooks'),api=require('@opentelemetry/api'),anthropic=require('@ai-sdk/anthropic'),google=require('@ai-sdk/google'),openai=require('@ai-sdk/openai'),openaiCompatible=require('@ai-sdk/openai-compatible'),os=require('os'),zod=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ve__default=/*#__PURE__*/_interopDefault(ve);var xe=Object.defineProperty;var s=(e,t)=>xe(e,"name",{value:t,configurable:true});var K={version:"0.0.3"};var j=new async_hooks.AsyncLocalStorage,Pe=s(()=>j.getStore()?.runId,"getCurrentRunId"),G=s(()=>j.getStore()?.sandboxDir,"getCurrentRunSandbox");var Me="@dudko.dev/agent",Ne=K.version,W,_e=s(()=>(W||(W=api.trace.getTracer(Me,Ne)),W),"tracer"),b={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=s(async(e,t,n)=>_e().startActiveSpan(e,async o=>{for(let[r,a]of Object.entries(t))a!==void 0&&o.setAttribute(r,a);try{let r=await n(o);return o.end(),r}catch(r){let a=r instanceof Error?r:new Error(String(r));throw o.recordException(a),o.setStatus({code:api.SpanStatusCode.ERROR,message:a.message}),o.end(),r}}),"withSpan");var We=s(e=>"command"in e&&!!e.command,"isStdioConfig"),Je=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Ve=K.version,re=64,ie=s(async(e,t,n,o,r,a)=>{let d=new Map,u={},p=[],i=[],c=s(async(m,g)=>{for(let y of Object.keys(u))y.startsWith(`${m}__`)&&delete u[y];for(let y=p.length-1;y>=0;y--)p[y].server===m&&p.splice(y,1);let v=await g.listTools(),w=0,R=0;for(let y of v.tools){let I=`${m}__${y.name}`;if(I.length>re){t("warn",`[mcp] ${m}: tool "${y.name}" prefixed name (${I.length} chars) exceeds the ${re}-char limit enforced by major LLM providers; skipping`),R++;continue}let f=y.description??"";u[I]=ai.dynamicTool({description:f,inputSchema:ai.jsonSchema(y.inputSchema),execute:s(async(A,x)=>C("agent.tool_call",{[b.TOOL_NAME]:I},async E=>{let P=A??{};if(a)try{let T=await a(I,P);P=T&&typeof T=="object"&&!Array.isArray(T)?T:{value:T};}catch(T){t("warn",`[mcp] ${I}: inputSanitizer threw - ${T.message}; input replaced with placeholder`),P={_redacted:"inputSanitizer failed"};}let O;try{O=await g.callTool({name:y.name,arguments:P},void 0,x?.abortSignal?{signal:x.abortSignal}:void 0);}catch(T){throw E.setAttribute(b.TOOL_OK,false),T}let l=O.content;if(o)try{l=await o(I,l);}catch(T){return t("warn",`[mcp] ${I}: outputSanitizer threw - ${T.message}; output replaced with placeholder`),E.setAttribute(b.TOOL_OK,false),"[output redacted: sanitizer failed]"}let h=await Qe(l,{toolName:I,sandboxDir:G()});return E.setAttribute(b.TOOL_OK,true),h}),"execute")}),p.push({name:I,description:f,server:m}),w++;}R>0?t("info",`[mcp] ${m}: ${w} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${m}: ${w} tools mounted`);},"registerServerTools");for(let[m,g]of Object.entries(e))try{let v;if(We(g)){let R=g.env?{...stdio_js.getDefaultEnvironment(),...g.env}:void 0;v=new stdio_js.StdioClientTransport({command:g.command,args:g.args,env:R,cwd:g.cwd});}else if(Je(g)){if(g.headers&&g.getHeaders)throw new Error(`MCP server "${m}": specify either headers or getHeaders, not both`);let R=g.getHeaders?await g.getHeaders():g.headers;v=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(g.url),{requestInit:R?{headers:R}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${m}": config must specify either { url } (HTTP) or { command } (stdio)`);v.onerror=R=>t("warn",`[mcp] ${m}: transport error - ${R.message}`),v.onclose=()=>t("warn",`[mcp] ${m}: transport closed`);let w=new index_js.Client({name:n,version:Ve});await w.connect(v),d.set(m,w),r&&w.setNotificationHandler(types_js.ToolListChangedNotificationSchema,()=>{r(m);}),await c(m,w),i.push({name:m,connected:!0});}catch(v){let w=v.message;t("error",`[mcp] ${m}: failed to connect - ${w}`),i.push({name:m,connected:false,error:w});}return {tools:u,catalog:p,results:i,close:s(async()=>{await Promise.allSettled([...d.values()].map(m=>m.close()));},"close"),refreshServer:s(async m=>{let g=d.get(m);if(!g)throw new Error(`MCP server "${m}" is not connected`);await c(m,g);},"refreshServer")}},"connectMcpServers"),se={image:".bin",audio:".bin",resource:".bin"},Xe=s((e,t)=>{if(!e)return se[t];let n=e.indexOf("/"),r=(n>=0?e.slice(n+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?se[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"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Ze=/[^a-zA-Z0-9_-]/g,ae=s(async(e,t,n,o,r,a)=>{await a();let d=Xe(t,n),u=o.replace(Ze,"_").slice(0,32)||"tool",p=crypto.randomUUID().slice(0,8),i=ve__default.default.join(r,`${n}-${u}-${p}${d}`),c=Buffer.from(e,"base64");return await promises.writeFile(i,c),{type:"file",kind:n,path:i,mimeType:t,bytes:c.byteLength}},"spillBase64"),Qe=s(async(e,t)=>{if(!Array.isArray(e))return e;let n=e;if(n.length>0&&n.every(i=>i?.type==="text"&&typeof i.text=="string"))return n.map(i=>i.text).join(`
|
|
2
|
+
`);let r=t?.sandboxDir,a=t?.toolName??"tool",d,u=s(()=>r?(d||(d=promises.mkdir(r,{recursive:true}).then(()=>{})),d):Promise.resolve(),"ensureDir"),p=[];for(let i of n){if(i?.type==="text"&&typeof i.text=="string"){p.push(i.text);continue}if(r&&(i?.type==="image"||i?.type==="audio")&&typeof i.data=="string"){let c=await ae(i.data,typeof i.mimeType=="string"?i.mimeType:void 0,i.type,a,r,u);p.push(c);continue}if(r&&i?.type==="resource"&&i.resource&&typeof i.resource=="object"){let c=i.resource;if(typeof c.blob=="string"){let m=await ae(c.blob,typeof c.mimeType=="string"?c.mimeType:void 0,"resource",a,r,u);typeof c.uri=="string"&&(m.uri=c.uri),p.push(m);continue}if(typeof c.text=="string"){p.push(c.text);continue}}p.push(i);}return p},"flattenContent"),J=s((e,t,n,o)=>{let r=n?.length?new Set(n):null,a=o?.length?new Set(o):null,d={},u=[];for(let p of t){if(r&&!r.has(p.name)||!r&&a?.has(p.name))continue;let i=e[p.name];i&&(d[p.name]=i,u.push(p));}return {tools:d,catalog:u}},"filterTools");var H=s((e,t,n,o)=>{let r=t?.providerType??e.providerType,a=t?.apiKey??e.apiKey,d=t?.baseURL??e.baseURL,u=t?.model??n??e.model;if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${o}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${o}.apiKey (cross-provider key inheritance is unsafe)`);if(r==="openai-compatible"&&!d)throw new Error(`${o}: provider "openai-compatible" requires a baseURL (set ${o}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:d,apiKey:a,model:u}},"resolveStage"),F=s((e,t)=>{switch(t.providerType){case "openai":return openai.createOpenAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "anthropic":return anthropic.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 openaiCompatible.createOpenAICompatible({name:e,baseURL:t.baseURL,apiKey:t.apiKey})(t.model)}case "google":return google.createGoogleGenerativeAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model)}},"buildModelFromStage");var X=s(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 r of t){let a=r.content.length>1500?`${r.content.slice(0,1500)}... [truncated]`:r.content;o.push(`${r.role}: ${a}`);}return o.join(`
|
|
3
|
+
`)},"renderHistory"),rt={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},ce=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:n,descChars:o}=rt[t],r=e.slice(0,n),a=e.length-r.length,d=r.map(u=>{let p=(u.description||"").replace(/\s+/g," ").trim().slice(0,o);return `- ${u.name}: ${p}`});return a>0&&d.push(`... and ${a} more tools`),d.join(`
|
|
4
|
+
`)},"renderToolCatalog"),V=1500,st=s(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>V?`${t.slice(0,V)}... [truncated, ${t.length-V} chars]`:t},"truncateOutput"),at=s((e,t)=>{let n=e.toolCalls.length?e.toolCalls.map(o=>` - ${o.name} ${o.ok?"ok":"fail"}: ${st(o.output)}`).join(`
|
|
5
|
+
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",n].join(`
|
|
6
|
+
`)},"renderTraceEntry"),Z=s(e=>e.length===0?"(no steps executed yet)":e.map(at).join(`
|
|
7
|
+
`),"renderTrace"),Q=s(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"),_=s((e,t)=>t?`${e}
|
|
2
11
|
|
|
3
|
-
|
|
4
|
-
|
|
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.
|
|
12
|
+
Domain context:
|
|
13
|
+
${t}`:e,"withDomainContext"),le=`You are the Planner of a multi-step agent system.
|
|
242
14
|
|
|
243
15
|
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
16
|
|
|
@@ -248,52 +20,28 @@ Rules:
|
|
|
248
20
|
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
249
21
|
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
22
|
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 = `
|
|
23
|
+
6. Output strict JSON matching the requested schema. No prose outside JSON.`,it=`
|
|
253
24
|
|
|
254
25
|
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
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
${
|
|
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.
|
|
26
|
+
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.`,pe=s(e=>e==="compact"?le+it:le,"buildPlannerSystem"),ue=s((e,t,n,o="full")=>[n?.length?`Conversation history:
|
|
27
|
+
${X(n)}
|
|
28
|
+
`:"",`User request:
|
|
29
|
+
${e}`,"",`Available tools:
|
|
30
|
+
${ce(t,o)}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
31
|
+
`),"buildPlannerUserPrompt"),de=`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
32
|
|
|
271
33
|
Rules:
|
|
272
34
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
273
35
|
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
36
|
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
37
|
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
|
-
|
|
278
|
-
|
|
279
|
-
${
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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.
|
|
38
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,me=s((e,t,n,o,r)=>[r?.length?`Conversation history:
|
|
39
|
+
${X(r)}
|
|
40
|
+
`:"",`Original user request:
|
|
41
|
+
${e}`,"",`Overall plan:
|
|
42
|
+
${Q(t)}`,"",`Trace so far:
|
|
43
|
+
${Z(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(`
|
|
44
|
+
`),"buildExecutorUserPrompt"),ge=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
|
|
297
45
|
|
|
298
46
|
You have three options:
|
|
299
47
|
- "continue": the next planned step is still appropriate.
|
|
@@ -304,753 +52,21 @@ Rules:
|
|
|
304
52
|
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
305
53
|
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
306
54
|
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
|
-
|
|
309
|
-
|
|
310
|
-
${
|
|
311
|
-
|
|
312
|
-
|
|
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.
|
|
55
|
+
4. Output strict JSON matching the schema. No prose outside JSON.`,fe=s((e,t,n,o,r,a="full")=>[`Original user request:
|
|
56
|
+
${e}`,"",`Current plan:
|
|
57
|
+
${Q(t)}`,"",`Completed steps:
|
|
58
|
+
${Z(n)}`,"",o?`Next planned step: [${o.id}] ${o.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
|
|
59
|
+
${ce(r,a)}`,"","Decide now: continue, revise, or finish."].join(`
|
|
60
|
+
`),"buildReplannerUserPrompt"),he=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
326
61
|
|
|
327
62
|
Rules:
|
|
328
63
|
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
329
64
|
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
330
65
|
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
|
-
|
|
333
|
-
|
|
334
|
-
${
|
|
335
|
-
|
|
336
|
-
|
|
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}
|
|
506
|
-
|
|
507
|
-
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)}
|
|
634
|
-
|
|
635
|
-
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
|
|
66
|
+
4. Use the user's language.`,ye=s((e,t,n,o)=>[o?.length?`Conversation history:
|
|
67
|
+
${X(o)}
|
|
68
|
+
`:"",`User request:
|
|
69
|
+
${e}`,"",`Plan that was executed:
|
|
70
|
+
${Q(t)}`,"",`Execution trace:
|
|
71
|
+
${Z(n)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
72
|
+
`),"buildSynthesizerUserPrompt");var we=s((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"?we(n.cause,t):false},"isRetriable"),L=s(async(e,t)=>{let n=t.baseDelayMs??500,o;for(let r=0;r<=t.maxRetries;r++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(a){if(o=a,r===t.maxRetries||!we(a))throw a;t.onRetry?.(r+1,a);let d=n*2**r+Math.random()*250;await lt(d,t.signal);}}throw o},"withRetry"),lt=s((e,t)=>new Promise((n,o)=>{if(t?.aborted){o(new DOMException("Aborted","AbortError"));return}let r=setTimeout(()=>{t?.removeEventListener("abort",a),n();},e),a=s(()=>{clearTimeout(r),o(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",a,{once:true});}),"sleep"),ee=s(e=>{let t=e.filter(n=>!!n);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),U=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:ee([e,AbortSignal.timeout(t)]),"withTimeout"),ct=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),pt=s(e=>{if(!e)return e;let t={};for(let[n,o]of Object.entries(e))t[n]=ct.has(n.toLowerCase())?"***redacted***":o;return t},"redactHeaders");var mt=s((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 r of n){let a=e.tools[r];a&&(o[r]=a);}return o},"buildActiveToolSet"),Te="[BLOCKER]",gt=s(e=>e.includes(Te)?{summary:e.split(Te).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),te=4e3,ft=s(e=>e.length>te?`${e.slice(0,te)}... [truncated, ${e.length-te} chars]`:e,"truncateForTrace"),Se=s(async(e,t,n,o,r,a,d)=>C("agent.execute_step",{[b.PHASE]:"execute",[b.STEP_ID]:n.id},async u=>{let p=Date.now(),i=await L(()=>ht(e,t,n,o,r,a,d),{maxRetries:a.config.llmMaxRetries??2,signal:d,onRetry:s((c,m)=>a.emit({type:"retry",phase:"execute",attempt:c,error:m.message}),"onRetry")});return a.emit({type:"usage",phase:"execute",usage:i.usage}),u.setAttribute(b.USAGE_TOTAL_TOKENS,i.usage.totalTokens),u.setAttribute(b.STEP_BLOCKED,i.blocked),u.setAttribute(b.TOOL_COUNT,i.toolCalls.length),{step:n,summary:i.summary,toolCalls:i.toolCalls,durationMs:Date.now()-p,blocked:i.blocked}}),"executeStep"),ht=s(async(e,t,n,o,r,a,d)=>{let u=[],p=new Map,i=mt(a,n),c=a.config.toolSelectionStrategy==="plan-narrowed",m=s(async(f,A)=>{let x=a.config.inputSanitizer;if(!x)return A;try{return await x(f,A)}catch(E){return a.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${f} - ${E.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),g=ai.streamText({model:a.executorModel,tools:i,...c?{activeTools:Object.keys(i)}:{},stopWhen:ai.stepCountIs(a.config.maxStepsPerTask),system:_(de,a.config.systemPrompt),prompt:me(e,t,n,o,r),abortSignal:U(d,a.config.llmTimeoutMs??0)});for await(let f of g.fullStream)switch(f.type){case "text-delta":f.text&&a.emit({type:"step.text-delta",step:n,delta:f.text});break;case "tool-call":{let A=await m(f.toolName,f.input);p.set(f.toolCallId,{name:f.toolName,input:A}),a.emit({type:"step.tool-call",step:n,name:f.toolName,input:A});break}case "tool-result":{let x=p.get(f.toolCallId)?.input??await m(f.toolName,f.input);u.push({name:f.toolName,input:x,output:f.output,ok:true}),a.emit({type:"step.tool-result",step:n,name:f.toolName,output:f.output,ok:true}),p.delete(f.toolCallId);break}case "tool-error":{let x=p.get(f.toolCallId)?.input??await m(f.toolName,f.input);u.push({name:f.toolName,input:x,output:f.error,ok:false}),a.emit({type:"step.tool-result",step:n,name:f.toolName,output:f.error,ok:false}),p.delete(f.toolCallId);break}case "error":{let A=f.error;throw A instanceof Error?A:new Error(String(A))}}let[v,w]=await Promise.all([g.text,g.usage]),{summary:R,blocked:y}=gt(v.trim());return {summary:R.length>0?ft(R):u.length>0?`Executed ${u.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:u,blocked:y,usage:{inputTokens:w.inputTokens??0,outputTokens:w.outputTokens??0,totalTokens:w.totalTokens??0}}},"runOnce");var wt=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")}),ne=zod.z.object({thought:zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:zod.z.array(wt).min(1).max(8)}),Ie=s(async(e,t,n,o)=>C("agent.plan",{[b.PHASE]:"plan"},async r=>{let a=new Set(n.toolCatalog.map(i=>i.name)),d=n.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:u,usage:p}=await L(()=>Tt(e,t,d,n,o),{maxRetries:n.config.llmMaxRetries??2,signal:o,onRetry:s((i,c)=>n.emit({type:"retry",phase:"plan",attempt:i,error:c.message}),"onRetry")});return n.emit({type:"usage",phase:"plan",usage:p}),r.setAttribute(b.USAGE_TOTAL_TOKENS,p.totalTokens),{thought:u.thought,steps:u.steps.map(i=>{if(!i.suggestedTools?.length)return i;let c=i.suggestedTools.filter(g=>a.has(g)),m=i.suggestedTools.length-c.length;return m>0&&n.emit({type:"log",level:"warn",message:`[plan] step "${i.id}" had ${m} unknown suggestedTools, stripped`}),c.length===0?(n.emit({type:"log",level:"warn",message:`[plan] step "${i.id}" had no valid suggestedTools left; falling back to full toolset`}),{...i,suggestedTools:void 0,requiresTools:true}):{...i,suggestedTools:c}})}}),"createInitialPlan"),Tt=s(async(e,t,n,o,r)=>{let a=ai.streamObject({model:o.plannerModel,schema:ne,system:_(pe(n),o.config.systemPrompt),prompt:ue(e,o.toolCatalog,t,n),abortSignal:U(r,o.config.llmTimeoutMs??0)}),d="",u=false,p=0;for await(let m of a.partialObjectStream){let g=m?.thought;typeof g=="string"&&g!==d&&(g.startsWith(d)?o.emit({type:"plan.thought-delta",delta:g.slice(d.length)}):u||(o.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),u=true),d=g);let v=m?.steps;if(Array.isArray(v)&&v.length>p)for(;p<v.length;){let w=v[p];if(!w||typeof w.description!="string"||!w.description.length)break;let R={id:typeof w.id=="string"&&w.id?w.id:`s${p+1}`,description:w.description,expectedOutcome:typeof w.expectedOutcome=="string"?w.expectedOutcome:"",suggestedTools:Array.isArray(w.suggestedTools)?w.suggestedTools.filter(y=>typeof y=="string"):void 0};o.emit({type:"plan.step-added",step:R,index:p}),p++;}}let[i,c]=await Promise.all([a.object,a.usage]);return {object:i,usage:{inputTokens:c.inputTokens??0,outputTokens:c.outputTokens??0,totalTokens:c.totalTokens??0}}},"streamPlanOnce");var It=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:ne.describe("Plan covering ONLY the remaining work")})]),be=s(async(e,t,n,o,r,a)=>C("agent.replan",{[b.PHASE]:"replan"},async d=>{let u=r.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:p,usage:i}=await L(async()=>{let c=await ai.generateObject({model:r.plannerModel,schema:It,system:_(ge,r.config.systemPrompt),prompt:fe(e,t,n,o,r.toolCatalog,u),abortSignal:U(a,r.config.llmTimeoutMs??0)}),m={inputTokens:c.usage.inputTokens??0,outputTokens:c.usage.outputTokens??0,totalTokens:c.usage.totalTokens??0};return {object:c.object,usage:m}},{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((c,m)=>r.emit({type:"retry",phase:"replan",attempt:c,error:m.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:i}),d.setAttribute(b.REPLAN_MODE,p.mode),d.setAttribute(b.USAGE_TOTAL_TOKENS,i.totalTokens),p}),"decideNextAction");var Re=s(async(e,t,n,o,r,a)=>C("agent.synthesize",{[b.PHASE]:"synthesize"},async d=>{let{text:u,usage:p}=await L(()=>Rt(e,t,n,o,r,a),{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((i,c)=>r.emit({type:"retry",phase:"synthesize",attempt:i,error:c.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:p}),d.setAttribute(b.USAGE_TOTAL_TOKENS,p.totalTokens),u}),"synthesizeAnswer"),Rt=s(async(e,t,n,o,r,a)=>{let d=ai.streamText({model:r.synthesizerModel,system:_(he,r.config.systemPrompt),prompt:ye(e,t,n,o),abortSignal:U(a,r.config.llmTimeoutMs??0)});for await(let i of d.fullStream)if(i.type==="text-delta")i.text&&r.emit({type:"final.text-delta",delta:i.text});else if(i.type==="error"){let c=i.error;throw c instanceof Error?c:new Error(String(c))}let[u,p]=await Promise.all([d.text,d.usage]);return {text:u,usage:{inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,totalTokens:p.totalTokens??0}}},"streamOnce");var xt=s(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),Y=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),kt=s((e,t)=>{let n=e.config.sandboxRoot?.trim()||ve__default.default.join(os.tmpdir(),"agent-sandbox");return ve__default.default.join(n,t)},"resolveSandboxDir"),Ae=/^[a-zA-Z0-9_-]{1,128}$/,oe=s((e,t)=>{if(!Ae.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Ae}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Ct=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(oe(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let n=await e.config.persistence.loadRun(t.resumeFromRunId);if(!n)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(oe(n.runId,"snapshot.runId"),n.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${n.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(n.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!n.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${n.status}"); cannot resume`);return n},"resolveResume"),Ee=s(async(e,t)=>{let n=await Ct(e,t),o=n?.runId??crypto.randomUUID();oe(o,"runId");let r=n?.startedAt??Date.now(),a=kt(e,o);return j.run({runId:o,startedAt:r,sandboxDir:a},async()=>C("agent.run",{[b.RUN_ID]:o,[b.PROVIDER]:e.config.providerType,[b.MODEL]:e.config.model},async d=>{try{let u=await Pt(e,t,n);return d.setAttribute(b.ITERATIONS,u.iterations),d.setAttribute(b.USAGE_TOTAL_TOKENS,u.usage.totalTokens),d.setAttribute(b.USAGE_INPUT_TOKENS,u.usage.inputTokens),d.setAttribute(b.USAGE_OUTPUT_TOKENS,u.usage.outputTokens),u}finally{e.config.keepSandbox||await promises.rm(a,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Pt=s(async(e,t,n)=>{let{signal:o}=t,r=n?.input??t.input,a=n?.history?[...n.history]:t.history?[...t.history]:void 0,d=t.onEvent??(()=>{}),u=n?{...n.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},p=j.getStore()?.startedAt??Date.now(),i=j.getStore()?.runId??"<unknown>",c={...e,emit:s(l=>{l.type==="usage"&&(u.inputTokens+=l.usage.inputTokens,u.outputTokens+=l.usage.outputTokens,u.totalTokens+=l.usage.totalTokens);let h={...l,runId:j.getStore()?.runId};try{d(h);}catch{}try{e.emit(h);}catch{}},"emit")},m=e.config.persistence,g=s(async(l,h)=>{let T=m?.[l];if(T)try{await T(h);}catch(S){c.emit({type:"log",level:"warn",message:`[persistence] ${l} threw: ${S.message}`});}},"callPersistence"),v;if(n)v=n.plan,c.emit({type:"log",level:"info",message:`[resume] continuing run ${i} from step ${n.stepIndex}/${v.steps.length} (iterations=${n.iterations}, revisions=${n.revisions})`}),c.emit({type:"plan.created",plan:v});else {try{v=await Ie(r,a,c,o);}catch(l){if(c.emit({type:"error",error:z(l),phase:"plan"}),Y(l)||o?.aborted)throw await g("onRunComplete",{runId:i,startedAt:p,status:"cancelled",input:r,history:a,trace:[],usage:u,stepIndex:0,iterations:0,revisions:0,error:l.message,completedAt:Date.now()}),l;v={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:v});}let w=n?[...n.trace]:[],R=v,y=n?.stepIndex??0,I=n?.iterations??0,f=n?.revisions??0,A=e.config.maxRevisions??2,x=e.config.maxTotalTokens,E=s((l,h={})=>({runId:i,startedAt:p,status:l,input:r,history:a,plan:R,trace:w,usage:u,stepIndex:y,iterations:I,revisions:f,...h}),"buildSnapshot");n||await g("onRunStart",E("executing"));let P=s(async()=>{await g("onStepComplete",E("executing"));},"persistCheckpoint");for(;I<e.config.maxIterations;){if(o?.aborted)throw new DOMException("Aborted","AbortError");if(y>=R.steps.length)break;if(x&&u.totalTokens>=x){c.emit({type:"budget.exceeded",tokens:u.totalTokens,cap:x});break}I++;let l=R.steps[y];c.emit({type:"step.start",step:l,index:y});let h=new AbortController;if(t.onStepStart)try{t.onStepStart({step:l,index:y,abort:s(()=>h.abort(),"abort")});}catch(k){c.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${k.message}`});}let T=ee([o,h.signal]),S;try{S=await Se(r,R,l,w,a,c,T);}catch(k){if(o?.aborted)throw c.emit({type:"error",error:z(k),phase:"execute"}),await g("onRunComplete",E("cancelled",{error:k.message,completedAt:Date.now()})),k;if(h.signal.aborted&&Y(k))c.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),S={step:l,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw c.emit({type:"error",error:z(k),phase:"execute"}),await g("onRunComplete",E("failed",{error:k.message,completedAt:Date.now()})),k}w.push(S),c.emit({type:"step.complete",step:l,result:S});let $=R.steps[y+1]??null;if($===null){c.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!xt(S)){c.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),y++,await P();continue}let D;try{D=await be(r,R,w,$,c,o);}catch(k){throw c.emit({type:"error",error:z(k),phase:"replan"}),await g("onRunComplete",E(Y(k)||o?.aborted?"cancelled":"failed",{error:k.message,completedAt:Date.now()})),k}if(c.emit({type:"replan.decision",mode:D.mode,reason:D.reason,cause:"llm-decision"}),D.mode==="finish")break;if(D.mode==="revise"){if(f>=A){c.emit({type:"revisions.exceeded",cap:A});break}f++,R=D.newPlan,c.emit({type:"plan.revised",plan:R,reason:D.reason}),y=0,await P();continue}y++,await P();}let O;try{O=await Re(r,R,w,a,c,o);}catch(l){throw c.emit({type:"error",error:z(l),phase:"synthesize"}),await g("onRunComplete",E(Y(l)||o?.aborted?"cancelled":"failed",{error:l.message,completedAt:Date.now()})),l}return c.emit({type:"final",text:O}),await g("onRunComplete",E("complete",{text:O,completedAt:Date.now()})),{text:O,plan:R,trace:w,iterations:I,usage:u}},"runAgentLoopInner"),z=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var q={none:0,error:1,warn:2,info:3,debug:4},eo=s(async(e,t)=>{let n=q[e.logLevel]>=q.debug,o=s(l=>{if(t)try{t(l);}catch(h){n&&console.error("[agent] event handler threw:",h);}},"emit"),r=s((l,h)=>{q[e.logLevel]>=q[l]&&o({type:"log",level:l,message:h});},"log"),a,d=s((l,h)=>{if(!e.tools)return l;let T=[];for(let[S,$]of Object.entries(e.tools)){if(l.tools[S]&&h(S),e.availableTools?.length&&!e.availableTools.includes(S)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(S))continue;l.tools[S]=$;let B=typeof $=="object"&&$&&"description"in $?$.description:"";T.push({name:S,description:typeof B=="string"?B:"",server:"<native>"});}return {tools:l.tools,catalog:[...l.catalog,...T]}},"mergeNativeTools"),u=s(async()=>{let l=await ie(e.mcpServers,r,e.clientName,e.outputSanitizer,S=>a?.(S),e.inputSanitizer),h=J(l.tools,l.catalog,e.availableTools,e.excludedTools),T=d(h,S=>{throw l.close().catch(()=>{}),new Error(`Native tool "${S}" collides with an MCP-registered tool of the same name`)});return {connection:l,tools:T.tools,catalog:T.catalog}},"connect"),p;try{p=await u();}catch(l){throw o({type:"error",error:l instanceof Error?l:new Error(String(l)),phase:"init"}),l}let i=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&i>0&&!p.connection.results.some(h=>h.connected)){let h=p.connection.results.filter(S=>!S.connected).map(S=>`${S.name}: ${S.error??"unknown"}`).join("; ");await p.connection.close().catch(()=>{});let T=new Error(`All ${i} configured MCP server(s) failed to connect [${h}]`);throw o({type:"error",error:T,phase:"init"}),T}let c=H(e,void 0,void 0,"executor"),m=H(e,e.planner,e.plannerModel,"planner"),g=H(e,e.synthesizer,e.synthesizerModel,"synthesizer"),v=F(e.clientName,c),w=F(e.clientName,m),R=F(e.clientName,g),y={config:e,executorModel:v,plannerModel:w,synthesizerModel:R,tools:p.tools,toolCatalog:p.catalog.map(l=>({name:l.name,description:l.description})),emit:o},I=0,f=false,A=false,x=false,E=new Set,P=s(async l=>{await p.connection.refreshServer(l);let h=J(p.connection.tools,p.connection.catalog,e.availableTools,e.excludedTools),T=d(h,S=>{throw new Error(`Native tool "${S}" collides with an MCP-registered tool of the same name`)});for(let S of Object.keys(y.tools))delete y.tools[S];Object.assign(y.tools,T.tools),y.toolCatalog=T.catalog.map(S=>({name:S.name,description:S.description})),r("info",`[mcp] ${l}: tool list refreshed (${T.catalog.length} tools total after filter)`);},"applyRefresh"),O=s(async()=>{if(!(x||f||A)&&!(I>0||E.size===0)){x=true;try{for(;E.size>0&&I===0&&!f&&!A;){let l=E.values().next().value;E.delete(l);try{await P(l);}catch(h){r("warn",`[mcp] ${l}: refresh failed - ${h.message}`);}}}finally{x=false;}}},"drainPendingRefreshes");return a=s(l=>{E.add(l),O();},"onToolsChanged"),{run:s(async l=>{if(f)throw new Error("Agent is closed");if(A)throw new Error("Agent is reconnecting; retry shortly");if(x)throw new Error("Agent is refreshing tools; retry shortly");let h=e.maxConcurrentRuns;if(typeof h=="number"&&h>0&&I>=h)throw new Error(`maxConcurrentRuns reached (${I}/${h}); rate-limit on the caller side or raise the cap`);I++;try{return await Ee(y,l)}finally{I--,O();}},"run"),listTools:s(()=>y.toolCatalog.slice(),"listTools"),reconnect:s(async()=>{if(f)throw new Error("Agent is closed");if(A)throw new Error("Already reconnecting");if(x)throw new Error("Agent is refreshing tools; retry shortly");if(I>0)throw new Error(`Cannot reconnect with ${I} active run(s)`);A=true;try{let l=p.connection;E.clear();let h=await u();for(let T of Object.keys(y.tools))delete y.tools[T];Object.assign(y.tools,h.tools),y.toolCatalog=h.catalog.map(T=>({name:T.name,description:T.description})),p=h,await l.close().catch(()=>{});}finally{A=false;}},"reconnect"),close:s(async l=>{f=true;let h=l?.waitForRuns??false,T=l?.timeoutMs??3e4;if(h&&I>0){let S=Date.now();for(;I>0&&Date.now()-S<T;)await new Promise($=>setTimeout($,50));}I>0&&o({type:"log",level:"warn",message:`[agent] close called with ${I} active run(s); they will fail mid-flight`}),await p.connection.close().catch(()=>{});},"close"),activeRuns:s(()=>I,"activeRuns")}},"createAgent");exports.createAgent=eo;exports.getCurrentRunId=Pe;exports.getCurrentRunSandbox=G;exports.redactHeaders=pt;
|