@dudko.dev/agent 0.0.19 → 0.0.22
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 +30 -3
- package/dist/cli.js +46 -46
- package/dist/index.cjs +35 -35
- package/dist/index.d.cts +149 -1
- package/dist/index.d.ts +149 -1
- package/dist/index.js +35 -35
- package/package.json +11 -11
package/README.md
CHANGED
|
@@ -61,7 +61,7 @@ const agent = await createAgent({
|
|
|
61
61
|
apiKey: process.env.OPENAI_API_KEY!,
|
|
62
62
|
model: 'gpt-4.1-mini',
|
|
63
63
|
mcpServers: {
|
|
64
|
-
docs: { url: 'https://mcp.example.com/
|
|
64
|
+
docs: { url: 'https://mcp.example.com/mcp' },
|
|
65
65
|
},
|
|
66
66
|
maxIterations: 6,
|
|
67
67
|
maxStepsPerTask: 8,
|
|
@@ -161,6 +161,31 @@ await agent.run({ input: 'Got a contact?', history })
|
|
|
161
161
|
|
|
162
162
|
Use `getHeaders` on a server config to inject fresh credentials at connect time, then call `agent.reconnect()` after a token rotation. Reconnect refuses while runs are in flight.
|
|
163
163
|
|
|
164
|
+
`getHeaders` is resolved **once per connect**, so it cannot save a token that expires mid-run — for that, use OAuth.
|
|
165
|
+
|
|
166
|
+
### MCP over OAuth 2.1
|
|
167
|
+
|
|
168
|
+
Point `authProvider` at an `OAuthClientProvider` and the SDK discovers the authorization server (RFC 9728), registers this client dynamically when it has no `client_id` yet (RFC 7591), runs PKCE, and — the part a header cannot do — **refreshes the access token on a 401 and retries the request**. `createNodeOAuthProvider` persists tokens and the registration in a `0600` JSON file, so a restarted process picks up where it left off.
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { createAgent, createNodeOAuthProvider, finishMcpOAuth } from '@dudko.dev/agent'
|
|
172
|
+
|
|
173
|
+
const auth = createNodeOAuthProvider({
|
|
174
|
+
serverUrl: 'https://mcp.example.com/mcp',
|
|
175
|
+
redirectUrl: 'http://127.0.0.1:8765/callback', // whatever you listen on
|
|
176
|
+
onAuthorizationUrl: (url) => console.error('Authorize here:', url.href),
|
|
177
|
+
})
|
|
178
|
+
|
|
179
|
+
const agent = await createAgent({ /* … */ mcpServers: { docs: { url: auth.serverUrl, authProvider: auth } } })
|
|
180
|
+
|
|
181
|
+
// First run only: the server answers 401, the connect result carries
|
|
182
|
+
// needsAuthorization, and the operator visits the URL above. Feed the code back:
|
|
183
|
+
await finishMcpOAuth(auth, { code, state })
|
|
184
|
+
await agent.reconnect()
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
Nothing is printed or opened on your behalf; `onAuthorizationUrl` and the loopback listener are yours to wire. `agent.listTools()` stays empty until the flow completes — a server that needs authorization reports `needsAuthorization: true` in its connect result rather than a generic failure. `MCP_SERVERS` (the CLI's env config) is JSON, so it can only express `headers`; OAuth is a library-level feature.
|
|
188
|
+
|
|
164
189
|
## Configuration
|
|
165
190
|
|
|
166
191
|
`createAgent(config)` accepts an [`IAgentConfig`](./src/types.ts). Highlights:
|
|
@@ -174,7 +199,7 @@ Use `getHeaders` on a server config to inject fresh credentials at connect time,
|
|
|
174
199
|
| `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
|
|
175
200
|
| `planner` / `synthesizer` | Optional per-stage override blocks: `{ providerType?, baseURL?, apiKey?, model? }`. Use these to mix providers (e.g. Gemini planner, Anthropic synthesizer). Cross-provider overrides MUST set their own `apiKey`. |
|
|
176
201
|
| `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
|
|
177
|
-
| `mcpServers` | `Record<name, { url, headers?, getHeaders? } \| { command, args?, env?, cwd? }>` — HTTP
|
|
202
|
+
| `mcpServers` | `Record<name, { url, headers?, getHeaders?, authProvider?, fetch? } \| { command, args?, env?, cwd? }>` — StreamableHTTP for remote (legacy HTTP+SSE servers are **not** supported), stdio for locally-spawned servers. |
|
|
178
203
|
| `tools` | Optional `ToolSet` of native AI-SDK tools registered alongside MCP-discovered ones. Names must not collide with MCP-prefixed names (`createAgent` throws on conflict). |
|
|
179
204
|
| `availableTools` / `excludedTools` | Whitelist / blacklist applied to **all** tools (MCP and native). |
|
|
180
205
|
| `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
|
|
@@ -276,7 +301,9 @@ npm run format:check # prettier --check
|
|
|
276
301
|
## Behavior notes & limitations
|
|
277
302
|
|
|
278
303
|
- **Module formats.** ESM is the primary target; the CJS build (`dist/index.cjs`) is best-effort and depends on upstream deps (`ai`, `@ai-sdk/*`, `@modelcontextprotocol/sdk`) keeping their CJS fallbacks. If they go pure-ESM, CJS will break — the dual-format guard in [`tests/dist-loadable.test.ts`](./tests/dist-loadable.test.ts) catches the regression on the next build.
|
|
279
|
-
- **MCP connect failures.** By default `createAgent` is fail-tolerant: a server that can't connect is logged at `error` level and skipped. The agent still starts with whatever tools did mount. Set `failOnNoTools: true` to throw when **every** configured server failed.
|
|
304
|
+
- **MCP connect failures.** By default `createAgent` is fail-tolerant: a server that can't connect is logged at `error` level and skipped. The agent still starts with whatever tools did mount. Set `failOnNoTools: true` to throw when **every** configured server failed. Servers connect concurrently, so one slow server no longer delays the ones declared after it; tools still mount in declaration order.
|
|
305
|
+
- **MCP tool errors.** A tool result carrying `isError: true` is surfaced as a **thrown** tool error, so the step records `ok: false` and `replanAfter: 'failure'` sees it. The error text the server returned becomes the error message (after `outputSanitizer`, if you set one).
|
|
306
|
+
- **MCP tool names.** Server and tool names are sanitized into `[a-zA-Z0-9_-]` (what OpenAI, Anthropic and Gemini accept) before being joined as `server__tool`, and a collision produced by that mapping gets a `_2` suffix rather than being dropped. `callTool` always uses the server's original name. If you pin `availableTools` / `excludedTools`, use the sanitized names.
|
|
280
307
|
- **Blocker detection.** When the executor cannot complete a step it ends its reply with the literal `[BLOCKER]` token; the agent strips the token from the surfaced summary and sets `IStepResult.blocked = true`, which triggers the replanner. The detection is structural and language-independent — works regardless of the language the executor wrote in.
|
|
281
308
|
- **Retry duplicates in events.** Executor LLM retries (5xx / 429 / network) restart `streamText`, so consumers may observe `step.text-delta` / `step.tool-call` / `step.tool-result` events repeated for the same step. The `retry` event with `phase: 'execute'` precedes each repeat — UIs should clear any per-step buffers on it.
|
|
282
309
|
- **Mid-stream thought rewrites.** Some providers (notably Gemini structured outputs) rewrite `partialObjectStream.thought` from scratch instead of appending. The agent emits a single `log`-level warning and stops streaming `plan.thought-delta` for that run; the canonical thought still arrives in `plan.created`.
|
package/dist/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {dynamicTool,jsonSchema,generateObject,streamObject,streamText,stepCountIs}from'ai';import {randomUUID}from'crypto';import {rm,mkdir,writeFile}from'fs/promises';import
|
|
2
|
+
import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {UnauthorizedError,auth}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {dynamicTool,jsonSchema,generateObject,streamObject,streamText,stepCountIs}from'ai';import {randomUUID}from'crypto';import {rm,mkdir,writeFile}from'fs/promises';import je from'path';import {URL as URL$1}from'url';import {AsyncLocalStorage}from'async_hooks';import st,{tmpdir}from'os';import {SpanStatusCode,trace}from'@opentelemetry/api';import {z as z$1}from'zod';var et=Object.defineProperty;var s=(e,t)=>et(e,"name",{value:t,configurable:true});var ye=`Usage: dd-agent [options]
|
|
3
3
|
|
|
4
4
|
Options:
|
|
5
5
|
--env-file=<path> Load env vars from a dotenv file before starting
|
|
@@ -26,19 +26,19 @@ Required env vars (set directly or via --env-file):
|
|
|
26
26
|
|
|
27
27
|
Commands inside the REPL:
|
|
28
28
|
/status, /tools, /history, /reset, /reconnect, /exit
|
|
29
|
-
`,
|
|
30
|
-
`);let
|
|
31
|
-
`)},"renderHistory"),
|
|
32
|
-
`)},"renderToolCatalog"),
|
|
29
|
+
`,ot={provider:"AGENT_PROVIDER_TYPE",model:"AGENT_MODEL","planner-model":"AGENT_PLANNER_MODEL","synthesizer-model":"AGENT_SYNTHESIZER_MODEL","base-url":"AGENT_BASE_URL","log-level":"AGENT_LOG_LEVEL","max-iterations":"AGENT_MAX_ITERATIONS","max-steps-per-task":"AGENT_MAX_STEPS_PER_TASK","tool-strategy":"AGENT_TOOL_SELECTION_STRATEGY"},we=s(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"},provider:{type:"string"},model:{type:"string"},"planner-model":{type:"string"},"synthesizer-model":{type:"string"},"base-url":{type:"string"},"log-level":{type:"string"},"max-iterations":{type:"string"},"max-steps-per-task":{type:"string"},"tool-strategy":{type:"string"}},strict:true,allowPositionals:false}),o={},r=t;for(let[n,i]of Object.entries(ot)){let m=r[n];typeof m=="string"&&m.length>0&&(o[i]=m);}return {envFile:t["env-file"],help:!!t.help,overrides:o}},"parseCliArgs");var J={version:"0.0.22"};var K=new AsyncLocalStorage;var ne=s(()=>K.getStore()?.sandboxDir,"getCurrentRunSandbox");je.join(st.homedir(),".agent","mcp-oauth.json");var at=new Set(["localhost","127.0.0.1","[::1]","::1"]),Te=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||at.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var dt="@dudko.dev/agent",pt=J.version,se,ut=s(()=>(se||(se=trace.getTracer(dt,pt)),se),"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"},_=s(async(e,t,o)=>ut().startActiveSpan(e,async r=>{for(let[n,i]of Object.entries(t))i!==void 0&&r.setAttribute(n,i);try{let n=await o(r);return r.end(),n}catch(n){let i=n instanceof Error?n:new Error(String(n));throw r.recordException(i),r.setStatus({code:SpanStatusCode.ERROR,message:i.message}),r.end(),n}}),"withSpan");var kt=s(e=>"command"in e&&!!e.command,"isStdioConfig"),Ot=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Pt=J.version,ie=64,q=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),xt=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let r=`_${o}`,n=e.slice(0,ie-r.length)+r;if(!t[n])return n}return ""},"uniqueKey"),W=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},F=class extends Error{static{s(this,"RefreshOnlyAbort");}},Ct=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new F},"state"),saveCodeVerifier:s(()=>{throw new F},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new F},"redirectToAuthorization")}),"refreshOnly"),_t=s(async(e,t,o,r,n)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(Ct(e),{serverUrl:t,fetchFn:o});}catch(p){r("info",p instanceof F?`[mcp] ${n}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${n}: proactive token refresh failed (${p.message}); continuing`);}},"refreshIfExpired"),Se=s(async(e,t,o,r,n,i)=>{let m=new Map,p={},c=[],u=[],l=new Map,w=s((a,d,I)=>{let h=`${q(a)}__`;for(let y of l.get(a)??[])delete p[y];for(let y=c.length-1;y>=0;y--)c[y].server===a&&c.splice(y,1);let A=[],k=0,f=0;for(let y of I){let S=h+q(y.name);if(S.length>ie){t("warn",`[mcp] ${a}: tool "${y.name}" prefixed name (${S.length} chars) exceeds the ${ie}-char limit enforced by major LLM providers; skipping`),f++;continue}let g=xt(S,p);if(!g){t("warn",`[mcp] ${a}: no free name left for tool "${y.name}"; skipping`),f++;continue}g!==S&&t("warn",`[mcp] ${a}: tool name "${S}" already taken; mounted as "${g}"`);let R=y.description??"";p[g]=dynamicTool({description:R,inputSchema:jsonSchema(y.inputSchema),execute:s(async(C,P)=>_("agent.tool_call",{[b.TOOL_NAME]:g},async $=>{let Y=C??{};if(i)try{let x=await i(g,Y);Y=x&&typeof x=="object"&&!Array.isArray(x)?x:{value:x};}catch(x){t("warn",`[mcp] ${g}: inputSanitizer threw - ${x.message}; input replaced with placeholder`),Y={_redacted:"inputSanitizer failed"};}let V;try{V=await d.callTool({name:y.name,arguments:Y},void 0,P?.abortSignal?{signal:P.abortSignal}:void 0);}catch(x){throw $.setAttribute(b.TOOL_OK,false),x}let N=V.isError===true,O=V.content;if(r)try{O=await r(g,O);}catch(x){if(t("warn",`[mcp] ${g}: outputSanitizer threw - ${x.message}; output replaced with placeholder`),$.setAttribute(b.TOOL_OK,false),N)throw new W("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let B=await Lt(O,{toolName:g,sandboxDir:N?void 0:ne()});if(N){$.setAttribute(b.TOOL_OK,false);let x=typeof B=="string"?B:JSON.stringify(B);throw new W(x&&x!=="[]"?x:`MCP tool "${y.name}" reported an error with no content`)}return $.setAttribute(b.TOOL_OK,true),B}),"execute")}),c.push({name:g,description:R,server:a}),A.push(g),k++;}l.set(a,A),f>0?t("info",`[mcp] ${a}: ${k} tools mounted, ${f} skipped (length cap)`):t("info",`[mcp] ${a}: ${k} tools mounted`);},"mountServerTools"),v=s(async(a,d)=>{w(a,d,(await d.listTools()).tools);},"registerServerTools"),E=s(async(a,d)=>{let I;try{let h;if(kt(d)){let A=d.env?{...getDefaultEnvironment(),...d.env}:void 0;h=new StdioClientTransport({command:d.command,args:d.args,env:A,cwd:d.cwd});}else if(Ot(d)){if(d.headers&&d.getHeaders)throw new Error(`MCP server "${a}": specify either headers or getHeaders, not both`);let A=d.getHeaders?await d.getHeaders():d.headers;d.authProvider&&(A&&"Authorization"in A&&t("warn",`[mcp] ${a}: an explicit Authorization header shadows the OAuth token from authProvider`),Te(d.url,`MCP server "${a}"`),await _t(d.authProvider,d.url,d.fetch,t,a)),h=new StreamableHTTPClientTransport(new URL$1(d.url),{requestInit:A?{headers:A}:void 0,authProvider:d.authProvider,fetch:d.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${a}": config must specify either { url } (HTTP) or { command } (stdio)`);return h.onerror=A=>t("warn",`[mcp] ${a}: transport error - ${A.message}`),h.onclose=()=>t("warn",`[mcp] ${a}: transport closed`),I=new Client({name:o,version:Pt}),await I.connect(h),n&&I.setNotificationHandler(ToolListChangedNotificationSchema,()=>{n(a);}),{name:a,client:I,listed:(await I.listTools()).tools}}catch(h){I&&await I.close().catch(()=>{});let A=h.message,k=h instanceof UnauthorizedError;return t("error",k?`[mcp] ${a}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${a}: failed to connect - ${A}`),{name:a,error:A,needsAuthorization:k}}},"openConnection"),T=await Promise.all(Object.entries(e).map(([a,d])=>E(a,d)));for(let a of T){if(!a.client||!a.listed){u.push({name:a.name,connected:false,error:a.error,...a.needsAuthorization?{needsAuthorization:true}:{}});continue}m.set(a.name,a.client),w(a.name,a.client,a.listed),u.push({name:a.name,connected:true});}return {tools:p,catalog:c,results:u,close:s(async()=>{await Promise.allSettled([...m.values()].map(a=>a.close()));},"close"),refreshServer:s(async a=>{let d=m.get(a);if(!d)throw new Error(`MCP server "${a}" is not connected`);await v(a,d);},"refreshServer")}},"connectMcpServers"),ve={image:".bin",audio:".bin",resource:".bin"},$t=s((e,t)=>{if(!e)return ve[t];let o=e.indexOf("/"),n=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !n||/[^a-z0-9.+-]/.test(n)?ve[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"}[n]??`.${n.replace(/\+/g,"-")}`},"extFromMime"),Nt=/[^a-zA-Z0-9_-]/g,Ee=s(async(e,t,o,r,n,i)=>{await i();let m=$t(t,o),p=r.replace(Nt,"_").slice(0,32)||"tool",c=randomUUID().slice(0,8),u=je.join(n,`${o}-${p}-${c}${m}`),l=Buffer.from(e,"base64");return await writeFile(u,l),{type:"file",kind:o,path:u,mimeType:t,bytes:l.byteLength}},"spillBase64"),Lt=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(u=>u?.type==="text"&&typeof u.text=="string"))return o.map(u=>u.text).join(`
|
|
30
|
+
`);let n=t?.sandboxDir,i=t?.toolName??"tool",m,p=s(()=>n?(m||(m=mkdir(n,{recursive:true}).then(()=>{})),m):Promise.resolve(),"ensureDir"),c=[];for(let u of o){if(u?.type==="text"&&typeof u.text=="string"){c.push(u.text);continue}if(n&&(u?.type==="image"||u?.type==="audio")&&typeof u.data=="string"){let l=await Ee(u.data,typeof u.mimeType=="string"?u.mimeType:void 0,u.type,i,n,p);c.push(l);continue}if(n&&u?.type==="resource"&&u.resource&&typeof u.resource=="object"){let l=u.resource;if(typeof l.blob=="string"){let w=await Ee(l.blob,typeof l.mimeType=="string"?l.mimeType:void 0,"resource",i,n,p);typeof l.uri=="string"&&(w.uri=l.uri),c.push(w);continue}if(typeof l.text=="string"){c.push(l.text);continue}}c.push(u);}return c},"flattenContent"),ae=s((e,t,o,r,n)=>{let i=o?.length?new Set(o.map(q)):null,m=r?.length?new Set(r.map(q)):null,p=new Set,c={},u=[];for(let l of t){if((i?.has(l.name)||m?.has(l.name))&&p.add(l.name),i&&!i.has(l.name)||!i&&m?.has(l.name))continue;let w=e[l.name];w&&(c[l.name]=w,u.push(l));}if(n)for(let[l,w]of [["availableTools",o],["excludedTools",r]])for(let v of w??[])p.has(q(v))||n("warn",`[mcp] ${l}: "${v}" matches no discovered tool`);return {tools:c,catalog:u}},"filterTools");var X=s((e,t,o,r)=>{let n=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,m=t?.baseURL??e.baseURL,p=t?.model??o??e.model,c=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${r}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${r}.apiKey (cross-provider key inheritance is unsafe)`);if(Mt.has(n)&&!m)throw new Error(`${r}: provider "${n}" requires a baseURL (set ${r}.baseURL or the top-level baseURL)`);return {providerType:n,baseURL:m,apiKey:i,model:p,providerOptions:c}},"resolveStage"),Mt=new Set(["openai-compatible","azure"]),L={openai:"@ai-sdk/openai",anthropic:"@ai-sdk/anthropic",google:"@ai-sdk/google","openai-compatible":"@ai-sdk/openai-compatible",xai:"@ai-sdk/xai",azure:"@ai-sdk/azure","amazon-bedrock":"@ai-sdk/amazon-bedrock","google-vertex":"@ai-sdk/google-vertex",deepseek:"@ai-sdk/deepseek",cloudflare:"workers-ai-provider"},M=s(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),Z=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:r}=await M(L.openai);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:r}=await M(L.anthropic);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:r}=await M(L["openai-compatible"]);return r({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:r}=await M(L.google);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:r}=await M(L.xai);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:r}=await M(L.azure);return r({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:r}=await M(L["amazon-bedrock"]);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:r}=await M(L["google-vertex"]);return r({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:r}=await M(L.deepseek);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:r}=await import('ai');return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let n=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...m}=o;if(!n&&!("binding"in m))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:p}=await M(L.cloudflare),c="binding"in m?m:{accountId:n,apiKey:t.apiKey,...m};return p(c)(t.model)}}},"buildModelFromStage");var ce=s(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),o=e.length-t.length,r=[];o>0&&r.push(`(${o} earlier turns omitted)`);for(let n of t){let i=n.content.length>1500?`${n.content.slice(0,1500)}... [truncated]`:n.content;r.push(`${n.role}: ${i}`);}return r.join(`
|
|
31
|
+
`)},"renderHistory"),Ut={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},be=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:r}=Ut[t],n=e.slice(0,o),i=e.length-n.length,m=n.map(p=>{let c=(p.description||"").replace(/\s+/g," ").trim().slice(0,r);return `- ${p.name}: ${c}`});return i>0&&m.push(`... and ${i} more tools`),m.join(`
|
|
32
|
+
`)},"renderToolCatalog"),le=1500,Dt=s(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>le?`${t.slice(0,le)}... [truncated, ${t.length-le} chars]`:t},"truncateOutput"),zt=s((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(r=>` - ${r.name} ${r.ok?"ok":"fail"}: ${Dt(r.output)}`).join(`
|
|
33
33
|
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
|
|
34
|
-
`)},"renderTraceEntry"),
|
|
35
|
-
`),"renderTrace"),
|
|
34
|
+
`)},"renderTraceEntry"),de=s(e=>e.length===0?"(no steps executed yet)":e.map(zt).join(`
|
|
35
|
+
`),"renderTrace"),pe=s(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
|
|
36
36
|
expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
|
|
37
37
|
suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
|
|
38
|
-
`),"renderPlan"),
|
|
38
|
+
`),"renderPlan"),z=s((e,t)=>t?`${e}
|
|
39
39
|
|
|
40
40
|
Domain context:
|
|
41
|
-
${t}`:e,"withDomainContext"),
|
|
41
|
+
${t}`:e,"withDomainContext"),Ae=`You are the Planner of a multi-step agent system.
|
|
42
42
|
|
|
43
43
|
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.
|
|
44
44
|
|
|
@@ -48,28 +48,28 @@ Rules:
|
|
|
48
48
|
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
49
49
|
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.
|
|
50
50
|
5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
|
|
51
|
-
6. Output strict JSON matching the requested schema. No prose outside JSON.`,
|
|
51
|
+
6. Output strict JSON matching the requested schema. No prose outside JSON.`,jt=`
|
|
52
52
|
|
|
53
53
|
ADDITIONAL RULE (tool-narrowed mode):
|
|
54
|
-
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.`,
|
|
55
|
-
${
|
|
54
|
+
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.`,Ie=s(e=>e==="compact"?Ae+jt:Ae,"buildPlannerSystem"),Re=s((e,t,o,r="full")=>[o?.length?`Conversation history:
|
|
55
|
+
${ce(o)}
|
|
56
56
|
`:"",`User request:
|
|
57
57
|
${e}`,"",`Available tools:
|
|
58
|
-
${
|
|
59
|
-
`),"buildPlannerUserPrompt"),
|
|
58
|
+
${be(t,r)}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
59
|
+
`),"buildPlannerUserPrompt"),ke=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
|
|
60
60
|
|
|
61
61
|
Rules:
|
|
62
62
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
63
63
|
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.
|
|
64
64
|
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.
|
|
65
65
|
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.
|
|
66
|
-
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,
|
|
67
|
-
${
|
|
66
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,Oe=s((e,t,o,r,n)=>[n?.length?`Conversation history:
|
|
67
|
+
${ce(n)}
|
|
68
68
|
`:"",`Original user request:
|
|
69
69
|
${e}`,"",`Overall plan:
|
|
70
|
-
${
|
|
71
|
-
${
|
|
72
|
-
`),"buildExecutorUserPrompt"),
|
|
70
|
+
${pe(t)}`,"",`Trace so far:
|
|
71
|
+
${de(r)}`,"",`CURRENT STEP to execute (id=${o.id}): ${o.description}`,`Expected outcome: ${o.expectedOutcome}`,o.suggestedTools?.length?`Suggested tools: ${o.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
|
|
72
|
+
`),"buildExecutorUserPrompt"),Pe=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
|
|
73
73
|
|
|
74
74
|
You have three options:
|
|
75
75
|
- "continue": the next planned step is still appropriate.
|
|
@@ -80,40 +80,40 @@ Rules:
|
|
|
80
80
|
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
81
81
|
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
82
82
|
3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
|
|
83
|
-
4. Output strict JSON matching the schema. No prose outside JSON.`,
|
|
83
|
+
4. Output strict JSON matching the schema. No prose outside JSON.`,xe=s((e,t,o,r,n,i="full")=>[`Original user request:
|
|
84
84
|
${e}`,"",`Current plan:
|
|
85
|
-
${
|
|
86
|
-
${
|
|
87
|
-
${
|
|
88
|
-
`),"buildReplannerUserPrompt"),
|
|
85
|
+
${pe(t)}`,"",`Completed steps:
|
|
86
|
+
${de(o)}`,"",r?`Next planned step: [${r.id}] ${r.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
|
|
87
|
+
${be(n,i)}`,"","Decide now: continue, revise, or finish."].join(`
|
|
88
|
+
`),"buildReplannerUserPrompt"),Ce=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
89
89
|
|
|
90
90
|
Rules:
|
|
91
91
|
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
92
92
|
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
93
93
|
3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
|
|
94
|
-
4. Use the user's language.`,
|
|
95
|
-
${
|
|
94
|
+
4. Use the user's language.`,_e=s((e,t,o,r)=>[r?.length?`Conversation history:
|
|
95
|
+
${ce(r)}
|
|
96
96
|
`:"",`User request:
|
|
97
97
|
${e}`,"",`Plan that was executed:
|
|
98
|
-
${
|
|
99
|
-
${
|
|
100
|
-
`),"buildSynthesizerUserPrompt");var Ie=i((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let o=e;if(o.name==="AbortError")return false;let n=o.statusCode??o.status;return typeof n=="number"?n===429||n>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?Ie(o.cause,t):false},"isRetriable"),U=i(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let r=0;r<=t.maxRetries;r++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(s){if(n=s,r===t.maxRetries||!Ie(s))throw s;t.onRetry?.(r+1,s);let u=o*2**r+Math.random()*250;await It(u,t.signal);}}throw n},"withRetry"),It=i((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let r=setTimeout(()=>{t?.removeEventListener("abort",s),o();},e),s=i(()=>{clearTimeout(r),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",s,{once:true});}),"sleep"),re=i(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),D=i((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:re([e,AbortSignal.timeout(t)]),"withTimeout");var xt=i((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let o=new Set(t.suggestedTools??[]);if(o.size===0)return t.requiresTools?e.tools:{};let n={};for(let r of o){let s=e.tools[r];s&&(n[r]=s);}return n},"buildActiveToolSet"),Ae="[BLOCKER]",Ot=i(e=>e.includes(Ae)?{summary:e.split(Ae).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),se=4e3,Pt=i(e=>e.length>se?`${e.slice(0,se)}... [truncated, ${e.length-se} chars]`:e,"truncateForTrace"),ke=i(async(e,t,o,n,r,s,u)=>_("agent.execute_step",{[R.PHASE]:"execute",[R.STEP_ID]:o.id},async p=>{let l=Date.now(),d=await U(()=>_t(e,t,o,n,r,s,u),{maxRetries:s.config.llmMaxRetries??2,signal:u,onRetry:i((a,m)=>s.emit({type:"retry",phase:"execute",attempt:a,error:m.message}),"onRetry")});return s.emit({type:"usage",phase:"execute",usage:d.usage}),p.setAttribute(R.USAGE_TOTAL_TOKENS,d.usage.totalTokens),p.setAttribute(R.STEP_BLOCKED,d.blocked),p.setAttribute(R.TOOL_COUNT,d.toolCalls.length),{step:o,summary:d.summary,toolCalls:d.toolCalls,durationMs:Date.now()-l,blocked:d.blocked}}),"executeStep"),_t=i(async(e,t,o,n,r,s,u)=>{let p=[],l=new Map,d=xt(s,o),a=s.config.toolSelectionStrategy==="plan-narrowed",m=i(async(E,k)=>{let x=s.config.inputSanitizer;if(!x)return k;try{return await x(E,k)}catch(f){return s.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${E} - ${f.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),y=streamText({model:s.executorModel,tools:d,...a?{activeTools:Object.keys(d)}:{},stopWhen:stepCountIs(s.config.maxStepsPerTask),system:M(Te,s.config.systemPrompt),prompt:Ee(e,t,o,n,r),abortSignal:D(u,s.config.llmTimeoutMs??0)});for await(let E of y.fullStream)switch(E.type){case "text-delta":E.text&&s.emit({type:"step.text-delta",step:o,delta:E.text});break;case "tool-call":{let k=await m(E.toolName,E.input);l.set(E.toolCallId,{name:E.toolName,input:k}),s.emit({type:"step.tool-call",step:o,name:E.toolName,input:k});break}case "tool-result":{let x=l.get(E.toolCallId)?.input??await m(E.toolName,E.input);p.push({name:E.toolName,input:x,output:E.output,ok:true}),s.emit({type:"step.tool-result",step:o,name:E.toolName,output:E.output,ok:true}),l.delete(E.toolCallId);break}case "tool-error":{let x=l.get(E.toolCallId)?.input??await m(E.toolName,E.input);p.push({name:E.toolName,input:x,output:E.error,ok:false}),s.emit({type:"step.tool-result",step:o,name:E.toolName,output:E.error,ok:false}),l.delete(E.toolCallId);break}case "error":{let k=E.error;throw k instanceof Error?k:new Error(String(k))}}let[T,w]=await Promise.all([y.text,y.usage]),{summary:c,blocked:g}=Ot(T.trim());return {summary:c.length>0?Pt(c):p.length>0?`Executed ${p.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:p,blocked:g,usage:{inputTokens:w.inputTokens??0,outputTokens:w.outputTokens??0,totalTokens:w.totalTokens??0}}},"runOnce");var $t=z$1.object({id:z$1.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z$1.string().min(1).describe("Concrete action to perform"),expectedOutcome:z$1.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z$1.array(z$1.string()).optional().describe("Tool names from the available list, if any")}),xe=8,ie=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array($t).min(1)}),Oe=i(async(e,t,o,n)=>_("agent.plan",{[R.PHASE]:"plan"},async r=>{let s=new Set(o.toolCatalog.map(a=>a.name)),u=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:p,usage:l}=await U(()=>Nt(e,t,u,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:i((a,m)=>o.emit({type:"retry",phase:"plan",attempt:a,error:m.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:l}),r.setAttribute(R.USAGE_TOTAL_TOKENS,l.totalTokens);let d=p.steps.slice(0,xe);return d.length<p.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${p.steps.length} steps; truncated to hard cap ${xe}`}),{thought:p.thought,steps:d.map(a=>{if(!a.suggestedTools?.length)return a;let m=a.suggestedTools.filter(T=>s.has(T)),y=a.suggestedTools.length-m.length;return y>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had ${y} unknown suggestedTools, stripped`}),m.length===0?(o.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:m}})}}),"createInitialPlan"),Nt=i(async(e,t,o,n,r)=>{let s=streamObject({model:n.plannerModel,schema:ie,system:M(ye(o),n.config.systemPrompt),prompt:we(e,n.toolCatalog,t,o),abortSignal:D(r,n.config.llmTimeoutMs??0)}),u="",p=false,l=0;for await(let m of s.partialObjectStream){let y=m?.thought;typeof y=="string"&&y!==u&&(y.startsWith(u)?n.emit({type:"plan.thought-delta",delta:y.slice(u.length)}):p||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),p=true),u=y);let T=m?.steps;if(Array.isArray(T)&&T.length>l)for(;l<T.length;){let w=T[l];if(!w||typeof w.description!="string"||!w.description.length)break;let c={id:typeof w.id=="string"&&w.id?w.id:`s${l+1}`,description:w.description,expectedOutcome:typeof w.expectedOutcome=="string"?w.expectedOutcome:"",suggestedTools:Array.isArray(w.suggestedTools)?w.suggestedTools.filter(g=>typeof g=="string"):void 0};n.emit({type:"plan.step-added",step:c,index:l}),l++;}}let[d,a]=await Promise.all([s.object,s.usage]);return {object:d,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamPlanOnce");var Mt=z$1.discriminatedUnion("mode",[z$1.object({mode:z$1.literal("continue"),reason:z$1.string().min(1).describe("Why the next step is still appropriate")}),z$1.object({mode:z$1.literal("finish"),reason:z$1.string().min(1).describe("Why no more steps are needed")}),z$1.object({mode:z$1.literal("revise"),reason:z$1.string().min(1).describe("Why the plan must change"),newPlan:ie.describe("Plan covering ONLY the remaining work")})]),Pe=i(async(e,t,o,n,r,s)=>_("agent.replan",{[R.PHASE]:"replan"},async u=>{let p=r.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:l,usage:d}=await U(async()=>{let a=await generateObject({model:r.plannerModel,schema:Mt,system:M(be,r.config.systemPrompt),prompt:Se(e,t,o,n,r.toolCatalog,p),abortSignal:D(s,r.config.llmTimeoutMs??0)}),m={inputTokens:a.usage.inputTokens??0,outputTokens:a.usage.outputTokens??0,totalTokens:a.usage.totalTokens??0};return {object:a.object,usage:m}},{maxRetries:r.config.llmMaxRetries??2,signal:s,onRetry:i((a,m)=>r.emit({type:"retry",phase:"replan",attempt:a,error:m.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:d}),u.setAttribute(R.REPLAN_MODE,l.mode),u.setAttribute(R.USAGE_TOTAL_TOKENS,d.totalTokens),l}),"decideNextAction");var _e=i(async(e,t,o,n,r,s)=>_("agent.synthesize",{[R.PHASE]:"synthesize"},async u=>{let{text:p,usage:l}=await U(()=>Dt(e,t,o,n,r,s),{maxRetries:r.config.llmMaxRetries??2,signal:s,onRetry:i((d,a)=>r.emit({type:"retry",phase:"synthesize",attempt:d,error:a.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:l}),u.setAttribute(R.USAGE_TOTAL_TOKENS,l.totalTokens),p}),"synthesizeAnswer"),Dt=i(async(e,t,o,n,r,s)=>{let u=streamText({model:r.synthesizerModel,system:M(ve,r.config.systemPrompt),prompt:Re(e,t,o,n),abortSignal:D(s,r.config.llmTimeoutMs??0)});for await(let d of u.fullStream)if(d.type==="text-delta")d.text&&r.emit({type:"final.text-delta",delta:d.text});else if(d.type==="error"){let a=d.error;throw a instanceof Error?a:new Error(String(a))}let[p,l]=await Promise.all([u.text,u.usage]);return {text:p,usage:{inputTokens:l.inputTokens??0,outputTokens:l.outputTokens??0,totalTokens:l.totalTokens??0}}},"streamOnce");var $e=i(e=>{if(e.blocked)return true;let{toolCalls:t}=e;return t.some((o,n)=>!o.ok&&!t.slice(n+1).some(r=>r.ok&&r.name===o.name))},"shouldCallReplanner"),Kt=i(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return $e(t);let n=i(()=>$e(t),"fallback"),{signal:r}=o,s=o.timeoutMs??0;if(r?.aborted)return n();let u=(async()=>{try{return !!await e(t)}catch(l){return o.onError?.(l),n()}})(),p=Number.isFinite(s)&&s>0;return !p&&!r?u:new Promise(l=>{let d=false,a,m=i(T=>{d||(d=true,a!==void 0&&clearTimeout(a),r?.removeEventListener("abort",y),l(T));},"finish");function y(){m(n());}i(y,"onAbort"),p&&(a=setTimeout(()=>m(n()),s)),r?.addEventListener("abort",y,{once:true}),u.then(m,()=>m(n()));})},"replanTriggered"),V=i(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Yt=i((e,t)=>{let o=e.config.sandboxRoot?.trim()||Ce.join(tmpdir(),"agent-sandbox");return Ce.join(o,t)},"resolveSandboxDir"),Ne=/^[a-zA-Z0-9_-]{1,128}$/,ae=i((e,t)=>{if(!Ne.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Ne}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Ft=i(async(e,t)=>{if(!t.resumeFromRunId)return;if(ae(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await e.config.persistence.loadRun(t.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(ae(o.runId,"snapshot.runId"),o.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Le=i(async(e,t)=>{let o=await Ft(e,t),n=o?.runId??randomUUID();ae(n,"runId");let r=o?.startedAt??Date.now(),s=Yt(e,n);return z.run({runId:n,startedAt:r,sandboxDir:s},async()=>_("agent.run",{[R.RUN_ID]:n,[R.PROVIDER]:e.config.providerType,[R.MODEL]:e.config.model},async u=>{try{let p=await Ht(e,t,o);return u.setAttribute(R.ITERATIONS,p.iterations),u.setAttribute(R.USAGE_TOTAL_TOKENS,p.usage.totalTokens),u.setAttribute(R.USAGE_INPUT_TOKENS,p.usage.inputTokens),u.setAttribute(R.USAGE_OUTPUT_TOKENS,p.usage.outputTokens),p}finally{e.config.keepSandbox||await rm(s,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Ht=i(async(e,t,o)=>{let{signal:n}=t,r=o?.input??t.input,s=o?.history?[...o.history]:t.history?[...t.history]:void 0,u=t.onEvent??(()=>{}),p=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},l=z.getStore()?.startedAt??Date.now(),d=z.getStore()?.runId??"<unknown>",a={...e,emit:i(h=>{h.type==="usage"&&(p.inputTokens+=h.usage.inputTokens,p.outputTokens+=h.usage.outputTokens,p.totalTokens+=h.usage.totalTokens);let A={...h,runId:z.getStore()?.runId};try{u(A);}catch{}try{e.emit(A);}catch{}},"emit")},m=e.config.persistence,y=i(async(h,A)=>{let I=m?.[h];if(I)try{await I(A);}catch(P){a.emit({type:"log",level:"warn",message:`[persistence] ${h} threw: ${P.message}`});}},"callPersistence"),T;if(o)T=o.plan,a.emit({type:"log",level:"info",message:`[resume] continuing run ${d} from step ${o.stepIndex}/${T.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),a.emit({type:"plan.created",plan:T});else {try{T=await Oe(r,s,a,n);}catch(h){if(a.emit({type:"error",error:K(h),phase:"plan"}),V(h)||n?.aborted)throw await y("onRunComplete",{runId:d,startedAt:l,status:"cancelled",input:r,history:s,trace:[],usage:p,stepIndex:0,iterations:0,revisions:0,error:h.message,completedAt:Date.now()}),h;T={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}a.emit({type:"plan.created",plan:T});}let w=o?[...o.trace]:[],c=T,g=o?.stepIndex??0,S=o?.iterations??0,E=o?.revisions??0,k=e.config.maxRevisions??2,x=e.config.maxTotalTokens,f=i((h,A={})=>({runId:d,startedAt:l,status:h,input:r,history:s,plan:c,trace:w,usage:p,stepIndex:g,iterations:S,revisions:E,...A}),"buildSnapshot");o||await y("onRunStart",f("executing"));let b=i(async()=>{await y("onStepComplete",f("executing"));},"persistCheckpoint");for(;S<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(g>=c.steps.length)break;if(x&&p.totalTokens>=x){a.emit({type:"budget.exceeded",tokens:p.totalTokens,cap:x});break}S++;let h=c.steps[g];a.emit({type:"step.start",step:h,index:g});let A=new AbortController;if(t.onStepStart)try{t.onStepStart({step:h,index:g,abort:i(()=>A.abort(),"abort")});}catch(O){a.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${O.message}`});}let I=re([n,A.signal]),P;try{P=await ke(r,c,h,w,s,a,I);}catch(O){if(n?.aborted)throw a.emit({type:"error",error:K(O),phase:"execute"}),await y("onRunComplete",f("cancelled",{error:O.message,completedAt:Date.now()})),O;if(A.signal.aborted&&V(O))a.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),P={step:h,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw a.emit({type:"error",error:K(O),phase:"execute"}),await y("onRunComplete",f("failed",{error:O.message,completedAt:Date.now()})),O}w.push(P),a.emit({type:"step.complete",step:h,result:P});let G=c.steps[g+1]??null;if(G===null){a.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await Kt(e.config.replanAfter,P,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:i(O=>a.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${O.message}`}),"onError")})){a.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),g++,await b();continue}let j;try{j=await Pe(r,c,w,G,a,n);}catch(O){throw a.emit({type:"error",error:K(O),phase:"replan"}),await y("onRunComplete",f(V(O)||n?.aborted?"cancelled":"failed",{error:O.message,completedAt:Date.now()})),O}if(a.emit({type:"replan.decision",mode:j.mode,reason:j.reason,cause:"llm-decision"}),j.mode==="finish")break;if(j.mode==="revise"){if(E>=k){a.emit({type:"revisions.exceeded",cap:k});break}E++,c=j.newPlan,a.emit({type:"plan.revised",plan:c,reason:j.reason}),g=0,await b();continue}g++,await b();}let v;try{v=await _e(r,c,w,s,a,n);}catch(h){throw a.emit({type:"error",error:K(h),phase:"synthesize"}),await y("onRunComplete",f(V(h)||n?.aborted?"cancelled":"failed",{error:h.message,completedAt:Date.now()})),h}return a.emit({type:"final",text:v}),await y("onRunComplete",f("complete",{text:v,completedAt:Date.now()})),{text:v,plan:c,trace:w,iterations:S,usage:p}},"runAgentLoopInner"),K=i(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var B={none:0,error:1,warn:2,info:3,debug:4},Me=i(async(e,t)=>{let o=B[e.logLevel]>=B.debug,n=i(f=>{if(t)try{t(f);}catch(b){o&&console.error("[agent] event handler threw:",b);}},"emit"),r=i((f,b)=>{B[e.logLevel]>=B[f]&&n({type:"log",level:f,message:b});},"log"),s,u=i((f,b)=>{if(!e.tools)return f;let v=[];for(let[h,A]of Object.entries(e.tools)){if(f.tools[h]&&b(h),e.availableTools?.length&&!e.availableTools.includes(h)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(h))continue;f.tools[h]=A;let I=typeof A=="object"&&A&&"description"in A?A.description:"";v.push({name:h,description:typeof I=="string"?I:"",server:"<native>"});}return {tools:f.tools,catalog:[...f.catalog,...v]}},"mergeNativeTools"),p=i(async()=>{let f=await ge(e.mcpServers,r,e.clientName,e.outputSanitizer,h=>s?.(h),e.inputSanitizer),b=Q(f.tools,f.catalog,e.availableTools,e.excludedTools),v=u(b,h=>{throw f.close().catch(()=>{}),new Error(`Native tool "${h}" collides with an MCP-registered tool of the same name`)});return {connection:f,tools:v.tools,catalog:v.catalog}},"connect"),l;try{l=await p();}catch(f){throw n({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let d=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&d>0&&!l.connection.results.some(b=>b.connected)){let b=l.connection.results.filter(h=>!h.connected).map(h=>`${h.name}: ${h.error??"unknown"}`).join("; ");await l.connection.close().catch(()=>{});let v=new Error(`All ${d} configured MCP server(s) failed to connect [${b}]`);throw n({type:"error",error:v,phase:"init"}),v}let a,m,y;try{let f=F(e,void 0,void 0,"executor"),b=F(e,e.planner,e.plannerModel,"planner"),v=F(e,e.synthesizer,e.synthesizerModel,"synthesizer");[a,m,y]=await Promise.all([H(e.clientName,f),H(e.clientName,b),H(e.clientName,v)]);}catch(f){throw await l.connection.close().catch(()=>{}),n({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let T={config:e,executorModel:a,plannerModel:m,synthesizerModel:y,tools:l.tools,toolCatalog:l.catalog.map(f=>({name:f.name,description:f.description})),emit:n},w=0,c=false,g=false,S=false,E=new Set,k=i(async f=>{await l.connection.refreshServer(f);let b=Q(l.connection.tools,l.connection.catalog,e.availableTools,e.excludedTools),v=u(b,h=>{throw new Error(`Native tool "${h}" collides with an MCP-registered tool of the same name`)});for(let h of Object.keys(T.tools))delete T.tools[h];Object.assign(T.tools,v.tools),T.toolCatalog=v.catalog.map(h=>({name:h.name,description:h.description})),r("info",`[mcp] ${f}: tool list refreshed (${v.catalog.length} tools total after filter)`);},"applyRefresh"),x=i(async()=>{if(!(S||c||g)&&!(w>0||E.size===0)){S=true;try{for(;E.size>0&&w===0&&!c&&!g;){let f=E.values().next().value;E.delete(f);try{await k(f);}catch(b){r("warn",`[mcp] ${f}: refresh failed - ${b.message}`);}}}finally{S=false;}}},"drainPendingRefreshes");return s=i(f=>{E.add(f),x();},"onToolsChanged"),{run:i(async f=>{if(c)throw new Error("Agent is closed");if(g)throw new Error("Agent is reconnecting; retry shortly");if(S)throw new Error("Agent is refreshing tools; retry shortly");let b=e.maxConcurrentRuns;if(typeof b=="number"&&b>0&&w>=b)throw new Error(`maxConcurrentRuns reached (${w}/${b}); rate-limit on the caller side or raise the cap`);w++;try{return await Le(T,f)}finally{w--,x();}},"run"),listTools:i(()=>T.toolCatalog.slice(),"listTools"),reconnect:i(async()=>{if(c)throw new Error("Agent is closed");if(g)throw new Error("Already reconnecting");if(S)throw new Error("Agent is refreshing tools; retry shortly");if(w>0)throw new Error(`Cannot reconnect with ${w} active run(s)`);g=true;try{let f=l.connection;E.clear();let b=await p();for(let v of Object.keys(T.tools))delete T.tools[v];Object.assign(T.tools,b.tools),T.toolCatalog=b.catalog.map(v=>({name:v.name,description:v.description})),l=b,await f.close().catch(()=>{});}finally{g=false;}},"reconnect"),close:i(async f=>{c=true;let b=f?.waitForRuns??false,v=f?.timeoutMs??3e4,h=Date.now()+v;if(b&&w>0)for(;w>0&&Date.now()<h;)await new Promise(G=>setTimeout(G,50));w>0&&n({type:"log",level:"warn",message:`[agent] close called with ${w} active run(s); they will fail mid-flight`});let A=Math.max(h-Date.now(),0),I=false,P;await Promise.race([l.connection.close().catch(()=>{}),new Promise(G=>{P=setTimeout(()=>{I=true,G();},A),P.unref?.();})]),P&&clearTimeout(P),I&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${A}ms; abandoning transport(s)`});},"close"),activeRuns:i(()=>w,"activeRuns")}},"createAgent");var J=["openai","anthropic","openai-compatible","google","xai","azure","amazon-bedrock","google-vertex","deepseek","gateway","cloudflare"],Vt=new Set(["openai-compatible","azure"]),Ue=["none","error","warn","info","debug"],De=["all","plan-narrowed"],Ke=i(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!J.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${J.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!Ue.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${Ue.join(" | ")}, got: ${t}`);let o=Vt.has(e)?le("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:le("AGENT_API_KEY"),model:le("AGENT_MODEL"),providerOptions:Ye("AGENT_PROVIDER_OPTIONS"),planner:je("AGENT_PLANNER"),synthesizer:je("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:qt(process.env.MCP_SERVERS),availableTools:Ge(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:Ge(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:ze(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:ze(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:q(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:q(process.env.AGENT_MAX_TOTAL_TOKENS),llmTimeoutMs:q(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:q(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:Bt(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),je=i(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),n=process.env[`${e}_API_KEY`]?.trim(),r=Ye(`${e}_PROVIDER_OPTIONS`);if(!(!t&&!o&&!n&&!r)){if(t&&!J.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${J.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:n||void 0,providerOptions:r}}},"parseStageOverride"),Ye=i(e=>{let t=process.env[e]?.trim();if(!t)return;let o;try{o=JSON.parse(t);}catch(n){throw new Error(`${e} must be valid JSON: ${n.message}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e} must be a JSON object (got ${typeof o})`);return o},"parseProviderOptions"),Bt=i(e=>{let t=e?.trim();if(t){if(!De.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${De.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),q=i(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),le=i(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),Ge=i(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),ze=i((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),qt=i(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(n){throw new Error(`MCP_SERVERS must be valid JSON: ${n.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[n,r]of Object.entries(t)){if(!r||typeof r!="object")throw new Error(`MCP_SERVERS.${n} must be an object`);let s=r,u=typeof s.url=="string"&&s.url.length>0,p=typeof s.command=="string"&&s.command.length>0;if(u&&p)throw new Error(`MCP_SERVERS.${n}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!u&&!p)throw new Error(`MCP_SERVERS.${n}: must specify "url" (HTTP) or "command" (stdio)`);if(u){let l=s.headers&&typeof s.headers=="object"&&!Array.isArray(s.headers)?s.headers:void 0;o[n]={url:s.url,headers:l};continue}if(s.args!==void 0&&!Array.isArray(s.args))throw new Error(`MCP_SERVERS.${n}.args must be a string array`);if(s.env!==void 0&&(!s.env||typeof s.env!="object"||Array.isArray(s.env)))throw new Error(`MCP_SERVERS.${n}.env must be a string-to-string map`);if(s.cwd!==void 0&&typeof s.cwd!="string")throw new Error(`MCP_SERVERS.${n}.cwd must be a string`);o[n]={command:s.command,args:s.args,env:s.env,cwd:s.cwd};}return o},"parseMcpServers");var Zt=16,W=i((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),Fe=i(e=>{try{return W(JSON.stringify(e))}catch{return String(e)}},"formatJson"),He=i(async()=>{let e=Ke(),t=Object.keys(e.mcpServers),o=e.planner?.model??e.plannerModel??e.model,n=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${o} synth=${n} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[mcp] servers=${t.length?t.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /reconnect, /exit
|
|
101
|
-
`);let
|
|
102
|
-
[plan] `),
|
|
103
|
-
`),
|
|
104
|
-
`),
|
|
105
|
-
[plan] ${
|
|
106
|
-
[replan] reason=${
|
|
107
|
-
[step ${
|
|
108
|
-
`),
|
|
109
|
-
assistant> `),
|
|
98
|
+
${pe(t)}`,"",`Execution trace:
|
|
99
|
+
${de(o)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
100
|
+
`),"buildSynthesizerUserPrompt");var $e=s((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let o=e;if(o.name==="AbortError")return false;let r=o.statusCode??o.status;return typeof r=="number"?r===429||r>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?$e(o.cause,t):false},"isRetriable"),j=s(async(e,t)=>{let o=t.baseDelayMs??500,r;for(let n=0;n<=t.maxRetries;n++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(r=i,n===t.maxRetries||!$e(i))throw i;t.onRetry?.(n+1,i);let m=o*2**n+Math.random()*250;await Gt(m,t.signal);}}throw r},"withRetry"),Gt=s((e,t)=>new Promise((o,r)=>{if(t?.aborted){r(new DOMException("Aborted","AbortError"));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),o();},e),i=s(()=>{clearTimeout(n),r(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),ue=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),G=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:ue([e,AbortSignal.timeout(t)]),"withTimeout");var Yt=s((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let o=new Set(t.suggestedTools??[]);if(o.size===0)return t.requiresTools?e.tools:{};let r={};for(let n of o){let i=e.tools[n];i&&(r[n]=i);}return r},"buildActiveToolSet"),Ne="[BLOCKER]",qt=s(e=>e.includes(Ne)?{summary:e.split(Ne).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),me=4e3,Ht=s(e=>e.length>me?`${e.slice(0,me)}... [truncated, ${e.length-me} chars]`:e,"truncateForTrace"),Le=s(async(e,t,o,r,n,i,m)=>_("agent.execute_step",{[b.PHASE]:"execute",[b.STEP_ID]:o.id},async p=>{let c=Date.now(),u=await j(()=>Vt(e,t,o,r,n,i,m),{maxRetries:i.config.llmMaxRetries??2,signal:m,onRetry:s((l,w)=>i.emit({type:"retry",phase:"execute",attempt:l,error:w.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:u.usage}),p.setAttribute(b.USAGE_TOTAL_TOKENS,u.usage.totalTokens),p.setAttribute(b.STEP_BLOCKED,u.blocked),p.setAttribute(b.TOOL_COUNT,u.toolCalls.length),{step:o,summary:u.summary,toolCalls:u.toolCalls,durationMs:Date.now()-c,blocked:u.blocked}}),"executeStep"),Vt=s(async(e,t,o,r,n,i,m)=>{let p=[],c=new Map,u=Yt(i,o),l=i.config.toolSelectionStrategy==="plan-narrowed",w=s(async(h,A)=>{let k=i.config.inputSanitizer;if(!k)return A;try{return await k(h,A)}catch(f){return i.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${h} - ${f.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),v=streamText({model:i.executorModel,tools:u,...l?{activeTools:Object.keys(u)}:{},stopWhen:stepCountIs(i.config.maxStepsPerTask),system:z(ke,i.config.systemPrompt),prompt:Oe(e,t,o,r,n),abortSignal:G(m,i.config.llmTimeoutMs??0)});for await(let h of v.fullStream)switch(h.type){case "text-delta":h.text&&i.emit({type:"step.text-delta",step:o,delta:h.text});break;case "tool-call":{let A=await w(h.toolName,h.input);c.set(h.toolCallId,{name:h.toolName,input:A}),i.emit({type:"step.tool-call",step:o,name:h.toolName,input:A});break}case "tool-result":{let k=c.get(h.toolCallId)?.input??await w(h.toolName,h.input);p.push({name:h.toolName,input:k,output:h.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:h.toolName,output:h.output,ok:true}),c.delete(h.toolCallId);break}case "tool-error":{let k=c.get(h.toolCallId)?.input??await w(h.toolName,h.input);p.push({name:h.toolName,input:k,output:h.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:h.toolName,output:h.error,ok:false}),c.delete(h.toolCallId);break}case "error":{let A=h.error;throw A instanceof Error?A:new Error(String(A))}}let[E,T]=await Promise.all([v.text,v.usage]),{summary:a,blocked:d}=qt(E.trim());return {summary:a.length>0?Ht(a):p.length>0?`Executed ${p.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:p,blocked:d,usage:{inputTokens:T.inputTokens??0,outputTokens:T.outputTokens??0,totalTokens:T.totalTokens??0}}},"runOnce");var Jt=z$1.object({id:z$1.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z$1.string().min(1).describe("Concrete action to perform"),expectedOutcome:z$1.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z$1.array(z$1.string()).optional().describe("Tool names from the available list, if any")}),Me=8,ge=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array(Jt).min(1)}),Ue=s(async(e,t,o,r)=>_("agent.plan",{[b.PHASE]:"plan"},async n=>{let i=new Set(o.toolCatalog.map(l=>l.name)),m=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:p,usage:c}=await j(()=>Wt(e,t,m,o,r),{maxRetries:o.config.llmMaxRetries??2,signal:r,onRetry:s((l,w)=>o.emit({type:"retry",phase:"plan",attempt:l,error:w.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:c}),n.setAttribute(b.USAGE_TOTAL_TOKENS,c.totalTokens);let u=p.steps.slice(0,Me);return u.length<p.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${p.steps.length} steps; truncated to hard cap ${Me}`}),{thought:p.thought,steps:u.map(l=>{if(!l.suggestedTools?.length)return l;let w=l.suggestedTools.filter(E=>i.has(E)),v=l.suggestedTools.length-w.length;return v>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${l.id}" had ${v} unknown suggestedTools, stripped`}),w.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${l.id}" had no valid suggestedTools left; falling back to full toolset`}),{...l,suggestedTools:void 0,requiresTools:true}):{...l,suggestedTools:w}})}}),"createInitialPlan"),Wt=s(async(e,t,o,r,n)=>{let i=streamObject({model:r.plannerModel,schema:ge,system:z(Ie(o),r.config.systemPrompt),prompt:Re(e,r.toolCatalog,t,o),abortSignal:G(n,r.config.llmTimeoutMs??0)}),m="",p=false,c=0;for await(let w of i.partialObjectStream){let v=w?.thought;typeof v=="string"&&v!==m&&(v.startsWith(m)?r.emit({type:"plan.thought-delta",delta:v.slice(m.length)}):p||(r.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),p=true),m=v);let E=w?.steps;if(Array.isArray(E)&&E.length>c)for(;c<E.length;){let T=E[c];if(!T||typeof T.description!="string"||!T.description.length)break;let a={id:typeof T.id=="string"&&T.id?T.id:`s${c+1}`,description:T.description,expectedOutcome:typeof T.expectedOutcome=="string"?T.expectedOutcome:"",suggestedTools:Array.isArray(T.suggestedTools)?T.suggestedTools.filter(d=>typeof d=="string"):void 0};r.emit({type:"plan.step-added",step:a,index:c}),c++;}}let[u,l]=await Promise.all([i.object,i.usage]);return {object:u,usage:{inputTokens:l.inputTokens??0,outputTokens:l.outputTokens??0,totalTokens:l.totalTokens??0}}},"streamPlanOnce");var Zt=z$1.discriminatedUnion("mode",[z$1.object({mode:z$1.literal("continue"),reason:z$1.string().min(1).describe("Why the next step is still appropriate")}),z$1.object({mode:z$1.literal("finish"),reason:z$1.string().min(1).describe("Why no more steps are needed")}),z$1.object({mode:z$1.literal("revise"),reason:z$1.string().min(1).describe("Why the plan must change"),newPlan:ge.describe("Plan covering ONLY the remaining work")})]),De=s(async(e,t,o,r,n,i)=>_("agent.replan",{[b.PHASE]:"replan"},async m=>{let p=n.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:u}=await j(async()=>{let l=await generateObject({model:n.plannerModel,schema:Zt,system:z(Pe,n.config.systemPrompt),prompt:xe(e,t,o,r,n.toolCatalog,p),abortSignal:G(i,n.config.llmTimeoutMs??0)}),w={inputTokens:l.usage.inputTokens??0,outputTokens:l.usage.outputTokens??0,totalTokens:l.usage.totalTokens??0};return {object:l.object,usage:w}},{maxRetries:n.config.llmMaxRetries??2,signal:i,onRetry:s((l,w)=>n.emit({type:"retry",phase:"replan",attempt:l,error:w.message}),"onRetry")});return n.emit({type:"usage",phase:"replan",usage:u}),m.setAttribute(b.REPLAN_MODE,c.mode),m.setAttribute(b.USAGE_TOTAL_TOKENS,u.totalTokens),c}),"decideNextAction");var ze=s(async(e,t,o,r,n,i)=>_("agent.synthesize",{[b.PHASE]:"synthesize"},async m=>{let{text:p,usage:c}=await j(()=>eo(e,t,o,r,n,i),{maxRetries:n.config.llmMaxRetries??2,signal:i,onRetry:s((u,l)=>n.emit({type:"retry",phase:"synthesize",attempt:u,error:l.message}),"onRetry")});return n.emit({type:"usage",phase:"synthesize",usage:c}),m.setAttribute(b.USAGE_TOTAL_TOKENS,c.totalTokens),p}),"synthesizeAnswer"),eo=s(async(e,t,o,r,n,i)=>{let m=streamText({model:n.synthesizerModel,system:z(Ce,n.config.systemPrompt),prompt:_e(e,t,o,r),abortSignal:G(i,n.config.llmTimeoutMs??0)});for await(let u of m.fullStream)if(u.type==="text-delta")u.text&&n.emit({type:"final.text-delta",delta:u.text});else if(u.type==="error"){let l=u.error;throw l instanceof Error?l:new Error(String(l))}let[p,c]=await Promise.all([m.text,m.usage]);return {text:p,usage:{inputTokens:c.inputTokens??0,outputTokens:c.outputTokens??0,totalTokens:c.totalTokens??0}}},"streamOnce");var Ge=s(e=>{if(e.blocked)return true;let{toolCalls:t}=e;return t.some((o,r)=>!o.ok&&!t.slice(r+1).some(n=>n.ok&&n.name===o.name))},"shouldCallReplanner"),no=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return Ge(t);let r=s(()=>Ge(t),"fallback"),{signal:n}=o,i=o.timeoutMs??0;if(n?.aborted)return r();let m=(async()=>{try{return !!await e(t)}catch(c){return o.onError?.(c),r()}})(),p=Number.isFinite(i)&&i>0;return !p&&!n?m:new Promise(c=>{let u=false,l,w=s(E=>{u||(u=true,l!==void 0&&clearTimeout(l),n?.removeEventListener("abort",v),c(E));},"finish");function v(){w(r());}s(v,"onAbort"),p&&(l=setTimeout(()=>w(r()),i)),n?.addEventListener("abort",v,{once:true}),m.then(w,()=>w(r()));})},"replanTriggered"),Q=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),so=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||je.join(tmpdir(),"agent-sandbox");return je.join(o,t)},"resolveSandboxDir"),Ke=/^[a-zA-Z0-9_-]{1,128}$/,fe=s((e,t)=>{if(!Ke.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Ke}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),io=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(fe(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await e.config.persistence.loadRun(t.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(fe(o.runId,"snapshot.runId"),o.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Fe=s(async(e,t)=>{let o=await io(e,t),r=o?.runId??randomUUID();fe(r,"runId");let n=o?.startedAt??Date.now(),i=so(e,r);return K.run({runId:r,startedAt:n,sandboxDir:i},async()=>_("agent.run",{[b.RUN_ID]:r,[b.PROVIDER]:e.config.providerType,[b.MODEL]:e.config.model},async m=>{try{let p=await ao(e,t,o);return m.setAttribute(b.ITERATIONS,p.iterations),m.setAttribute(b.USAGE_TOTAL_TOKENS,p.usage.totalTokens),m.setAttribute(b.USAGE_INPUT_TOKENS,p.usage.inputTokens),m.setAttribute(b.USAGE_OUTPUT_TOKENS,p.usage.outputTokens),p}finally{e.config.keepSandbox||await rm(i,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),ao=s(async(e,t,o)=>{let{signal:r}=t,n=o?.input??t.input,i=o?.history?[...o.history]:t.history?[...t.history]:void 0,m=t.onEvent??(()=>{}),p=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},c=K.getStore()?.startedAt??Date.now(),u=K.getStore()?.runId??"<unknown>",l={...e,emit:s(g=>{g.type==="usage"&&(p.inputTokens+=g.usage.inputTokens,p.outputTokens+=g.usage.outputTokens,p.totalTokens+=g.usage.totalTokens);let R={...g,runId:K.getStore()?.runId};try{m(R);}catch{}try{e.emit(R);}catch{}},"emit")},w=e.config.persistence,v=s(async(g,R)=>{let C=w?.[g];if(C)try{await C(R);}catch(P){l.emit({type:"log",level:"warn",message:`[persistence] ${g} threw: ${P.message}`});}},"callPersistence"),E;if(o)E=o.plan,l.emit({type:"log",level:"info",message:`[resume] continuing run ${u} from step ${o.stepIndex}/${E.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),l.emit({type:"plan.created",plan:E});else {try{E=await Ue(n,i,l,r);}catch(g){if(l.emit({type:"error",error:H(g),phase:"plan"}),Q(g)||r?.aborted)throw await v("onRunComplete",{runId:u,startedAt:c,status:"cancelled",input:n,history:i,trace:[],usage:p,stepIndex:0,iterations:0,revisions:0,error:g.message,completedAt:Date.now()}),g;E={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."}]};}l.emit({type:"plan.created",plan:E});}let T=o?[...o.trace]:[],a=E,d=o?.stepIndex??0,I=o?.iterations??0,h=o?.revisions??0,A=e.config.maxRevisions??2,k=e.config.maxTotalTokens,f=s((g,R={})=>({runId:u,startedAt:c,status:g,input:n,history:i,plan:a,trace:T,usage:p,stepIndex:d,iterations:I,revisions:h,...R}),"buildSnapshot");o||await v("onRunStart",f("executing"));let y=s(async()=>{await v("onStepComplete",f("executing"));},"persistCheckpoint");for(;I<e.config.maxIterations;){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(d>=a.steps.length)break;if(k&&p.totalTokens>=k){l.emit({type:"budget.exceeded",tokens:p.totalTokens,cap:k});break}I++;let g=a.steps[d];l.emit({type:"step.start",step:g,index:d});let R=new AbortController;if(t.onStepStart)try{t.onStepStart({step:g,index:d,abort:s(()=>R.abort(),"abort")});}catch(O){l.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${O.message}`});}let C=ue([r,R.signal]),P;try{P=await Le(n,a,g,T,i,l,C);}catch(O){if(r?.aborted)throw l.emit({type:"error",error:H(O),phase:"execute"}),await v("onRunComplete",f("cancelled",{error:O.message,completedAt:Date.now()})),O;if(R.signal.aborted&&Q(O))l.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),P={step:g,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw l.emit({type:"error",error:H(O),phase:"execute"}),await v("onRunComplete",f("failed",{error:O.message,completedAt:Date.now()})),O}T.push(P),l.emit({type:"step.complete",step:g,result:P});let $=a.steps[d+1]??null;if($===null){l.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await no(e.config.replanAfter,P,{signal:r,timeoutMs:e.config.llmTimeoutMs??0,onError:s(O=>l.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${O.message}`}),"onError")})){l.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),d++,await y();continue}let N;try{N=await De(n,a,T,$,l,r);}catch(O){throw l.emit({type:"error",error:H(O),phase:"replan"}),await v("onRunComplete",f(Q(O)||r?.aborted?"cancelled":"failed",{error:O.message,completedAt:Date.now()})),O}if(l.emit({type:"replan.decision",mode:N.mode,reason:N.reason,cause:"llm-decision"}),N.mode==="finish")break;if(N.mode==="revise"){if(h>=A){l.emit({type:"revisions.exceeded",cap:A});break}h++,a=N.newPlan,l.emit({type:"plan.revised",plan:a,reason:N.reason}),d=0,await y();continue}d++,await y();}let S;try{S=await ze(n,a,T,i,l,r);}catch(g){throw l.emit({type:"error",error:H(g),phase:"synthesize"}),await v("onRunComplete",f(Q(g)||r?.aborted?"cancelled":"failed",{error:g.message,completedAt:Date.now()})),g}return l.emit({type:"final",text:S}),await v("onRunComplete",f("complete",{text:S,completedAt:Date.now()})),{text:S,plan:a,trace:T,iterations:I,usage:p}},"runAgentLoopInner"),H=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var ee={none:0,error:1,warn:2,info:3,debug:4},Ye=s(async(e,t)=>{let o=ee[e.logLevel]>=ee.debug,r=s(f=>{if(t)try{t(f);}catch(y){o&&console.error("[agent] event handler threw:",y);}},"emit"),n=s((f,y)=>{ee[e.logLevel]>=ee[f]&&r({type:"log",level:f,message:y});},"log"),i,m=s((f,y)=>{if(!e.tools)return f;let S=[];for(let[g,R]of Object.entries(e.tools)){if(f.tools[g]&&y(g),e.availableTools?.length&&!e.availableTools.includes(g)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(g))continue;f.tools[g]=R;let C=typeof R=="object"&&R&&"description"in R?R.description:"";S.push({name:g,description:typeof C=="string"?C:"",server:"<native>"});}return {tools:f.tools,catalog:[...f.catalog,...S]}},"mergeNativeTools"),p=s(async()=>{let f=await Se(e.mcpServers,n,e.clientName,e.outputSanitizer,g=>i?.(g),e.inputSanitizer),y=ae(f.tools,f.catalog,e.availableTools,e.excludedTools,n),S=m(y,g=>{throw f.close().catch(()=>{}),new Error(`Native tool "${g}" collides with an MCP-registered tool of the same name`)});return {connection:f,tools:S.tools,catalog:S.catalog}},"connect"),c;try{c=await p();}catch(f){throw r({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let u=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&u>0&&!c.connection.results.some(y=>y.connected)){let y=c.connection.results.filter(g=>!g.connected).map(g=>`${g.name}: ${g.error??"unknown"}`).join("; ");await c.connection.close().catch(()=>{});let S=new Error(`All ${u} configured MCP server(s) failed to connect [${y}]`);throw r({type:"error",error:S,phase:"init"}),S}let l,w,v;try{let f=X(e,void 0,void 0,"executor"),y=X(e,e.planner,e.plannerModel,"planner"),S=X(e,e.synthesizer,e.synthesizerModel,"synthesizer");[l,w,v]=await Promise.all([Z(e.clientName,f),Z(e.clientName,y),Z(e.clientName,S)]);}catch(f){throw await c.connection.close().catch(()=>{}),r({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let E={config:e,executorModel:l,plannerModel:w,synthesizerModel:v,tools:c.tools,toolCatalog:c.catalog.map(f=>({name:f.name,description:f.description})),emit:r},T=0,a=false,d=false,I=false,h=new Set,A=s(async f=>{await c.connection.refreshServer(f);let y=ae(c.connection.tools,c.connection.catalog,e.availableTools,e.excludedTools),S=m(y,g=>{throw new Error(`Native tool "${g}" collides with an MCP-registered tool of the same name`)});for(let g of Object.keys(E.tools))delete E.tools[g];Object.assign(E.tools,S.tools),E.toolCatalog=S.catalog.map(g=>({name:g.name,description:g.description})),n("info",`[mcp] ${f}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),k=s(async()=>{if(!(I||a||d)&&!(T>0||h.size===0)){I=true;try{for(;h.size>0&&T===0&&!a&&!d;){let f=h.values().next().value;h.delete(f);try{await A(f);}catch(y){n("warn",`[mcp] ${f}: refresh failed - ${y.message}`);}}}finally{I=false;}}},"drainPendingRefreshes");return i=s(f=>{h.add(f),k();},"onToolsChanged"),{run:s(async f=>{if(a)throw new Error("Agent is closed");if(d)throw new Error("Agent is reconnecting; retry shortly");if(I)throw new Error("Agent is refreshing tools; retry shortly");let y=e.maxConcurrentRuns;if(typeof y=="number"&&y>0&&T>=y)throw new Error(`maxConcurrentRuns reached (${T}/${y}); rate-limit on the caller side or raise the cap`);T++;try{return await Fe(E,f)}finally{T--,k();}},"run"),listTools:s(()=>E.toolCatalog.slice(),"listTools"),reconnect:s(async()=>{if(a)throw new Error("Agent is closed");if(d)throw new Error("Already reconnecting");if(I)throw new Error("Agent is refreshing tools; retry shortly");if(T>0)throw new Error(`Cannot reconnect with ${T} active run(s)`);d=true;try{let f=c.connection;h.clear();let y=await p();for(let S of Object.keys(E.tools))delete E.tools[S];Object.assign(E.tools,y.tools),E.toolCatalog=y.catalog.map(S=>({name:S.name,description:S.description})),c=y,await f.close().catch(()=>{});}finally{d=false;}},"reconnect"),close:s(async f=>{a=true;let y=f?.waitForRuns??false,S=f?.timeoutMs??3e4,g=Date.now()+S;if(y&&T>0)for(;T>0&&Date.now()<g;)await new Promise($=>setTimeout($,50));T>0&&r({type:"log",level:"warn",message:`[agent] close called with ${T} active run(s); they will fail mid-flight`});let R=Math.max(g-Date.now(),0),C=false,P;await Promise.race([c.connection.close().catch(()=>{}),new Promise($=>{P=setTimeout(()=>{C=true,$();},R),P.unref?.();})]),P&&clearTimeout(P),C&&r({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${R}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>T,"activeRuns")}},"createAgent");var oe=["openai","anthropic","openai-compatible","google","xai","azure","amazon-bedrock","google-vertex","deepseek","gateway","cloudflare"],lo=new Set(["openai-compatible","azure"]),qe=["none","error","warn","info","debug"],He=["all","plan-narrowed"],We=s(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!oe.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${oe.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!qe.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${qe.join(" | ")}, got: ${t}`);let o=lo.has(e)?he("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:he("AGENT_API_KEY"),model:he("AGENT_MODEL"),providerOptions:Xe("AGENT_PROVIDER_OPTIONS"),planner:Ve("AGENT_PLANNER"),synthesizer:Ve("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:po(process.env.MCP_SERVERS),availableTools:Be(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:Be(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:Je(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:Je(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:te(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:te(process.env.AGENT_MAX_TOTAL_TOKENS),llmTimeoutMs:te(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:te(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:co(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),Ve=s(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),r=process.env[`${e}_API_KEY`]?.trim(),n=Xe(`${e}_PROVIDER_OPTIONS`);if(!(!t&&!o&&!r&&!n)){if(t&&!oe.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${oe.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:r||void 0,providerOptions:n}}},"parseStageOverride"),Xe=s(e=>{let t=process.env[e]?.trim();if(!t)return;let o;try{o=JSON.parse(t);}catch(r){throw new Error(`${e} must be valid JSON: ${r.message}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e} must be a JSON object (got ${typeof o})`);return o},"parseProviderOptions"),co=s(e=>{let t=e?.trim();if(t){if(!He.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${He.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),te=s(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),he=s(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),Be=s(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),Je=s((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),po=s(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(r){throw new Error(`MCP_SERVERS must be valid JSON: ${r.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[r,n]of Object.entries(t)){if(!n||typeof n!="object")throw new Error(`MCP_SERVERS.${r} must be an object`);let i=n,m=typeof i.url=="string"&&i.url.length>0,p=typeof i.command=="string"&&i.command.length>0;if(m&&p)throw new Error(`MCP_SERVERS.${r}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!m&&!p)throw new Error(`MCP_SERVERS.${r}: must specify "url" (HTTP) or "command" (stdio)`);if(m){let c=i.headers&&typeof i.headers=="object"&&!Array.isArray(i.headers)?i.headers:void 0;o[r]={url:i.url,headers:c};continue}if(i.args!==void 0&&!Array.isArray(i.args))throw new Error(`MCP_SERVERS.${r}.args must be a string array`);if(i.env!==void 0&&(!i.env||typeof i.env!="object"||Array.isArray(i.env)))throw new Error(`MCP_SERVERS.${r}.env must be a string-to-string map`);if(i.cwd!==void 0&&typeof i.cwd!="string")throw new Error(`MCP_SERVERS.${r}.cwd must be a string`);o[r]={command:i.command,args:i.args,env:i.env,cwd:i.cwd};}return o},"parseMcpServers");var fo=16,re=s((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),Ze=s(e=>{try{return re(JSON.stringify(e))}catch{return String(e)}},"formatJson"),Qe=s(async()=>{let e=We(),t=Object.keys(e.mcpServers),o=e.planner?.model??e.plannerModel??e.model,r=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${o} synth=${r} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[mcp] servers=${t.length?t.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /reconnect, /exit
|
|
101
|
+
`);let n=false,i=false,p=await Ye(e,s(a=>{switch(a.type){case "log":console.log(`[${a.level}] ${a.message}`);break;case "plan.thought-delta":i||(process.stdout.write(`
|
|
102
|
+
[plan] `),i=true),process.stdout.write(a.delta);break;case "plan.step-added":i&&(process.stdout.write(`
|
|
103
|
+
`),i=false),console.log(` ${a.index+1}. ${a.step.description}`);break;case "plan.created":i?(process.stdout.write(`
|
|
104
|
+
`),i=false):console.log(`
|
|
105
|
+
[plan] ${a.plan.thought}`);for(let[d,I]of a.plan.steps.entries()){let h=I.suggestedTools?.length?` (tools: ${I.suggestedTools.join(", ")})`:"";console.log(` ${d+1}. ${I.description}${h}`);}break;case "plan.revised":console.log(`
|
|
106
|
+
[replan] reason=${a.reason}`);for(let[d,I]of a.plan.steps.entries())console.log(` ${d+1}. ${I.description}`);break;case "step.start":console.log(`
|
|
107
|
+
[step ${a.index+1}] ${a.step.description}`);break;case "step.tool-call":console.log(` -> ${a.name} ${Ze(a.input)}`);break;case "step.tool-result":{let d=a.ok?"ok":"fail";console.log(` <- ${a.name} ${d} ${Ze(a.output)}`);break}case "step.complete":console.log(` = ${re(a.result.summary,400)} (${a.result.durationMs}ms, ${a.result.toolCalls.length} tool calls)`);break;case "replan.decision":a.mode!=="continue"&&console.log(`[replan] ${a.mode} (${a.cause}): ${a.reason}`);break;case "usage":break;case "retry":a.phase==="plan"&&i&&(process.stdout.write(`
|
|
108
|
+
`),i=false),console.log(`[retry] ${a.phase} attempt=${a.attempt}: ${a.error}`);break;case "budget.exceeded":console.log(`[budget] token cap reached: ${a.tokens}/${a.cap} - finishing early`);break;case "revisions.exceeded":console.log(`[budget] max ${a.cap} replan-revisions reached - finishing early`);break;case "final.text-delta":n||(process.stdout.write(`
|
|
109
|
+
assistant> `),n=true),process.stdout.write(a.delta);break;case "final":n?(process.stdout.write(`
|
|
110
110
|
|
|
111
|
-
`),
|
|
112
|
-
assistant> ${
|
|
113
|
-
`);break;case "error":
|
|
114
|
-
`),
|
|
115
|
-
[abort] forcing exit`),process.exit(130)),
|
|
116
|
-
[abort] cancelling current run...`),
|
|
117
|
-
you> `,{signal:
|
|
111
|
+
`),n=false):console.log(`
|
|
112
|
+
assistant> ${a.text}
|
|
113
|
+
`);break;case "error":a.phase==="plan"&&i&&(process.stdout.write(`
|
|
114
|
+
`),i=false),console.error(`[error] (${a.phase}) ${a.error.message}`);break}},"onEvent")),c=p.listTools();console.log(`[tools] available=${c.length}${c.length?`: ${c.map(a=>a.name).join(", ")}`:""}`);let u=createInterface({input:stdin,output:stdout}),l=[],w=null,v=null,E=0,T=s(()=>{if(E++,E>=2&&(console.log(`
|
|
115
|
+
[abort] forcing exit`),process.exit(130)),w){console.log(`
|
|
116
|
+
[abort] cancelling current run...`),w.abort();return}if(v){v.abort();return}},"onSigInt");process.on("SIGINT",T);try{for(;;){let a;v=new AbortController;try{a=(await u.question(`
|
|
117
|
+
you> `,{signal:v.signal})).trim(),E=0;}catch(d){if(d?.name==="AbortError")break;break}finally{v=null;}if(a){if(a==="/exit"||a==="/quit")break;if(a==="/tools"){if(c.length===0)console.log("[tools] (none)");else for(let d of c)console.log(` - ${d.name}: ${re(d.description,200)}`);continue}if(a==="/status"){console.log(`[status] model=${e.model} planner=${o} synth=${r}`),console.log(`[status] tools=${c.length} mcp=${t.join(", ")||"(none)"} historyTurns=${l.length}`);continue}if(a==="/history"){if(l.length===0)console.log("[history] (empty)");else for(let d of l)console.log(` ${d.role}: ${re(d.content,200)}`);continue}if(a==="/reset"){l.length=0,console.log("[history] cleared");continue}if(a==="/reconnect"){try{await p.reconnect();let d=p.listTools();c.length=0;for(let I of d)c.push(I);console.log(`[mcp] reconnected, ${c.length} tools available`);}catch(d){console.error("[error] reconnect failed:",d.message);}continue}n=!1,i=!1,w=new AbortController;try{let d=await p.run({input:a,history:l,signal:w.signal});for(E=0,l.push({role:"user",content:a}),l.push({role:"assistant",content:d.text});l.length>fo;)l.shift();console.log(`[meta] iterations=${d.iterations} steps=${d.trace.length} tokens=${d.usage.totalTokens} (in=${d.usage.inputTokens} out=${d.usage.outputTokens})`);}catch(d){d?.name==="AbortError"?(console.log("[abort] run cancelled"),E=0):console.error("[error]",d.message);}finally{w=null;}}}}finally{process.off("SIGINT",T),u.close(),await p.close({timeoutMs:5e3}).catch(a=>console.error("[cleanup] agent",a));}},"runRepl");var ho=s(async()=>{let e;try{e=we(process.argv.slice(2));}catch(t){console.error(t.message),console.error("\nRun `dd-agent --help` for usage."),process.exit(2);}if(e.help){process.stdout.write(ye);return}if(e.envFile)try{process.loadEnvFile(e.envFile);}catch(t){console.error(`Failed to load env file ${e.envFile}: ${t.message}`),process.exit(2);}for(let[t,o]of Object.entries(e.overrides))process.env[t]=o;try{await Qe();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
|
|
118
118
|
|
|
119
|
-
Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");
|
|
119
|
+
Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");ho().catch(e=>{console.error(e),process.exit(1);});
|