@dudko.dev/agent 0.0.2 → 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 CHANGED
@@ -2,6 +2,12 @@
2
2
 
3
3
  A small, opinionated planning agent that uses tools exposed via [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers, built on top of the [Vercel AI SDK](https://sdk.vercel.ai/).
4
4
 
5
+ [![npm](https://img.shields.io/npm/v/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
6
+ [![npm](https://img.shields.io/npm/dy/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
7
+ [![NpmLicense](https://img.shields.io/npm/l/@dudko.dev/agent.svg)](https://www.npmjs.com/package/@dudko.dev/agent)
8
+ ![GitHub last commit](https://img.shields.io/github/last-commit/dudko-dev/agent.svg)
9
+ ![GitHub release](https://img.shields.io/github/release/dudko-dev/agent.svg)
10
+
5
11
  The agent runs a plan → execute → replan → synthesize loop:
6
12
 
7
13
  1. **Plan** — the planner LLM produces a structured plan (a thought + ordered steps with optional suggested tools).
@@ -66,6 +72,54 @@ setTimeout(() => ac.abort(), 30_000)
66
72
  await agent.run({ input: '...', signal: ac.signal })
67
73
  ```
68
74
 
75
+ The run-level signal terminates everything. To cancel a single step (e.g. a long tool call) without aborting the whole run, use `onStepStart` — the cancelled step records as `blocked: true` and the replanner runs next:
76
+
77
+ ```ts
78
+ await agent.run({
79
+ input: '...',
80
+ onStepStart: ({ step, abort }) => {
81
+ if (step.suggestedTools?.includes('expensive_tool')) {
82
+ abort()
83
+ }
84
+ },
85
+ })
86
+ ```
87
+
88
+ ### Resume after crash
89
+
90
+ Wire a persistence adapter that implements `loadRun(runId)`, then resume with the run id:
91
+
92
+ ```ts
93
+ import { makeSqlitePersistence } from './examples/persistence-sqlite.ts'
94
+
95
+ const persistence = makeSqlitePersistence('./runs.db')
96
+ const agent = await createAgent({ ..., persistence, keepSandbox: true })
97
+
98
+ try {
99
+ await agent.run({ input: '...' })
100
+ } catch (err) {
101
+ // process crashed mid-run; the snapshot has the latest checkpoint.
102
+ }
103
+
104
+ // Later, in a new process:
105
+ await agent.run({ input: '', resumeFromRunId: '<saved-run-id>' })
106
+ ```
107
+
108
+ Caveats:
109
+
110
+ - **Idempotency.** Resume re-enters the loop at the saved checkpoint (the iteration boundary after the last successful step). A crash mid-step means the in-flight step's tool calls are lost; on resume, the runner re-executes that step from scratch. If your tools have side effects (writes, payments, emails), the same call may fire twice. Design tools to be idempotent or guard against replay.
111
+ - **Sandbox.** The per-run sandbox directory is auto-cleaned on completion. To resume, set `keepSandbox: true` so files written by earlier steps survive the crash. Without it, the trace's file references will point to a directory that no longer exists.
112
+ - **Plan changes.** The saved `currentPlan` (post any revise) is what gets used on resume — the planner is not re-invoked.
113
+ - **Caps inherit.** `iterations` and `revisions` carry over, so per-run caps still apply across the boundary.
114
+ - **Terminal status.** Resuming a run with `status: 'complete'` throws — re-read the saved `text` directly instead.
115
+ - **Event semantics.** On resume the runner re-emits a `plan.created` event so consumers attaching mid-resume see the canonical plan; consumers that store every event will observe `plan.created` twice for the same `runId`. `onRunStart` is **not** re-fired (the original run already emitted it) — code that counts run starts must use `runId` for de-duplication. `onStepComplete` only fires for steps the resumed run actually executes; pre-resume steps are already in the loaded `trace`.
116
+ - **Inputs are locked to the snapshot.** Both `options.input` and `options.history` passed to `agent.run({ resumeFromRunId })` are **silently ignored** in favor of the values stored at the original run start. This keeps the resumed prompt deterministic against the saved trace; pass an empty input (`input: ''`) to make the override explicit.
117
+ - **runId hygiene.** Persisted `runId`s end up in filesystem paths (`<sandboxRoot>/<runId>/`) and are validated against `^[a-zA-Z0-9_-]{1,128}$`. A persistence adapter that returns a snapshot whose `runId` differs from the requested one, or that contains path-unsafe characters, is rejected.
118
+
119
+ ### OpenTelemetry
120
+
121
+ The agent emits OTel spans for `agent.run`, `agent.plan`, `agent.execute_step`, `agent.replan`, and `agent.synthesize` via the `@opentelemetry/api` package. With no SDK installed, the calls are no-ops; install your favorite OTel exporter (jaeger, otlp, console) and you get traces and parent-child relationships out of the box. Span attributes are documented in [`src/tracing.ts`](./src/tracing.ts).
122
+
69
123
  ### Conversation history
70
124
 
71
125
  Pass prior turns as `history` on each run; the agent treats them as context but does not mutate the array.
@@ -90,9 +144,12 @@ Use `getHeaders` on a server config to inject fresh credentials at connect time,
90
144
  | --- | --- |
91
145
  | `providerType` | `'openai' \| 'anthropic' \| 'google' \| 'openai-compatible'` |
92
146
  | `baseURL` | Required for `openai-compatible`; optional for the rest. |
93
- | `model` / `plannerModel` / `synthesizerModel` | The latter two default to `model`. |
94
- | `mcpServers` | `Record<name, { url, headers?, getHeaders? }>` |
95
- | `availableTools` / `excludedTools` | Whitelist / blacklist applied to MCP-discovered tools. |
147
+ | `model` | Default model for every stage (executor / planner / synthesizer) when no per-stage override is set. |
148
+ | `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`. |
149
+ | `plannerModel` / `synthesizerModel` | **Deprecated** model-only shortcuts. Equivalent to `planner: { model }` / `synthesizer: { model }`. The override block, if present, wins. |
150
+ | `mcpServers` | `Record<name, { url, headers?, getHeaders? } \| { command, args?, env?, cwd? }>` — HTTP/SSE for remote, stdio for locally-spawned servers. |
151
+ | `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). |
152
+ | `availableTools` / `excludedTools` | Whitelist / blacklist applied to **all** tools (MCP and native). |
96
153
  | `maxIterations` | Cap on **executed steps** across the run (every step counts, including those run after a `revise`). |
97
154
  | `maxStepsPerTask` | Cap on LLM steps inside a single executor call (multi-step tool calling). |
98
155
  | `maxRevisions` | Cap on `revise` decisions the replanner can make per run. Default `2`. |
@@ -100,8 +157,14 @@ Use `getHeaders` on a server config to inject fresh credentials at connect time,
100
157
  | `llmTimeoutMs` / `llmMaxRetries` | Per-LLM-call timeout and retry budget. |
101
158
  | `toolSelectionStrategy` | `'all'` (default) gives the executor every tool each step; `'plan-narrowed'` exposes only `step.suggestedTools`. |
102
159
  | `outputSanitizer` | Optional `(toolName, output) => unknown` hook to redact tool results before they reach the LLM. |
103
- | `systemPrompt` | Appended to the executor system prompt. |
160
+ | `inputSanitizer` | Optional `(toolName, input) => unknown` hook to redact LLM-generated tool args before they hit the MCP server **and** before they appear in `step.tool-call` events. **Must be idempotent** — applied at both the event boundary and the dispatch boundary. |
161
+ | `outputSanitizer` ordering | The sanitizer runs on the **raw MCP `result.content`** (image/audio base64 still inline), **before** the agent spills binary parts to the sandbox. This favors privacy: a sanitizer that drops a sensitive image keeps the bytes out of the disk entirely. If you want post-spill sanitization (e.g. redact a path), do it in your tool wrapper instead. |
162
+ | `sandboxRoot` | Per-run sandbox subdirs are created at `<sandboxRoot>/<runId>/` for tools that spill binary content (images, audio, blob resources). Defaults to `<os.tmpdir()>/agent-sandbox`. |
163
+ | `keepSandbox` | When `true`, the per-run directory is not removed after the run completes. Default `false`. |
164
+ | `systemPrompt` | Appended to the planner, executor, replanner, and synthesizer system prompts so the same domain context (persona, language, tone) reaches every stage. |
104
165
  | `failOnNoTools` | When `true`, `createAgent` throws if every configured MCP server failed to connect (otherwise the agent starts with zero tools and emits an `error`-level log). Default `false`. |
166
+ | `maxConcurrentRuns` | Hard cap on concurrent `agent.run()` calls. When reached, further calls reject synchronously. Default: unlimited. Intentionally a throw, not a queue — back-pressure belongs on the caller. |
167
+ | `persistence` | Optional `IPersistence` facade. Receives `IRunSnapshot` at run start, at every iteration boundary, and at run completion. Implementing the optional `loadRun(runId)` enables resume via `agent.run({ resumeFromRunId })`. See [`examples/persistence-sqlite.ts`](./examples/persistence-sqlite.ts) for a `node:sqlite`-backed adapter. |
105
168
  | `logLevel` | `'none' \| 'error' \| 'warn' \| 'info' \| 'debug'` |
106
169
 
107
170
  ## API
@@ -121,6 +184,7 @@ A single agent instance supports concurrent `run()` calls — each gets its own
121
184
  Top-level exports beyond `createAgent`:
122
185
 
123
186
  - `getCurrentRunId(): string | undefined` — read the active run's id from any code reachable from `agent.run()` (planner, executor, MCP `execute`, retry sleeps, …). Useful for correlating logs/metrics across concurrent runs on a single agent instance.
187
+ - `getCurrentRunSandbox(): string | undefined` — absolute path to the active run's sandbox directory. Native tools that need to spill binary output should write into this path so files are auto-cleaned when the run completes (set `keepSandbox: true` to retain).
124
188
  - `redactHeaders(headers)` — small helper for masking `Authorization`, `X-Api-Key`, `Cookie`, etc. when logging request headers (e.g. inside an `outputSanitizer` or your own MCP transport wrapper).
125
189
 
126
190
  ### Closing the agent
package/dist/cli.js CHANGED
@@ -1,28 +1,43 @@
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 {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {dynamicTool,jsonSchema,generateObject,streamObject,streamText,stepCountIs}from'ai';import {URL}from'url';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {createOpenAI}from'@ai-sdk/openai';import {createOpenAICompatible}from'@ai-sdk/openai-compatible';import {randomUUID}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {z}from'zod';var ye=Object.defineProperty;var s=(e,t)=>ye(e,"name",{value:t,configurable:true});var q=`Usage: dd-agent [options]
2
+ import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {dynamicTool,jsonSchema,generateObject,streamObject,streamText,stepCountIs}from'ai';import {randomUUID}from'crypto';import {rm,mkdir,writeFile}from'fs/promises';import Pe from'path';import {URL}from'url';import {AsyncLocalStorage}from'async_hooks';import {SpanStatusCode,trace}from'@opentelemetry/api';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {createOpenAI}from'@ai-sdk/openai';import {createOpenAICompatible}from'@ai-sdk/openai-compatible';import {tmpdir}from'os';import {z as z$1}from'zod';var Ke=Object.defineProperty;var i=(e,t)=>Ke(e,"name",{value:t,configurable:true});var le=`Usage: dd-agent [options]
3
3
 
4
4
  Options:
5
- --env-file=<path> Load env vars from a dotenv file before starting
6
- -h, --help Show this help
5
+ --env-file=<path> Load env vars from a dotenv file before starting
6
+ --provider=<type> AGENT_PROVIDER_TYPE (openai|anthropic|google|openai-compatible)
7
+ --model=<id> AGENT_MODEL
8
+ --planner-model=<id> AGENT_PLANNER_MODEL
9
+ --synthesizer-model=<id> AGENT_SYNTHESIZER_MODEL
10
+ --base-url=<url> AGENT_BASE_URL
11
+ --log-level=<level> AGENT_LOG_LEVEL (none|error|warn|info|debug)
12
+ --max-iterations=<n> AGENT_MAX_ITERATIONS
13
+ --max-steps-per-task=<n> AGENT_MAX_STEPS_PER_TASK
14
+ --tool-strategy=<v> AGENT_TOOL_SELECTION_STRATEGY (all|plan-narrowed)
15
+ -h, --help Show this help
16
+
17
+ API keys are still read from env (AGENT_API_KEY etc.) - we deliberately do
18
+ not accept them as flags so they don't end up in shell history.
7
19
 
8
20
  Required env vars (set directly or via --env-file):
9
21
  AGENT_PROVIDER_TYPE one of: openai | anthropic | openai-compatible | google
10
22
  AGENT_API_KEY provider API key
11
23
  AGENT_MODEL model id
12
- MCP_SERVERS JSON: { "<name>": { "url": "...", "headers"?: {...} } }
24
+ MCP_SERVERS JSON: { "<name>": { "url": "...", "headers"?: {...} } | { "command": "...", "args"?: [], "env"?: {} } }
13
25
 
14
26
  Commands inside the REPL:
15
27
  /status, /tools, /history, /reset, /reconnect, /exit
16
- `,H=s(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"}},strict:true,allowPositionals:false});return {envFile:t["env-file"],help:!!t.help}},"parseCliArgs");var B=s(async(e,t,o,n)=>{let l=[],a={},c=[],p=[];for(let[i,u]of Object.entries(e)){if(u.headers&&u.getHeaders)throw new Error(`MCP server "${i}": specify either headers or getHeaders, not both`);try{let f=u.getHeaders?await u.getHeaders():u.headers,r=new StreamableHTTPClientTransport(new URL(u.url),{requestInit:f?{headers:f}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});r.onerror=g=>t("warn",`[mcp] ${i}: transport error - ${g.message}`),r.onclose=()=>t("warn",`[mcp] ${i}: transport closed`);let d=new Client({name:o,version:"0.0.0"});await d.connect(r),l.push(d);let T=await d.listTools(),w=0;for(let g of T.tools){let h=`${i}__${g.name}`,m=g.description??"";a[h]=dynamicTool({description:m,inputSchema:jsonSchema(g.inputSchema),execute:s(async(y,A)=>{let z=await d.callTool({name:g.name,arguments:y??{}},void 0,A?.abortSignal?{signal:A.abortSignal}:void 0),I=Re(z.content);if(!n)return I;try{return await n(h,I)}catch(v){return t("warn",`[mcp] ${h}: outputSanitizer threw - ${v.message}; output replaced with placeholder`),"[output redacted: sanitizer failed]"}},"execute")}),c.push({name:h,description:m,server:i}),w++;}t("info",`[mcp] ${i}: connected, ${w} tools`),p.push({name:i,connected:!0});}catch(f){let r=f.message;t("error",`[mcp] ${i}: failed to connect - ${r}`),p.push({name:i,connected:false,error:r});}}return {tools:a,catalog:c,results:p,close:s(async()=>{await Promise.allSettled(l.map(i=>i.close()));},"close")}},"connectMcpServers"),Re=s(e=>{if(!Array.isArray(e))return e;let t=e;return t.length>0&&t.every(n=>n?.type==="text"&&typeof n.text=="string")?t.map(n=>n.text).join(`
17
- `):t.map(n=>n?.type==="text"&&typeof n.text=="string"?n.text:n)},"flattenContent"),K=s((e,t,o,n)=>{let l=o?.length?new Set(o):null,a=n?.length?new Set(n):null,c={},p=[];for(let i of t){if(l&&!l.has(i.name)||!l&&a?.has(i.name))continue;let u=e[i.name];u&&(c[i.name]=u,p.push(i));}return {tools:c,catalog:p}},"filterTools");var C=s((e,t)=>{switch(e.providerType){case "openai":return createOpenAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "anthropic":return createAnthropic({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "openai-compatible":{if(!e.baseURL)throw new Error("openai-compatible provider requires baseURL");return createOpenAICompatible({name:e.clientName,baseURL:e.baseURL,apiKey:e.apiKey})(t)}case "google":return createGoogleGenerativeAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t)}},"buildModel");var O=new AsyncLocalStorage;var N=s(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),o=e.length-t.length,n=[];o>0&&n.push(`(${o} earlier turns omitted)`);for(let l of t){let a=l.content.length>1500?`${l.content.slice(0,1500)}... [truncated]`:l.content;n.push(`${l.role}: ${a}`);}return n.join(`
18
- `)},"renderHistory"),$e={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},V=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=$e[t],l=e.slice(0,o),a=e.length-l.length,c=l.map(p=>{let i=(p.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${p.name}: ${i}`});return a>0&&c.push(`... and ${a} more tools`),c.join(`
19
- `)},"renderToolCatalog"),M=1500,Pe=s(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>M?`${t.slice(0,M)}... [truncated, ${t.length-M} chars]`:t},"truncateOutput"),Oe=s((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${Pe(n.output)}`).join(`
28
+ `,He={provider:"AGENT_PROVIDER_TYPE",model:"AGENT_MODEL","planner-model":"AGENT_PLANNER_MODEL","synthesizer-model":"AGENT_SYNTHESIZER_MODEL","base-url":"AGENT_BASE_URL","log-level":"AGENT_LOG_LEVEL","max-iterations":"AGENT_MAX_ITERATIONS","max-steps-per-task":"AGENT_MAX_STEPS_PER_TASK","tool-strategy":"AGENT_TOOL_SELECTION_STRATEGY"},ce=i(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"},provider:{type:"string"},model:{type:"string"},"planner-model":{type:"string"},"synthesizer-model":{type:"string"},"base-url":{type:"string"},"log-level":{type:"string"},"max-iterations":{type:"string"},"max-steps-per-task":{type:"string"},"tool-strategy":{type:"string"}},strict:true,allowPositionals:false}),o={},n=t;for(let[s,r]of Object.entries(He)){let g=n[s];typeof g=="string"&&g.length>0&&(o[r]=g);}return {envFile:t["env-file"],help:!!t.help,overrides:o}},"parseCliArgs");var z={version:"0.0.3"};var j=new AsyncLocalStorage;var W=i(()=>j.getStore()?.sandboxDir,"getCurrentRunSandbox");var Xe="@dudko.dev/agent",We=z.version,J,Je=i(()=>(J||(J=trace.getTracer(Xe,We)),J),"tracer"),R={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},C=i(async(e,t,o)=>Je().startActiveSpan(e,async n=>{for(let[s,r]of Object.entries(t))r!==void 0&&n.setAttribute(s,r);try{let s=await o(n);return n.end(),s}catch(s){let r=s instanceof Error?s:new Error(String(s));throw n.recordException(r),n.setStatus({code:SpanStatusCode.ERROR,message:r.message}),n.end(),s}}),"withSpan");var pt=i(e=>"command"in e&&!!e.command,"isStdioConfig"),ut=i(e=>"url"in e&&!!e.url,"isHttpConfig"),dt=z.version,pe=64,me=i(async(e,t,o,n,s,r)=>{let g=new Map,d={},c=[],p=[],a=i(async(f,h)=>{for(let T of Object.keys(d))T.startsWith(`${f}__`)&&delete d[T];for(let T=c.length-1;T>=0;T--)c[T].server===f&&c.splice(T,1);let l=await h.listTools(),m=0,E=0;for(let T of l.tools){let I=`${f}__${T.name}`;if(I.length>pe){t("warn",`[mcp] ${f}: tool "${T.name}" prefixed name (${I.length} chars) exceeds the ${pe}-char limit enforced by major LLM providers; skipping`),E++;continue}let y=T.description??"";d[I]=dynamicTool({description:y,inputSchema:jsonSchema(T.inputSchema),execute:i(async(v,k)=>C("agent.tool_call",{[R.TOOL_NAME]:I},async A=>{let P=v??{};if(r)try{let S=await r(I,P);P=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${I}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),P={_redacted:"inputSanitizer failed"};}let _;try{_=await h.callTool({name:T.name,arguments:P},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw A.setAttribute(R.TOOL_OK,false),S}let u=_.content;if(n)try{u=await n(I,u);}catch(S){return t("warn",`[mcp] ${I}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),A.setAttribute(R.TOOL_OK,false),"[output redacted: sanitizer failed]"}let w=await ft(u,{toolName:I,sandboxDir:W()});return A.setAttribute(R.TOOL_OK,true),w}),"execute")}),c.push({name:I,description:y,server:f}),m++;}E>0?t("info",`[mcp] ${f}: ${m} tools mounted, ${E} skipped (length cap)`):t("info",`[mcp] ${f}: ${m} tools mounted`);},"registerServerTools");for(let[f,h]of Object.entries(e))try{let l;if(pt(h)){let E=h.env?{...getDefaultEnvironment(),...h.env}:void 0;l=new StdioClientTransport({command:h.command,args:h.args,env:E,cwd:h.cwd});}else if(ut(h)){if(h.headers&&h.getHeaders)throw new Error(`MCP server "${f}": specify either headers or getHeaders, not both`);let E=h.getHeaders?await h.getHeaders():h.headers;l=new StreamableHTTPClientTransport(new URL(h.url),{requestInit:E?{headers:E}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${f}": config must specify either { url } (HTTP) or { command } (stdio)`);l.onerror=E=>t("warn",`[mcp] ${f}: transport error - ${E.message}`),l.onclose=()=>t("warn",`[mcp] ${f}: transport closed`);let m=new Client({name:o,version:dt});await m.connect(l),g.set(f,m),s&&m.setNotificationHandler(ToolListChangedNotificationSchema,()=>{s(f);}),await a(f,m),p.push({name:f,connected:!0});}catch(l){let m=l.message;t("error",`[mcp] ${f}: failed to connect - ${m}`),p.push({name:f,connected:false,error:m});}return {tools:d,catalog:c,results:p,close:i(async()=>{await Promise.allSettled([...g.values()].map(f=>f.close()));},"close"),refreshServer:i(async f=>{let h=g.get(f);if(!h)throw new Error(`MCP server "${f}" is not connected`);await a(f,h);},"refreshServer")}},"connectMcpServers"),ue={image:".bin",audio:".bin",resource:".bin"},mt=i((e,t)=>{if(!e)return ue[t];let o=e.indexOf("/"),s=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !s||/[^a-z0-9.+-]/.test(s)?ue[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[s]??`.${s.replace(/\+/g,"-")}`},"extFromMime"),gt=/[^a-zA-Z0-9_-]/g,de=i(async(e,t,o,n,s,r)=>{await r();let g=mt(t,o),d=n.replace(gt,"_").slice(0,32)||"tool",c=randomUUID().slice(0,8),p=Pe.join(s,`${o}-${d}-${c}${g}`),a=Buffer.from(e,"base64");return await writeFile(p,a),{type:"file",kind:o,path:p,mimeType:t,bytes:a.byteLength}},"spillBase64"),ft=i(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
29
+ `);let s=t?.sandboxDir,r=t?.toolName??"tool",g,d=i(()=>s?(g||(g=mkdir(s,{recursive:true}).then(()=>{})),g):Promise.resolve(),"ensureDir"),c=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){c.push(p.text);continue}if(s&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let a=await de(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,r,s,d);c.push(a);continue}if(s&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let a=p.resource;if(typeof a.blob=="string"){let f=await de(a.blob,typeof a.mimeType=="string"?a.mimeType:void 0,"resource",r,s,d);typeof a.uri=="string"&&(f.uri=a.uri),c.push(f);continue}if(typeof a.text=="string"){c.push(a.text);continue}}c.push(p);}return c},"flattenContent"),Z=i((e,t,o,n)=>{let s=o?.length?new Set(o):null,r=n?.length?new Set(n):null,g={},d=[];for(let c of t){if(s&&!s.has(c.name)||!s&&r?.has(c.name))continue;let p=e[c.name];p&&(g[c.name]=p,d.push(c));}return {tools:g,catalog:d}},"filterTools");var K=i((e,t,o,n)=>{let s=t?.providerType??e.providerType,r=t?.apiKey??e.apiKey,g=t?.baseURL??e.baseURL,d=t?.model??o??e.model;if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(s==="openai-compatible"&&!g)throw new Error(`${n}: provider "openai-compatible" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:s,baseURL:g,apiKey:r,model:d}},"resolveStage"),Y=i((e,t)=>{switch(t.providerType){case "openai":return createOpenAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "anthropic":return createAnthropic({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");return createOpenAICompatible({name:e,baseURL:t.baseURL,apiKey:t.apiKey})(t.model)}case "google":return createGoogleGenerativeAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model)}},"buildModelFromStage");var ee=i(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),o=e.length-t.length,n=[];o>0&&n.push(`(${o} earlier turns omitted)`);for(let s of t){let r=s.content.length>1500?`${s.content.slice(0,1500)}... [truncated]`:s.content;n.push(`${s.role}: ${r}`);}return n.join(`
30
+ `)},"renderHistory"),Et={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},fe=i((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=Et[t],s=e.slice(0,o),r=e.length-s.length,g=s.map(d=>{let c=(d.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${d.name}: ${c}`});return r>0&&g.push(`... and ${r} more tools`),g.join(`
31
+ `)},"renderToolCatalog"),Q=1500,St=i(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>Q?`${t.slice(0,Q)}... [truncated, ${t.length-Q} chars]`:t},"truncateOutput"),bt=i((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${St(n.output)}`).join(`
20
32
  `):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
21
- `)},"renderTraceEntry"),L=s(e=>e.length===0?"(no steps executed yet)":e.map(Oe).join(`
22
- `),"renderTrace"),_=s(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
33
+ `)},"renderTraceEntry"),te=i(e=>e.length===0?"(no steps executed yet)":e.map(bt).join(`
34
+ `),"renderTrace"),oe=i(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
23
35
  expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
24
36
  suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
25
- `),"renderPlan"),F=`You are the Planner of a multi-step agent system.
37
+ `),"renderPlan"),L=i((e,t)=>t?`${e}
38
+
39
+ Domain context:
40
+ ${t}`:e,"withDomainContext"),ge=`You are the Planner of a multi-step agent system.
26
41
 
27
42
  Your only job is to decompose the user's request into a short ordered list of concrete actionable steps that a tool-using Executor can perform one at a time.
28
43
 
@@ -32,28 +47,28 @@ Rules:
32
47
  3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
33
48
  4. If the request asks for information that is likely retrievable via the available tools, plan to use them. If no tool fits, plan to answer from general knowledge.
34
49
  5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
35
- 6. Output strict JSON matching the requested schema. No prose outside JSON.`,Me=`
50
+ 6. Output strict JSON matching the requested schema. No prose outside JSON.`,It=`
36
51
 
37
52
  ADDITIONAL RULE (tool-narrowed mode):
38
- The agent narrows the active tool set per-step using suggestedTools. You MUST set suggestedTools to the EXACT tool names the executor will use for that step. If a step is reasoning-only and needs no tools, leave suggestedTools empty. Missing or wrong suggestedTools will leave the executor without the tools it needs.`,U=s(e=>e==="compact"?F+Me:F,"buildPlannerSystem"),W=s((e,t,o,n="full")=>[o?.length?`Conversation history:
39
- ${N(o)}
53
+ The agent narrows the active tool set per-step using suggestedTools. You MUST set suggestedTools to the EXACT tool names the executor will use for that step. If a step is reasoning-only and needs no tools, leave suggestedTools empty. Missing or wrong suggestedTools will leave the executor without the tools it needs.`,he=i(e=>e==="compact"?ge+It:ge,"buildPlannerSystem"),ye=i((e,t,o,n="full")=>[o?.length?`Conversation history:
54
+ ${ee(o)}
40
55
  `:"",`User request:
41
56
  ${e}`,"",`Available tools:
42
- ${V(t,n)}`,"","Produce the plan now."].filter(Boolean).join(`
43
- `),"buildPlannerUserPrompt"),j=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
57
+ ${fe(t,n)}`,"","Produce the plan now."].filter(Boolean).join(`
58
+ `),"buildPlannerUserPrompt"),Te=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
44
59
 
45
60
  Rules:
46
61
  1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
47
62
  2. Use the available tools when they help. Call them with valid arguments. Read prior step results in the trace before re-fetching the same data.
48
63
  3. When the step is complete, write a short concrete "step result" describing what you found / did. Include identifiers, names, or key data the next step might need.
49
64
  4. If the step is impossible with the available tools, or if you are otherwise blocked, explain the blocker briefly and end your reply with the literal token [BLOCKER] on its own line. The system uses this token (language-independent) to invoke the Replanner. Do not fabricate data.
50
- 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,J=s((e,t,o,n,l)=>[l?.length?`Conversation history:
51
- ${N(l)}
65
+ 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,we=i((e,t,o,n,s)=>[s?.length?`Conversation history:
66
+ ${ee(s)}
52
67
  `:"",`Original user request:
53
68
  ${e}`,"",`Overall plan:
54
- ${_(t)}`,"",`Trace so far:
55
- ${L(n)}`,"",`CURRENT STEP to execute (id=${o.id}): ${o.description}`,`Expected outcome: ${o.expectedOutcome}`,o.suggestedTools?.length?`Suggested tools: ${o.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
56
- `),"buildExecutorUserPrompt"),X=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
69
+ ${oe(t)}`,"",`Trace so far:
70
+ ${te(n)}`,"",`CURRENT STEP to execute (id=${o.id}): ${o.description}`,`Expected outcome: ${o.expectedOutcome}`,o.suggestedTools?.length?`Suggested tools: ${o.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
71
+ `),"buildExecutorUserPrompt"),Ee=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
57
72
 
58
73
  You have three options:
59
74
  - "continue": the next planned step is still appropriate.
@@ -64,44 +79,39 @@ Rules:
64
79
  1. Prefer "continue" when the original plan still applies. Revise only when needed.
65
80
  2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
66
81
  3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
67
- 4. Output strict JSON matching the schema. No prose outside JSON.`,Z=s((e,t,o,n,l,a="full")=>[`Original user request:
82
+ 4. Output strict JSON matching the schema. No prose outside JSON.`,Se=i((e,t,o,n,s,r="full")=>[`Original user request:
68
83
  ${e}`,"",`Current plan:
69
- ${_(t)}`,"",`Completed steps:
70
- ${L(o)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
71
- ${V(l,a)}`,"","Decide now: continue, revise, or finish."].join(`
72
- `),"buildReplannerUserPrompt"),Q=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
84
+ ${oe(t)}`,"",`Completed steps:
85
+ ${te(o)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
86
+ ${fe(s,r)}`,"","Decide now: continue, revise, or finish."].join(`
87
+ `),"buildReplannerUserPrompt"),be=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
73
88
 
74
89
  Rules:
75
90
  1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
76
91
  2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
77
92
  3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
78
- 4. Use the user's language.`,ee=s((e,t,o,n)=>[n?.length?`Conversation history:
79
- ${N(n)}
93
+ 4. Use the user's language.`,Ie=i((e,t,o,n)=>[n?.length?`Conversation history:
94
+ ${ee(n)}
80
95
  `:"",`User request:
81
96
  ${e}`,"",`Plan that was executed:
82
- ${_(t)}`,"",`Execution trace:
83
- ${L(o)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
84
- `),"buildSynthesizerUserPrompt");var te=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 n=o.statusCode??o.status;return typeof n=="number"?n===429||n>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?te(o.cause,t):false},"isRetriable"),E=s(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let l=0;l<=t.maxRetries;l++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(a){if(n=a,l===t.maxRetries||!te(a))throw a;t.onRetry?.(l+1,a);let c=o*2**l+Math.random()*250;await Ne(c,t.signal);}}throw n},"withRetry"),Ne=s((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let l=setTimeout(()=>{t?.removeEventListener("abort",a),o();},e),a=s(()=>{clearTimeout(l),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",a,{once:true});}),"sleep"),Le=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),R=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Le([e,AbortSignal.timeout(t)]),"withTimeout");var je=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 n={};for(let l of o){let a=e.tools[l];a&&(n[l]=a);}return n},"buildActiveToolSet"),oe="[BLOCKER]",De=s(e=>{let t=e.indexOf(oe);return t===-1?{summary:e,blocked:false}:{summary:(e.slice(0,t)+e.slice(t+oe.length)).trim(),blocked:true}},"splitBlockerSentinel"),D=4e3,Ge=s(e=>e.length>D?`${e.slice(0,D)}... [truncated, ${e.length-D} chars]`:e,"truncateForTrace"),ne=s(async(e,t,o,n,l,a,c)=>{let p=Date.now(),i=await E(()=>Ye(e,t,o,n,l,a,c),{maxRetries:a.config.llmMaxRetries??2,signal:c,onRetry:s((u,f)=>a.emit({type:"retry",phase:"execute",attempt:u,error:f.message}),"onRetry")});return a.emit({type:"usage",phase:"execute",usage:i.usage}),{step:o,summary:i.summary,toolCalls:i.toolCalls,durationMs:Date.now()-p,blocked:i.blocked}},"executeStep"),Ye=s(async(e,t,o,n,l,a,c)=>{let p=[],i=new Map,u=je(a,o),f=a.config.toolSelectionStrategy==="plan-narrowed",r=streamText({model:a.executorModel,tools:u,...f?{activeTools:Object.keys(u)}:{},stopWhen:stepCountIs(a.config.maxStepsPerTask),system:a.config.systemPrompt?`${j}
85
-
86
- Domain context:
87
- ${a.config.systemPrompt}`:j,prompt:J(e,t,o,n,l),abortSignal:R(c,a.config.llmTimeoutMs??0)});for await(let m of r.fullStream)switch(m.type){case "text-delta":m.text&&a.emit({type:"step.text-delta",step:o,delta:m.text});break;case "tool-call":{i.set(m.toolCallId,{name:m.toolName,input:m.input}),a.emit({type:"step.tool-call",step:o,name:m.toolName,input:m.input});break}case "tool-result":{let y=i.get(m.toolCallId);p.push({name:m.toolName,input:y?.input??m.input,output:m.output,ok:true}),a.emit({type:"step.tool-result",step:o,name:m.toolName,output:m.output,ok:true}),i.delete(m.toolCallId);break}case "tool-error":{let y=i.get(m.toolCallId);p.push({name:m.toolName,input:y?.input??m.input,output:m.error,ok:false}),a.emit({type:"step.tool-result",step:o,name:m.toolName,output:m.error,ok:false}),i.delete(m.toolCallId);break}case "error":{let y=m.error;throw y instanceof Error?y:new Error(String(y))}}let[d,T]=await Promise.all([r.text,r.usage]),{summary:w,blocked:g}=De(d.trim());return {summary:w.length>0?Ge(w):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:T.inputTokens??0,outputTokens:T.outputTokens??0,totalTokens:T.totalTokens??0}}},"runOnce");var qe=z.object({id:z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z.string().min(1).describe("Concrete action to perform"),expectedOutcome:z.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z.array(z.string()).optional().describe("Tool names from the available list, if any")}),G=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(qe).min(1).max(8)}),re=s(async(e,t,o,n)=>{let l=new Set(o.toolCatalog.map(i=>i.name)),a=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:p}=await E(()=>He(e,t,a,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((i,u)=>o.emit({type:"retry",phase:"plan",attempt:i,error:u.message}),"onRetry")});return o.emit({type:"usage",phase:"plan",usage:p}),{thought:c.thought,steps:c.steps.map(i=>{if(!i.suggestedTools?.length)return i;let u=i.suggestedTools.filter(r=>l.has(r)),f=i.suggestedTools.length-u.length;return f>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${i.id}" had ${f} unknown suggestedTools, stripped`}),u.length===0?(o.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:u}})}},"createInitialPlan"),He=s(async(e,t,o,n,l)=>{let a=streamObject({model:n.plannerModel,schema:G,system:n.config.systemPrompt?`${U(o)}
88
-
89
- Domain context:
90
- ${n.config.systemPrompt}`:U(o),prompt:W(e,n.toolCatalog,t,o),abortSignal:R(l,n.config.llmTimeoutMs??0)}),c="",p=false;for await(let f of a.partialObjectStream){let r=f?.thought;typeof r!="string"||r===c||(r.startsWith(c)?n.emit({type:"plan.thought-delta",delta:r.slice(c.length)}):p||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),p=true),c=r);}let[i,u]=await Promise.all([a.object,a.usage]);return {object:i,usage:{inputTokens:u.inputTokens??0,outputTokens:u.outputTokens??0,totalTokens:u.totalTokens??0}}},"streamPlanOnce");var Ke=z.discriminatedUnion("mode",[z.object({mode:z.literal("continue"),reason:z.string().min(1).describe("Why the next step is still appropriate")}),z.object({mode:z.literal("finish"),reason:z.string().min(1).describe("Why no more steps are needed")}),z.object({mode:z.literal("revise"),reason:z.string().min(1).describe("Why the plan must change"),newPlan:G.describe("Plan covering ONLY the remaining work")})]),se=s(async(e,t,o,n,l,a)=>{let c=l.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:p,usage:i}=await E(async()=>{let u=await generateObject({model:l.plannerModel,schema:Ke,system:X,prompt:Z(e,t,o,n,l.toolCatalog,c),abortSignal:R(a,l.config.llmTimeoutMs??0)}),f={inputTokens:u.usage.inputTokens??0,outputTokens:u.usage.outputTokens??0,totalTokens:u.usage.totalTokens??0};return {object:u.object,usage:f}},{maxRetries:l.config.llmMaxRetries??2,signal:a,onRetry:s((u,f)=>l.emit({type:"retry",phase:"replan",attempt:u,error:f.message}),"onRetry")});return l.emit({type:"usage",phase:"replan",usage:i}),p},"decideNextAction");var ae=s(async(e,t,o,n,l,a)=>{let{text:c,usage:p}=await E(()=>Ve(e,t,o,n,l,a),{maxRetries:l.config.llmMaxRetries??2,signal:a,onRetry:s((i,u)=>l.emit({type:"retry",phase:"synthesize",attempt:i,error:u.message}),"onRetry")});return l.emit({type:"usage",phase:"synthesize",usage:p}),c},"synthesizeAnswer"),Ve=s(async(e,t,o,n,l,a)=>{let c=streamText({model:l.synthesizerModel,system:Q,prompt:ee(e,t,o,n),abortSignal:R(a,l.config.llmTimeoutMs??0)});for await(let u of c.fullStream)if(u.type==="text-delta")u.text&&l.emit({type:"final.text-delta",delta:u.text});else if(u.type==="error"){let f=u.error;throw f instanceof Error?f:new Error(String(f))}let[p,i]=await Promise.all([c.text,c.usage]);return {text:p,usage:{inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,totalTokens:i.totalTokens??0}}},"streamOnce");var Je=s(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),Xe=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),ie=s(async(e,t)=>{let o=randomUUID();return O.run({runId:o,startedAt:Date.now()},()=>Ze(e,t))},"runAgentLoop"),Ze=s(async(e,t)=>{let{input:o,signal:n}=t,l=t.history?[...t.history]:void 0,a=t.onEvent??(()=>{}),c={inputTokens:0,outputTokens:0,totalTokens:0},p={...e,emit:s(m=>{m.type==="usage"&&(c.inputTokens+=m.usage.inputTokens,c.outputTokens+=m.usage.outputTokens,c.totalTokens+=m.usage.totalTokens);let y={...m,runId:O.getStore()?.runId};try{a(y);}catch{}try{e.emit(y);}catch{}},"emit")},i;try{i=await re(o,l,p,n);}catch(m){if(p.emit({type:"error",error:x(m),phase:"plan"}),Xe(m)||n?.aborted)throw m;i={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."}]};}p.emit({type:"plan.created",plan:i});let u=[],f=i,r=0,d=0,T=0,w=e.config.maxRevisions??2,g=e.config.maxTotalTokens;for(;d<e.config.maxIterations;){if(d++,n?.aborted)throw new DOMException("Aborted","AbortError");if(r>=f.steps.length)break;if(g&&c.totalTokens>=g){p.emit({type:"budget.exceeded",tokens:c.totalTokens,cap:g});break}let m=f.steps[r];p.emit({type:"step.start",step:m,index:r});let y;try{y=await ne(o,f,m,u,l,p,n);}catch(v){throw p.emit({type:"error",error:x(v),phase:"execute"}),v}u.push(y),p.emit({type:"step.complete",step:m,result:y});let A=f.steps[r+1]??null;if(A===null){p.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!Je(y)){p.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),r++;continue}let I;try{I=await se(o,f,u,A,p,n);}catch(v){throw p.emit({type:"error",error:x(v),phase:"replan"}),v}if(p.emit({type:"replan.decision",mode:I.mode,reason:I.reason,cause:"llm-decision"}),I.mode==="finish")break;if(I.mode==="revise"){if(T>=w){p.emit({type:"revisions.exceeded",cap:w});break}T++,f=I.newPlan,p.emit({type:"plan.revised",plan:f,reason:I.reason}),r=0;continue}r++;}let h;try{h=await ae(o,f,u,l,p,n);}catch(m){throw p.emit({type:"error",error:x(m),phase:"synthesize"}),m}return p.emit({type:"final",text:h}),{text:h,plan:f,trace:u,iterations:d,usage:c}},"runAgentLoopInner"),x=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var k={none:0,error:1,warn:2,info:3,debug:4},le=s(async(e,t)=>{let o=k[e.logLevel]>=k.debug,n=s(g=>{if(t)try{t(g);}catch(h){o&&console.error("[agent] event handler threw:",h);}},"emit"),l=s((g,h)=>{k[e.logLevel]>=k[g]&&n({type:"log",level:g,message:h});},"log"),a=s(async()=>{let g=await B(e.mcpServers,l,e.clientName,e.outputSanitizer),h=K(g.tools,g.catalog,e.availableTools,e.excludedTools);return {connection:g,tools:h.tools,catalog:h.catalog}},"connect"),c;try{c=await a();}catch(g){throw n({type:"error",error:g instanceof Error?g:new Error(String(g)),phase:"init"}),g}let p=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&p>0&&!c.connection.results.some(h=>h.connected)){let h=c.connection.results.filter(y=>!y.connected).map(y=>`${y.name}: ${y.error??"unknown"}`).join("; ");await c.connection.close().catch(()=>{});let m=new Error(`All ${p} configured MCP server(s) failed to connect [${h}]`);throw n({type:"error",error:m,phase:"init"}),m}let i=C(e,e.model),u=C(e,e.plannerModel??e.model),f=C(e,e.synthesizerModel??e.model),r={config:e,executorModel:i,plannerModel:u,synthesizerModel:f,tools:c.tools,toolCatalog:c.catalog.map(g=>({name:g.name,description:g.description})),emit:n},d=0,T=false,w=false;return {run:s(async g=>{if(T)throw new Error("Agent is closed");if(w)throw new Error("Agent is reconnecting; retry shortly");d++;try{return await ie(r,g)}finally{d--;}},"run"),listTools:s(()=>r.toolCatalog.slice(),"listTools"),reconnect:s(async()=>{if(T)throw new Error("Agent is closed");if(w)throw new Error("Already reconnecting");if(d>0)throw new Error(`Cannot reconnect with ${d} active run(s)`);w=true;try{let g=c.connection,h=await a();for(let m of Object.keys(r.tools))delete r.tools[m];Object.assign(r.tools,h.tools),r.toolCatalog=h.catalog.map(m=>({name:m.name,description:m.description})),c=h,await g.close().catch(()=>{});}finally{w=false;}},"reconnect"),close:s(async g=>{T=true;let h=g?.waitForRuns??false,m=g?.timeoutMs??3e4;if(h&&d>0){let y=Date.now();for(;d>0&&Date.now()-y<m;)await new Promise(A=>setTimeout(A,50));}d>0&&n({type:"log",level:"warn",message:`[agent] close called with ${d} active run(s); they will fail mid-flight`}),await c.connection.close().catch(()=>{});},"close"),activeRuns:s(()=>d,"activeRuns")}},"createAgent");var ce=["openai","anthropic","openai-compatible","google"],pe=["none","error","warn","info","debug"],ue=["all","plan-narrowed"],ge=s(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!ce.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${ce.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!pe.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${pe.join(" | ")}, got: ${t}`);let o=e==="openai-compatible"?Y("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:Y("AGENT_API_KEY"),model:Y("AGENT_MODEL"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:et(process.env.MCP_SERVERS),availableTools:me(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:me(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:de(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:de(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:$(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:$(process.env.AGENT_MAX_TOTAL_TOKENS),llmTimeoutMs:$(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:$(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:Qe(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),Qe=s(e=>{let t=e?.trim();if(t){if(!ue.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${ue.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),$=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"),Y=s(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),me=s(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),de=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"),et=s(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? }>");let o={};for(let[n,l]of Object.entries(t)){if(!l||typeof l!="object")throw new Error(`MCP_SERVERS.${n} must be an object`);let a=l;if(typeof a.url!="string"||!a.url)throw new Error(`MCP_SERVERS.${n}.url must be a non-empty string`);let c=a.headers&&typeof a.headers=="object"&&!Array.isArray(a.headers)?a.headers:void 0;o[n]={url:a.url,headers:c};}return o},"parseMcpServers");var rt=16,P=s((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),fe=s(e=>{try{return P(JSON.stringify(e))}catch{return String(e)}},"formatJson"),he=s(async()=>{let e=ge(),t=Object.keys(e.mcpServers);console.log(`[session] model=${e.model} planner=${e.plannerModel??e.model} synth=${e.synthesizerModel??e.model} 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
91
- `);let o=false,n=false,a=await le(e,s(r=>{switch(r.type){case "log":console.log(`[${r.level}] ${r.message}`);break;case "plan.thought-delta":n||(process.stdout.write(`
92
- [plan] `),n=true),process.stdout.write(r.delta);break;case "plan.created":n?(process.stdout.write(`
93
- `),n=false):console.log(`
94
- [plan] ${r.plan.thought}`);for(let[d,T]of r.plan.steps.entries()){let w=T.suggestedTools?.length?` (tools: ${T.suggestedTools.join(", ")})`:"";console.log(` ${d+1}. ${T.description}${w}`);}break;case "plan.revised":console.log(`
95
- [replan] reason=${r.reason}`);for(let[d,T]of r.plan.steps.entries())console.log(` ${d+1}. ${T.description}`);break;case "step.start":console.log(`
96
- [step ${r.index+1}] ${r.step.description}`);break;case "step.tool-call":console.log(` -> ${r.name} ${fe(r.input)}`);break;case "step.tool-result":{let d=r.ok?"ok":"fail";console.log(` <- ${r.name} ${d} ${fe(r.output)}`);break}case "step.complete":console.log(` = ${P(r.result.summary,400)} (${r.result.durationMs}ms, ${r.result.toolCalls.length} tool calls)`);break;case "replan.decision":r.mode!=="continue"&&console.log(`[replan] ${r.mode} (${r.cause}): ${r.reason}`);break;case "usage":break;case "retry":r.phase==="plan"&&n&&(process.stdout.write(`
97
- `),n=false),console.log(`[retry] ${r.phase} attempt=${r.attempt}: ${r.error}`);break;case "budget.exceeded":console.log(`[budget] token cap reached: ${r.tokens}/${r.cap} - finishing early`);break;case "revisions.exceeded":console.log(`[budget] max ${r.cap} replan-revisions reached - finishing early`);break;case "final.text-delta":o||(process.stdout.write(`
98
- assistant> `),o=true),process.stdout.write(r.delta);break;case "final":o?(process.stdout.write(`
97
+ ${oe(t)}`,"",`Execution trace:
98
+ ${te(o)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
99
+ `),"buildSynthesizerUserPrompt");var Re=i((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let o=e;if(o.name==="AbortError")return false;let n=o.statusCode??o.status;return typeof n=="number"?n===429||n>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?Re(o.cause,t):false},"isRetriable"),M=i(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(r){if(n=r,s===t.maxRetries||!Re(r))throw r;t.onRetry?.(s+1,r);let g=o*2**s+Math.random()*250;await Rt(g,t.signal);}}throw n},"withRetry"),Rt=i((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",r),o();},e),r=i(()=>{clearTimeout(s),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",r,{once:true});}),"sleep"),ne=i(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),U=i((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:ne([e,AbortSignal.timeout(t)]),"withTimeout");var kt=i((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let o=new Set(t.suggestedTools??[]);if(o.size===0)return t.requiresTools?e.tools:{};let n={};for(let s of o){let r=e.tools[s];r&&(n[s]=r);}return n},"buildActiveToolSet"),ve="[BLOCKER]",xt=i(e=>e.includes(ve)?{summary:e.split(ve).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),re=4e3,Ct=i(e=>e.length>re?`${e.slice(0,re)}... [truncated, ${e.length-re} chars]`:e,"truncateForTrace"),Ae=i(async(e,t,o,n,s,r,g)=>C("agent.execute_step",{[R.PHASE]:"execute",[R.STEP_ID]:o.id},async d=>{let c=Date.now(),p=await M(()=>Pt(e,t,o,n,s,r,g),{maxRetries:r.config.llmMaxRetries??2,signal:g,onRetry:i((a,f)=>r.emit({type:"retry",phase:"execute",attempt:a,error:f.message}),"onRetry")});return r.emit({type:"usage",phase:"execute",usage:p.usage}),d.setAttribute(R.USAGE_TOTAL_TOKENS,p.usage.totalTokens),d.setAttribute(R.STEP_BLOCKED,p.blocked),d.setAttribute(R.TOOL_COUNT,p.toolCalls.length),{step:o,summary:p.summary,toolCalls:p.toolCalls,durationMs:Date.now()-c,blocked:p.blocked}}),"executeStep"),Pt=i(async(e,t,o,n,s,r,g)=>{let d=[],c=new Map,p=kt(r,o),a=r.config.toolSelectionStrategy==="plan-narrowed",f=i(async(y,v)=>{let k=r.config.inputSanitizer;if(!k)return v;try{return await k(y,v)}catch(A){return r.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${y} - ${A.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),h=streamText({model:r.executorModel,tools:p,...a?{activeTools:Object.keys(p)}:{},stopWhen:stepCountIs(r.config.maxStepsPerTask),system:L(Te,r.config.systemPrompt),prompt:we(e,t,o,n,s),abortSignal:U(g,r.config.llmTimeoutMs??0)});for await(let y of h.fullStream)switch(y.type){case "text-delta":y.text&&r.emit({type:"step.text-delta",step:o,delta:y.text});break;case "tool-call":{let v=await f(y.toolName,y.input);c.set(y.toolCallId,{name:y.toolName,input:v}),r.emit({type:"step.tool-call",step:o,name:y.toolName,input:v});break}case "tool-result":{let k=c.get(y.toolCallId)?.input??await f(y.toolName,y.input);d.push({name:y.toolName,input:k,output:y.output,ok:true}),r.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.output,ok:true}),c.delete(y.toolCallId);break}case "tool-error":{let k=c.get(y.toolCallId)?.input??await f(y.toolName,y.input);d.push({name:y.toolName,input:k,output:y.error,ok:false}),r.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.error,ok:false}),c.delete(y.toolCallId);break}case "error":{let v=y.error;throw v instanceof Error?v:new Error(String(v))}}let[l,m]=await Promise.all([h.text,h.usage]),{summary:E,blocked:T}=xt(l.trim());return {summary:E.length>0?Ct(E):d.length>0?`Executed ${d.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:d,blocked:T,usage:{inputTokens:m.inputTokens??0,outputTokens:m.outputTokens??0,totalTokens:m.totalTokens??0}}},"runOnce");var Ot=z$1.object({id:z$1.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z$1.string().min(1).describe("Concrete action to perform"),expectedOutcome:z$1.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z$1.array(z$1.string()).optional().describe("Tool names from the available list, if any")}),se=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array(Ot).min(1).max(8)}),ke=i(async(e,t,o,n)=>C("agent.plan",{[R.PHASE]:"plan"},async s=>{let r=new Set(o.toolCatalog.map(p=>p.name)),g=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:d,usage:c}=await M(()=>$t(e,t,g,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:i((p,a)=>o.emit({type:"retry",phase:"plan",attempt:p,error:a.message}),"onRetry")});return o.emit({type:"usage",phase:"plan",usage:c}),s.setAttribute(R.USAGE_TOTAL_TOKENS,c.totalTokens),{thought:d.thought,steps:d.steps.map(p=>{if(!p.suggestedTools?.length)return p;let a=p.suggestedTools.filter(h=>r.has(h)),f=p.suggestedTools.length-a.length;return f>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${p.id}" had ${f} unknown suggestedTools, stripped`}),a.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${p.id}" had no valid suggestedTools left; falling back to full toolset`}),{...p,suggestedTools:void 0,requiresTools:true}):{...p,suggestedTools:a}})}}),"createInitialPlan"),$t=i(async(e,t,o,n,s)=>{let r=streamObject({model:n.plannerModel,schema:se,system:L(he(o),n.config.systemPrompt),prompt:ye(e,n.toolCatalog,t,o),abortSignal:U(s,n.config.llmTimeoutMs??0)}),g="",d=false,c=0;for await(let f of r.partialObjectStream){let h=f?.thought;typeof h=="string"&&h!==g&&(h.startsWith(g)?n.emit({type:"plan.thought-delta",delta:h.slice(g.length)}):d||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),d=true),g=h);let l=f?.steps;if(Array.isArray(l)&&l.length>c)for(;c<l.length;){let m=l[c];if(!m||typeof m.description!="string"||!m.description.length)break;let E={id:typeof m.id=="string"&&m.id?m.id:`s${c+1}`,description:m.description,expectedOutcome:typeof m.expectedOutcome=="string"?m.expectedOutcome:"",suggestedTools:Array.isArray(m.suggestedTools)?m.suggestedTools.filter(T=>typeof T=="string"):void 0};n.emit({type:"plan.step-added",step:E,index:c}),c++;}}let[p,a]=await Promise.all([r.object,r.usage]);return {object:p,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamPlanOnce");var Lt=z$1.discriminatedUnion("mode",[z$1.object({mode:z$1.literal("continue"),reason:z$1.string().min(1).describe("Why the next step is still appropriate")}),z$1.object({mode:z$1.literal("finish"),reason:z$1.string().min(1).describe("Why no more steps are needed")}),z$1.object({mode:z$1.literal("revise"),reason:z$1.string().min(1).describe("Why the plan must change"),newPlan:se.describe("Plan covering ONLY the remaining work")})]),xe=i(async(e,t,o,n,s,r)=>C("agent.replan",{[R.PHASE]:"replan"},async g=>{let d=s.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:p}=await M(async()=>{let a=await generateObject({model:s.plannerModel,schema:Lt,system:L(Ee,s.config.systemPrompt),prompt:Se(e,t,o,n,s.toolCatalog,d),abortSignal:U(r,s.config.llmTimeoutMs??0)}),f={inputTokens:a.usage.inputTokens??0,outputTokens:a.usage.outputTokens??0,totalTokens:a.usage.totalTokens??0};return {object:a.object,usage:f}},{maxRetries:s.config.llmMaxRetries??2,signal:r,onRetry:i((a,f)=>s.emit({type:"retry",phase:"replan",attempt:a,error:f.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:p}),g.setAttribute(R.REPLAN_MODE,c.mode),g.setAttribute(R.USAGE_TOTAL_TOKENS,p.totalTokens),c}),"decideNextAction");var Ce=i(async(e,t,o,n,s,r)=>C("agent.synthesize",{[R.PHASE]:"synthesize"},async g=>{let{text:d,usage:c}=await M(()=>Ut(e,t,o,n,s,r),{maxRetries:s.config.llmMaxRetries??2,signal:r,onRetry:i((p,a)=>s.emit({type:"retry",phase:"synthesize",attempt:p,error:a.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:c}),g.setAttribute(R.USAGE_TOTAL_TOKENS,c.totalTokens),d}),"synthesizeAnswer"),Ut=i(async(e,t,o,n,s,r)=>{let g=streamText({model:s.synthesizerModel,system:L(be,s.config.systemPrompt),prompt:Ie(e,t,o,n),abortSignal:U(r,s.config.llmTimeoutMs??0)});for await(let p of g.fullStream)if(p.type==="text-delta")p.text&&s.emit({type:"final.text-delta",delta:p.text});else if(p.type==="error"){let a=p.error;throw a instanceof Error?a:new Error(String(a))}let[d,c]=await Promise.all([g.text,g.usage]);return {text:d,usage:{inputTokens:c.inputTokens??0,outputTokens:c.outputTokens??0,totalTokens:c.totalTokens??0}}},"streamOnce");var zt=i(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),H=i(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Kt=i((e,t)=>{let o=e.config.sandboxRoot?.trim()||Pe.join(tmpdir(),"agent-sandbox");return Pe.join(o,t)},"resolveSandboxDir"),_e=/^[a-zA-Z0-9_-]{1,128}$/,ie=i((e,t)=>{if(!_e.test(e))throw new Error(`Unsafe runId from ${t}: must match ${_e}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Yt=i(async(e,t)=>{if(!t.resumeFromRunId)return;if(ie(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await e.config.persistence.loadRun(t.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(ie(o.runId,"snapshot.runId"),o.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Oe=i(async(e,t)=>{let o=await Yt(e,t),n=o?.runId??randomUUID();ie(n,"runId");let s=o?.startedAt??Date.now(),r=Kt(e,n);return j.run({runId:n,startedAt:s,sandboxDir:r},async()=>C("agent.run",{[R.RUN_ID]:n,[R.PROVIDER]:e.config.providerType,[R.MODEL]:e.config.model},async g=>{try{let d=await Ht(e,t,o);return g.setAttribute(R.ITERATIONS,d.iterations),g.setAttribute(R.USAGE_TOTAL_TOKENS,d.usage.totalTokens),g.setAttribute(R.USAGE_INPUT_TOKENS,d.usage.inputTokens),g.setAttribute(R.USAGE_OUTPUT_TOKENS,d.usage.outputTokens),d}finally{e.config.keepSandbox||await rm(r,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Ht=i(async(e,t,o)=>{let{signal:n}=t,s=o?.input??t.input,r=o?.history?[...o.history]:t.history?[...t.history]:void 0,g=t.onEvent??(()=>{}),d=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},c=j.getStore()?.startedAt??Date.now(),p=j.getStore()?.runId??"<unknown>",a={...e,emit:i(u=>{u.type==="usage"&&(d.inputTokens+=u.usage.inputTokens,d.outputTokens+=u.usage.outputTokens,d.totalTokens+=u.usage.totalTokens);let w={...u,runId:j.getStore()?.runId};try{g(w);}catch{}try{e.emit(w);}catch{}},"emit")},f=e.config.persistence,h=i(async(u,w)=>{let S=f?.[u];if(S)try{await S(w);}catch(b){a.emit({type:"log",level:"warn",message:`[persistence] ${u} threw: ${b.message}`});}},"callPersistence"),l;if(o)l=o.plan,a.emit({type:"log",level:"info",message:`[resume] continuing run ${p} from step ${o.stepIndex}/${l.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),a.emit({type:"plan.created",plan:l});else {try{l=await ke(s,r,a,n);}catch(u){if(a.emit({type:"error",error:G(u),phase:"plan"}),H(u)||n?.aborted)throw await h("onRunComplete",{runId:p,startedAt:c,status:"cancelled",input:s,history:r,trace:[],usage:d,stepIndex:0,iterations:0,revisions:0,error:u.message,completedAt:Date.now()}),u;l={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}a.emit({type:"plan.created",plan:l});}let m=o?[...o.trace]:[],E=l,T=o?.stepIndex??0,I=o?.iterations??0,y=o?.revisions??0,v=e.config.maxRevisions??2,k=e.config.maxTotalTokens,A=i((u,w={})=>({runId:p,startedAt:c,status:u,input:s,history:r,plan:E,trace:m,usage:d,stepIndex:T,iterations:I,revisions:y,...w}),"buildSnapshot");o||await h("onRunStart",A("executing"));let P=i(async()=>{await h("onStepComplete",A("executing"));},"persistCheckpoint");for(;I<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(T>=E.steps.length)break;if(k&&d.totalTokens>=k){a.emit({type:"budget.exceeded",tokens:d.totalTokens,cap:k});break}I++;let u=E.steps[T];a.emit({type:"step.start",step:u,index:T});let w=new AbortController;if(t.onStepStart)try{t.onStepStart({step:u,index:T,abort:i(()=>w.abort(),"abort")});}catch(x){a.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${x.message}`});}let S=ne([n,w.signal]),b;try{b=await Ae(s,E,u,m,r,a,S);}catch(x){if(n?.aborted)throw a.emit({type:"error",error:G(x),phase:"execute"}),await h("onRunComplete",A("cancelled",{error:x.message,completedAt:Date.now()})),x;if(w.signal.aborted&&H(x))a.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),b={step:u,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw a.emit({type:"error",error:G(x),phase:"execute"}),await h("onRunComplete",A("failed",{error:x.message,completedAt:Date.now()})),x}m.push(b),a.emit({type:"step.complete",step:u,result:b});let O=E.steps[T+1]??null;if(O===null){a.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!zt(b)){a.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),T++,await P();continue}let D;try{D=await xe(s,E,m,O,a,n);}catch(x){throw a.emit({type:"error",error:G(x),phase:"replan"}),await h("onRunComplete",A(H(x)||n?.aborted?"cancelled":"failed",{error:x.message,completedAt:Date.now()})),x}if(a.emit({type:"replan.decision",mode:D.mode,reason:D.reason,cause:"llm-decision"}),D.mode==="finish")break;if(D.mode==="revise"){if(y>=v){a.emit({type:"revisions.exceeded",cap:v});break}y++,E=D.newPlan,a.emit({type:"plan.revised",plan:E,reason:D.reason}),T=0,await P();continue}T++,await P();}let _;try{_=await Ce(s,E,m,r,a,n);}catch(u){throw a.emit({type:"error",error:G(u),phase:"synthesize"}),await h("onRunComplete",A(H(u)||n?.aborted?"cancelled":"failed",{error:u.message,completedAt:Date.now()})),u}return a.emit({type:"final",text:_}),await h("onRunComplete",A("complete",{text:_,completedAt:Date.now()})),{text:_,plan:E,trace:m,iterations:I,usage:d}},"runAgentLoopInner"),G=i(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var F={none:0,error:1,warn:2,info:3,debug:4},$e=i(async(e,t)=>{let o=F[e.logLevel]>=F.debug,n=i(u=>{if(t)try{t(u);}catch(w){o&&console.error("[agent] event handler threw:",w);}},"emit"),s=i((u,w)=>{F[e.logLevel]>=F[u]&&n({type:"log",level:u,message:w});},"log"),r,g=i((u,w)=>{if(!e.tools)return u;let S=[];for(let[b,O]of Object.entries(e.tools)){if(u.tools[b]&&w(b),e.availableTools?.length&&!e.availableTools.includes(b)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(b))continue;u.tools[b]=O;let X=typeof O=="object"&&O&&"description"in O?O.description:"";S.push({name:b,description:typeof X=="string"?X:"",server:"<native>"});}return {tools:u.tools,catalog:[...u.catalog,...S]}},"mergeNativeTools"),d=i(async()=>{let u=await me(e.mcpServers,s,e.clientName,e.outputSanitizer,b=>r?.(b),e.inputSanitizer),w=Z(u.tools,u.catalog,e.availableTools,e.excludedTools),S=g(w,b=>{throw u.close().catch(()=>{}),new Error(`Native tool "${b}" collides with an MCP-registered tool of the same name`)});return {connection:u,tools:S.tools,catalog:S.catalog}},"connect"),c;try{c=await d();}catch(u){throw n({type:"error",error:u instanceof Error?u:new Error(String(u)),phase:"init"}),u}let p=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&p>0&&!c.connection.results.some(w=>w.connected)){let w=c.connection.results.filter(b=>!b.connected).map(b=>`${b.name}: ${b.error??"unknown"}`).join("; ");await c.connection.close().catch(()=>{});let S=new Error(`All ${p} configured MCP server(s) failed to connect [${w}]`);throw n({type:"error",error:S,phase:"init"}),S}let a=K(e,void 0,void 0,"executor"),f=K(e,e.planner,e.plannerModel,"planner"),h=K(e,e.synthesizer,e.synthesizerModel,"synthesizer"),l=Y(e.clientName,a),m=Y(e.clientName,f),E=Y(e.clientName,h),T={config:e,executorModel:l,plannerModel:m,synthesizerModel:E,tools:c.tools,toolCatalog:c.catalog.map(u=>({name:u.name,description:u.description})),emit:n},I=0,y=false,v=false,k=false,A=new Set,P=i(async u=>{await c.connection.refreshServer(u);let w=Z(c.connection.tools,c.connection.catalog,e.availableTools,e.excludedTools),S=g(w,b=>{throw new Error(`Native tool "${b}" collides with an MCP-registered tool of the same name`)});for(let b of Object.keys(T.tools))delete T.tools[b];Object.assign(T.tools,S.tools),T.toolCatalog=S.catalog.map(b=>({name:b.name,description:b.description})),s("info",`[mcp] ${u}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),_=i(async()=>{if(!(k||y||v)&&!(I>0||A.size===0)){k=true;try{for(;A.size>0&&I===0&&!y&&!v;){let u=A.values().next().value;A.delete(u);try{await P(u);}catch(w){s("warn",`[mcp] ${u}: refresh failed - ${w.message}`);}}}finally{k=false;}}},"drainPendingRefreshes");return r=i(u=>{A.add(u),_();},"onToolsChanged"),{run:i(async u=>{if(y)throw new Error("Agent is closed");if(v)throw new Error("Agent is reconnecting; retry shortly");if(k)throw new Error("Agent is refreshing tools; retry shortly");let w=e.maxConcurrentRuns;if(typeof w=="number"&&w>0&&I>=w)throw new Error(`maxConcurrentRuns reached (${I}/${w}); rate-limit on the caller side or raise the cap`);I++;try{return await Oe(T,u)}finally{I--,_();}},"run"),listTools:i(()=>T.toolCatalog.slice(),"listTools"),reconnect:i(async()=>{if(y)throw new Error("Agent is closed");if(v)throw new Error("Already reconnecting");if(k)throw new Error("Agent is refreshing tools; retry shortly");if(I>0)throw new Error(`Cannot reconnect with ${I} active run(s)`);v=true;try{let u=c.connection;A.clear();let w=await d();for(let S of Object.keys(T.tools))delete T.tools[S];Object.assign(T.tools,w.tools),T.toolCatalog=w.catalog.map(S=>({name:S.name,description:S.description})),c=w,await u.close().catch(()=>{});}finally{v=false;}},"reconnect"),close:i(async u=>{y=true;let w=u?.waitForRuns??false,S=u?.timeoutMs??3e4;if(w&&I>0){let b=Date.now();for(;I>0&&Date.now()-b<S;)await new Promise(O=>setTimeout(O,50));}I>0&&n({type:"log",level:"warn",message:`[agent] close called with ${I} active run(s); they will fail mid-flight`}),await c.connection.close().catch(()=>{});},"close"),activeRuns:i(()=>I,"activeRuns")}},"createAgent");var B=["openai","anthropic","openai-compatible","google"],Ne=["none","error","warn","info","debug"],Le=["all","plan-narrowed"],je=i(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!B.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${B.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!Ne.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${Ne.join(" | ")}, got: ${t}`);let o=e==="openai-compatible"?ae("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:ae("AGENT_API_KEY"),model:ae("AGENT_MODEL"),planner:Me("AGENT_PLANNER"),synthesizer:Me("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:Vt(process.env.MCP_SERVERS),availableTools:Ue(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:Ue(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:De(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:De(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:V(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:V(process.env.AGENT_MAX_TOTAL_TOKENS),llmTimeoutMs:V(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:V(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:Ft(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),Me=i(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),n=process.env[`${e}_API_KEY`]?.trim();if(!(!t&&!o&&!n)){if(t&&!B.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${B.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:n||void 0}}},"parseStageOverride"),Ft=i(e=>{let t=e?.trim();if(t){if(!Le.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${Le.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),V=i(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),ae=i(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),Ue=i(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),De=i((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),Vt=i(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(n){throw new Error(`MCP_SERVERS must be valid JSON: ${n.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[n,s]of Object.entries(t)){if(!s||typeof s!="object")throw new Error(`MCP_SERVERS.${n} must be an object`);let r=s,g=typeof r.url=="string"&&r.url.length>0,d=typeof r.command=="string"&&r.command.length>0;if(g&&d)throw new Error(`MCP_SERVERS.${n}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!g&&!d)throw new Error(`MCP_SERVERS.${n}: must specify "url" (HTTP) or "command" (stdio)`);if(g){let c=r.headers&&typeof r.headers=="object"&&!Array.isArray(r.headers)?r.headers:void 0;o[n]={url:r.url,headers:c};continue}if(r.args!==void 0&&!Array.isArray(r.args))throw new Error(`MCP_SERVERS.${n}.args must be a string array`);if(r.env!==void 0&&(!r.env||typeof r.env!="object"||Array.isArray(r.env)))throw new Error(`MCP_SERVERS.${n}.env must be a string-to-string map`);if(r.cwd!==void 0&&typeof r.cwd!="string")throw new Error(`MCP_SERVERS.${n}.cwd must be a string`);o[n]={command:r.command,args:r.args,env:r.env,cwd:r.cwd};}return o},"parseMcpServers");var Wt=16,q=i((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),Ge=i(e=>{try{return q(JSON.stringify(e))}catch{return String(e)}},"formatJson"),ze=i(async()=>{let e=je(),t=Object.keys(e.mcpServers),o=e.planner?.model??e.plannerModel??e.model,n=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${o} synth=${n} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[mcp] servers=${t.length?t.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /reconnect, /exit
100
+ `);let s=false,r=false,d=await $e(e,i(l=>{switch(l.type){case "log":console.log(`[${l.level}] ${l.message}`);break;case "plan.thought-delta":r||(process.stdout.write(`
101
+ [plan] `),r=true),process.stdout.write(l.delta);break;case "plan.step-added":r&&(process.stdout.write(`
102
+ `),r=false),console.log(` ${l.index+1}. ${l.step.description}`);break;case "plan.created":r?(process.stdout.write(`
103
+ `),r=false):console.log(`
104
+ [plan] ${l.plan.thought}`);for(let[m,E]of l.plan.steps.entries()){let T=E.suggestedTools?.length?` (tools: ${E.suggestedTools.join(", ")})`:"";console.log(` ${m+1}. ${E.description}${T}`);}break;case "plan.revised":console.log(`
105
+ [replan] reason=${l.reason}`);for(let[m,E]of l.plan.steps.entries())console.log(` ${m+1}. ${E.description}`);break;case "step.start":console.log(`
106
+ [step ${l.index+1}] ${l.step.description}`);break;case "step.tool-call":console.log(` -> ${l.name} ${Ge(l.input)}`);break;case "step.tool-result":{let m=l.ok?"ok":"fail";console.log(` <- ${l.name} ${m} ${Ge(l.output)}`);break}case "step.complete":console.log(` = ${q(l.result.summary,400)} (${l.result.durationMs}ms, ${l.result.toolCalls.length} tool calls)`);break;case "replan.decision":l.mode!=="continue"&&console.log(`[replan] ${l.mode} (${l.cause}): ${l.reason}`);break;case "usage":break;case "retry":l.phase==="plan"&&r&&(process.stdout.write(`
107
+ `),r=false),console.log(`[retry] ${l.phase} attempt=${l.attempt}: ${l.error}`);break;case "budget.exceeded":console.log(`[budget] token cap reached: ${l.tokens}/${l.cap} - finishing early`);break;case "revisions.exceeded":console.log(`[budget] max ${l.cap} replan-revisions reached - finishing early`);break;case "final.text-delta":s||(process.stdout.write(`
108
+ assistant> `),s=true),process.stdout.write(l.delta);break;case "final":s?(process.stdout.write(`
99
109
 
100
- `),o=false):console.log(`
101
- assistant> ${r.text}
102
- `);break;case "error":r.phase==="plan"&&n&&(process.stdout.write(`
103
- `),n=false),console.error(`[error] (${r.phase}) ${r.error.message}`);break}},"onEvent")),c=a.listTools();console.log(`[tools] available=${c.length}${c.length?`: ${c.map(r=>r.name).join(", ")}`:""}`);let p=createInterface({input:stdin,output:stdout}),i=[],u=null,f=s(()=>{u?(console.log(`
104
- [abort] cancelling current run...`),u.abort()):p.close();},"onSigInt");process.on("SIGINT",f);try{for(;;){let r;try{r=(await p.question(`
105
- you> `)).trim();}catch{break}if(r){if(r==="/exit"||r==="/quit")break;if(r==="/tools"){if(c.length===0)console.log("[tools] (none)");else for(let d of c)console.log(` - ${d.name}: ${P(d.description,200)}`);continue}if(r==="/status"){console.log(`[status] model=${e.model} planner=${e.plannerModel??e.model}`),console.log(`[status] tools=${c.length} mcp=${t.join(", ")||"(none)"} historyTurns=${i.length}`);continue}if(r==="/history"){if(i.length===0)console.log("[history] (empty)");else for(let d of i)console.log(` ${d.role}: ${P(d.content,200)}`);continue}if(r==="/reset"){i.length=0,console.log("[history] cleared");continue}if(r==="/reconnect"){try{await a.reconnect();let d=a.listTools();c.length=0;for(let T of d)c.push(T);console.log(`[mcp] reconnected, ${c.length} tools available`);}catch(d){console.error("[error] reconnect failed:",d.message);}continue}o=!1,n=!1,u=new AbortController;try{let d=await a.run({input:r,history:i,signal:u.signal});for(i.push({role:"user",content:r}),i.push({role:"assistant",content:d.text});i.length>rt;)i.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"):console.error("[error]",d.message);}finally{u=null;}}}}finally{process.off("SIGINT",f),p.close(),await a.close().catch(r=>console.error("[cleanup] agent",r));}},"runRepl");var st=s(async()=>{let e;try{e=H(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(q);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);}try{await he();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
110
+ `),s=false):console.log(`
111
+ assistant> ${l.text}
112
+ `);break;case "error":l.phase==="plan"&&r&&(process.stdout.write(`
113
+ `),r=false),console.error(`[error] (${l.phase}) ${l.error.message}`);break}},"onEvent")),c=d.listTools();console.log(`[tools] available=${c.length}${c.length?`: ${c.map(l=>l.name).join(", ")}`:""}`);let p=createInterface({input:stdin,output:stdout}),a=[],f=null,h=i(()=>{f?(console.log(`
114
+ [abort] cancelling current run...`),f.abort()):p.close();},"onSigInt");process.on("SIGINT",h);try{for(;;){let l;try{l=(await p.question(`
115
+ you> `)).trim();}catch{break}if(l){if(l==="/exit"||l==="/quit")break;if(l==="/tools"){if(c.length===0)console.log("[tools] (none)");else for(let m of c)console.log(` - ${m.name}: ${q(m.description,200)}`);continue}if(l==="/status"){console.log(`[status] model=${e.model} planner=${o} synth=${n}`),console.log(`[status] tools=${c.length} mcp=${t.join(", ")||"(none)"} historyTurns=${a.length}`);continue}if(l==="/history"){if(a.length===0)console.log("[history] (empty)");else for(let m of a)console.log(` ${m.role}: ${q(m.content,200)}`);continue}if(l==="/reset"){a.length=0,console.log("[history] cleared");continue}if(l==="/reconnect"){try{await d.reconnect();let m=d.listTools();c.length=0;for(let E of m)c.push(E);console.log(`[mcp] reconnected, ${c.length} tools available`);}catch(m){console.error("[error] reconnect failed:",m.message);}continue}s=!1,r=!1,f=new AbortController;try{let m=await d.run({input:l,history:a,signal:f.signal});for(a.push({role:"user",content:l}),a.push({role:"assistant",content:m.text});a.length>Wt;)a.shift();console.log(`[meta] iterations=${m.iterations} steps=${m.trace.length} tokens=${m.usage.totalTokens} (in=${m.usage.inputTokens} out=${m.usage.outputTokens})`);}catch(m){m?.name==="AbortError"?console.log("[abort] run cancelled"):console.error("[error]",m.message);}finally{f=null;}}}}finally{process.off("SIGINT",h),p.close(),await d.close().catch(l=>console.error("[cleanup] agent",l));}},"runRepl");var Jt=i(async()=>{let e;try{e=ce(process.argv.slice(2));}catch(t){console.error(t.message),console.error("\nRun `dd-agent --help` for usage."),process.exit(2);}if(e.help){process.stdout.write(le);return}if(e.envFile)try{process.loadEnvFile(e.envFile);}catch(t){console.error(`Failed to load env file ${e.envFile}: ${t.message}`),process.exit(2);}for(let[t,o]of Object.entries(e.overrides))process.env[t]=o;try{await ze();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
106
116
 
107
- Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");st().catch(e=>{console.error(e),process.exit(1);});
117
+ Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");Jt().catch(e=>{console.error(e),process.exit(1);});
package/dist/index.cjs CHANGED
@@ -1,13 +1,16 @@
1
- 'use strict';var index_js=require('@modelcontextprotocol/sdk/client/index.js'),streamableHttp_js=require('@modelcontextprotocol/sdk/client/streamableHttp.js'),ai=require('ai'),url=require('url'),anthropic=require('@ai-sdk/anthropic'),google=require('@ai-sdk/google'),openai=require('@ai-sdk/openai'),openaiCompatible=require('@ai-sdk/openai-compatible'),crypto=require('crypto'),async_hooks=require('async_hooks'),zod=require('zod');var oe=Object.defineProperty;var r=(e,t)=>oe(e,"name",{value:t,configurable:true});var Y=r(async(e,t,n,o)=>{let s=[],i={},u=[],c=[];for(let[a,p]of Object.entries(e)){if(p.headers&&p.getHeaders)throw new Error(`MCP server "${a}": specify either headers or getHeaders, not both`);try{let d=p.getHeaders?await p.getHeaders():p.headers,g=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(p.url),{requestInit:d?{headers:d}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});g.onerror=m=>t("warn",`[mcp] ${a}: transport error - ${m.message}`),g.onclose=()=>t("warn",`[mcp] ${a}: transport closed`);let y=new index_js.Client({name:n,version:"0.0.0"});await y.connect(g),s.push(y);let I=await y.listTools(),w=0;for(let m of I.tools){let h=`${a}__${m.name}`,l=m.description??"";i[h]=ai.dynamicTool({description:l,inputSchema:ai.jsonSchema(m.inputSchema),execute:r(async(f,x)=>{let _=await y.callTool({name:m.name,arguments:f??{}},void 0,x?.abortSignal?{signal:x.abortSignal}:void 0),T=ce(_.content);if(!o)return T;try{return await o(h,T)}catch(A){return t("warn",`[mcp] ${h}: outputSanitizer threw - ${A.message}; output replaced with placeholder`),"[output redacted: sanitizer failed]"}},"execute")}),u.push({name:h,description:l,server:a}),w++;}t("info",`[mcp] ${a}: connected, ${w} tools`),c.push({name:a,connected:!0});}catch(d){let g=d.message;t("error",`[mcp] ${a}: failed to connect - ${g}`),c.push({name:a,connected:false,error:g});}}return {tools:i,catalog:u,results:c,close:r(async()=>{await Promise.allSettled(s.map(a=>a.close()));},"close")}},"connectMcpServers"),ce=r(e=>{if(!Array.isArray(e))return e;let t=e;return t.length>0&&t.every(o=>o?.type==="text"&&typeof o.text=="string")?t.map(o=>o.text).join(`
2
- `):t.map(o=>o?.type==="text"&&typeof o.text=="string"?o.text:o)},"flattenContent"),z=r((e,t,n,o)=>{let s=n?.length?new Set(n):null,i=o?.length?new Set(o):null,u={},c=[];for(let a of t){if(s&&!s.has(a.name)||!s&&i?.has(a.name))continue;let p=e[a.name];p&&(u[a.name]=p,c.push(a));}return {tools:u,catalog:c}},"filterTools");var v=r((e,t)=>{switch(e.providerType){case "openai":return openai.createOpenAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "anthropic":return anthropic.createAnthropic({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "openai-compatible":{if(!e.baseURL)throw new Error("openai-compatible provider requires baseURL");return openaiCompatible.createOpenAICompatible({name:e.clientName,baseURL:e.baseURL,apiKey:e.apiKey})(t)}case "google":return google.createGoogleGenerativeAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t)}},"buildModel");var k=new async_hooks.AsyncLocalStorage,he=r(()=>k.getStore()?.runId,"getCurrentRunId");var M=r(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),n=e.length-t.length,o=[];n>0&&o.push(`(${n} earlier turns omitted)`);for(let s of t){let i=s.content.length>1500?`${s.content.slice(0,1500)}... [truncated]`:s.content;o.push(`${s.role}: ${i}`);}return o.join(`
3
- `)},"renderHistory"),fe={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},q=r((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:n,descChars:o}=fe[t],s=e.slice(0,n),i=e.length-s.length,u=s.map(c=>{let a=(c.description||"").replace(/\s+/g," ").trim().slice(0,o);return `- ${c.name}: ${a}`});return i>0&&u.push(`... and ${i} more tools`),u.join(`
4
- `)},"renderToolCatalog"),O=1500,ye=r(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>O?`${t.slice(0,O)}... [truncated, ${t.length-O} chars]`:t},"truncateOutput"),we=r((e,t)=>{let n=e.toolCalls.length?e.toolCalls.map(o=>` - ${o.name} ${o.ok?"ok":"fail"}: ${ye(o.output)}`).join(`
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
5
  `):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",n].join(`
6
- `)},"renderTraceEntry"),$=r(e=>e.length===0?"(no steps executed yet)":e.map(we).join(`
7
- `),"renderTrace"),N=r(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,n)=>` ${n+1}. [${t.id}] ${t.description}
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
8
  expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
9
9
  suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
10
- `),"renderPlan"),H=`You are the Planner of a multi-step agent system.
10
+ `),"renderPlan"),_=s((e,t)=>t?`${e}
11
+
12
+ Domain context:
13
+ ${t}`:e,"withDomainContext"),le=`You are the Planner of a multi-step agent system.
11
14
 
12
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.
13
16
 
@@ -17,28 +20,28 @@ Rules:
17
20
  3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
18
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.
19
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).
20
- 6. Output strict JSON matching the requested schema. No prose outside JSON.`,Ie=`
23
+ 6. Output strict JSON matching the requested schema. No prose outside JSON.`,it=`
21
24
 
22
25
  ADDITIONAL RULE (tool-narrowed mode):
23
- The agent narrows the active tool set per-step using suggestedTools. You MUST set suggestedTools to the EXACT tool names the executor will use for that step. If a step is reasoning-only and needs no tools, leave suggestedTools empty. Missing or wrong suggestedTools will leave the executor without the tools it needs.`,U=r(e=>e==="compact"?H+Ie:H,"buildPlannerSystem"),B=r((e,t,n,o="full")=>[n?.length?`Conversation history:
24
- ${M(n)}
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)}
25
28
  `:"",`User request:
26
29
  ${e}`,"",`Available tools:
27
- ${q(t,o)}`,"","Produce the plan now."].filter(Boolean).join(`
28
- `),"buildPlannerUserPrompt"),L=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
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.
29
32
 
30
33
  Rules:
31
34
  1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
32
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.
33
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.
34
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.
35
- 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,K=r((e,t,n,o,s)=>[s?.length?`Conversation history:
36
- ${M(s)}
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)}
37
40
  `:"",`Original user request:
38
41
  ${e}`,"",`Overall plan:
39
- ${N(t)}`,"",`Trace so far:
40
- ${$(o)}`,"",`CURRENT STEP to execute (id=${n.id}): ${n.description}`,`Expected outcome: ${n.expectedOutcome}`,n.suggestedTools?.length?`Suggested tools: ${n.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
41
- `),"buildExecutorUserPrompt"),W=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
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.
42
45
 
43
46
  You have three options:
44
47
  - "continue": the next planned step is still appropriate.
@@ -49,27 +52,21 @@ Rules:
49
52
  1. Prefer "continue" when the original plan still applies. Revise only when needed.
50
53
  2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
51
54
  3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
52
- 4. Output strict JSON matching the schema. No prose outside JSON.`,G=r((e,t,n,o,s,i="full")=>[`Original user request:
55
+ 4. Output strict JSON matching the schema. No prose outside JSON.`,fe=s((e,t,n,o,r,a="full")=>[`Original user request:
53
56
  ${e}`,"",`Current plan:
54
- ${N(t)}`,"",`Completed steps:
55
- ${$(n)}`,"",o?`Next planned step: [${o.id}] ${o.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
56
- ${q(s,i)}`,"","Decide now: continue, revise, or finish."].join(`
57
- `),"buildReplannerUserPrompt"),F=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
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.
58
61
 
59
62
  Rules:
60
63
  1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
61
64
  2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
62
65
  3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
63
- 4. Use the user's language.`,J=r((e,t,n,o)=>[o?.length?`Conversation history:
64
- ${M(o)}
66
+ 4. Use the user's language.`,ye=s((e,t,n,o)=>[o?.length?`Conversation history:
67
+ ${X(o)}
65
68
  `:"",`User request:
66
69
  ${e}`,"",`Plan that was executed:
67
- ${N(t)}`,"",`Execution trace:
68
- ${$(n)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
69
- `),"buildSynthesizerUserPrompt");var X=r((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let n=e;if(n.name==="AbortError")return false;let o=n.statusCode??n.status;return typeof o=="number"?o===429||o>=500:n.name==="TypeError"?true:n.cause&&typeof n.cause=="object"?X(n.cause,t):false},"isRetriable"),R=r(async(e,t)=>{let n=t.baseDelayMs??500,o;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(o=i,s===t.maxRetries||!X(i))throw i;t.onRetry?.(s+1,i);let u=n*2**s+Math.random()*250;await Te(u,t.signal);}}throw o},"withRetry"),Te=r((e,t)=>new Promise((n,o)=>{if(t?.aborted){o(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",i),n();},e),i=r(()=>{clearTimeout(s),o(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),be=r(e=>{let t=e.filter(n=>!!n);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),C=r((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:be([e,AbortSignal.timeout(t)]),"withTimeout"),Se=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),Re=r(e=>{if(!e)return e;let t={};for(let[n,o]of Object.entries(e))t[n]=Se.has(n.toLowerCase())?"***redacted***":o;return t},"redactHeaders");var Ae=r((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let n=new Set(t.suggestedTools??[]);if(n.size===0)return t.requiresTools?e.tools:{};let o={};for(let s of n){let i=e.tools[s];i&&(o[s]=i);}return o},"buildActiveToolSet"),V="[BLOCKER]",ve=r(e=>{let t=e.indexOf(V);return t===-1?{summary:e,blocked:false}:{summary:(e.slice(0,t)+e.slice(t+V.length)).trim(),blocked:true}},"splitBlockerSentinel"),j=4e3,ke=r(e=>e.length>j?`${e.slice(0,j)}... [truncated, ${e.length-j} chars]`:e,"truncateForTrace"),Z=r(async(e,t,n,o,s,i,u)=>{let c=Date.now(),a=await R(()=>Ee(e,t,n,o,s,i,u),{maxRetries:i.config.llmMaxRetries??2,signal:u,onRetry:r((p,d)=>i.emit({type:"retry",phase:"execute",attempt:p,error:d.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:a.usage}),{step:n,summary:a.summary,toolCalls:a.toolCalls,durationMs:Date.now()-c,blocked:a.blocked}},"executeStep"),Ee=r(async(e,t,n,o,s,i,u)=>{let c=[],a=new Map,p=Ae(i,n),d=i.config.toolSelectionStrategy==="plan-narrowed",g=ai.streamText({model:i.executorModel,tools:p,...d?{activeTools:Object.keys(p)}:{},stopWhen:ai.stepCountIs(i.config.maxStepsPerTask),system:i.config.systemPrompt?`${L}
70
-
71
- Domain context:
72
- ${i.config.systemPrompt}`:L,prompt:K(e,t,n,o,s),abortSignal:C(u,i.config.llmTimeoutMs??0)});for await(let l of g.fullStream)switch(l.type){case "text-delta":l.text&&i.emit({type:"step.text-delta",step:n,delta:l.text});break;case "tool-call":{a.set(l.toolCallId,{name:l.toolName,input:l.input}),i.emit({type:"step.tool-call",step:n,name:l.toolName,input:l.input});break}case "tool-result":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.output,ok:true}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.output,ok:true}),a.delete(l.toolCallId);break}case "tool-error":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.error,ok:false}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.error,ok:false}),a.delete(l.toolCallId);break}case "error":{let f=l.error;throw f instanceof Error?f:new Error(String(f))}}let[y,I]=await Promise.all([g.text,g.usage]),{summary:w,blocked:m}=ve(y.trim());return {summary:w.length>0?ke(w):c.length>0?`Executed ${c.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:c,blocked:m,usage:{inputTokens:I.inputTokens??0,outputTokens:I.outputTokens??0,totalTokens:I.totalTokens??0}}},"runOnce");var Oe=zod.z.object({id:zod.z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:zod.z.string().min(1).describe("Concrete action to perform"),expectedOutcome:zod.z.string().min(1).describe("What state/data should exist after this step"),suggestedTools:zod.z.array(zod.z.string()).optional().describe("Tool names from the available list, if any")}),D=zod.z.object({thought:zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:zod.z.array(Oe).min(1).max(8)}),Q=r(async(e,t,n,o)=>{let s=new Set(n.toolCatalog.map(a=>a.name)),i=n.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:u,usage:c}=await R(()=>Me(e,t,i,n,o),{maxRetries:n.config.llmMaxRetries??2,signal:o,onRetry:r((a,p)=>n.emit({type:"retry",phase:"plan",attempt:a,error:p.message}),"onRetry")});return n.emit({type:"usage",phase:"plan",usage:c}),{thought:u.thought,steps:u.steps.map(a=>{if(!a.suggestedTools?.length)return a;let p=a.suggestedTools.filter(g=>s.has(g)),d=a.suggestedTools.length-p.length;return d>0&&n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had ${d} unknown suggestedTools, stripped`}),p.length===0?(n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had no valid suggestedTools left; falling back to full toolset`}),{...a,suggestedTools:void 0,requiresTools:true}):{...a,suggestedTools:p}})}},"createInitialPlan"),Me=r(async(e,t,n,o,s)=>{let i=ai.streamObject({model:o.plannerModel,schema:D,system:o.config.systemPrompt?`${U(n)}
73
-
74
- Domain context:
75
- ${o.config.systemPrompt}`:U(n),prompt:B(e,o.toolCatalog,t,n),abortSignal:C(s,o.config.llmTimeoutMs??0)}),u="",c=false;for await(let d of i.partialObjectStream){let g=d?.thought;typeof g!="string"||g===u||(g.startsWith(u)?o.emit({type:"plan.thought-delta",delta:g.slice(u.length)}):c||(o.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),c=true),u=g);}let[a,p]=await Promise.all([i.object,i.usage]);return {object:a,usage:{inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,totalTokens:p.totalTokens??0}}},"streamPlanOnce");var Ne=zod.z.discriminatedUnion("mode",[zod.z.object({mode:zod.z.literal("continue"),reason:zod.z.string().min(1).describe("Why the next step is still appropriate")}),zod.z.object({mode:zod.z.literal("finish"),reason:zod.z.string().min(1).describe("Why no more steps are needed")}),zod.z.object({mode:zod.z.literal("revise"),reason:zod.z.string().min(1).describe("Why the plan must change"),newPlan:D.describe("Plan covering ONLY the remaining work")})]),ee=r(async(e,t,n,o,s,i)=>{let u=s.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:a}=await R(async()=>{let p=await ai.generateObject({model:s.plannerModel,schema:Ne,system:W,prompt:G(e,t,n,o,s.toolCatalog,u),abortSignal:C(i,s.config.llmTimeoutMs??0)}),d={inputTokens:p.usage.inputTokens??0,outputTokens:p.usage.outputTokens??0,totalTokens:p.usage.totalTokens??0};return {object:p.object,usage:d}},{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((p,d)=>s.emit({type:"retry",phase:"replan",attempt:p,error:d.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:a}),c},"decideNextAction");var te=r(async(e,t,n,o,s,i)=>{let{text:u,usage:c}=await R(()=>Le(e,t,n,o,s,i),{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((a,p)=>s.emit({type:"retry",phase:"synthesize",attempt:a,error:p.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:c}),u},"synthesizeAnswer"),Le=r(async(e,t,n,o,s,i)=>{let u=ai.streamText({model:s.synthesizerModel,system:F,prompt:J(e,t,n,o),abortSignal:C(i,s.config.llmTimeoutMs??0)});for await(let p of u.fullStream)if(p.type==="text-delta")p.text&&s.emit({type:"final.text-delta",delta:p.text});else if(p.type==="error"){let d=p.error;throw d instanceof Error?d:new Error(String(d))}let[c,a]=await Promise.all([u.text,u.usage]);return {text:c,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamOnce");var De=r(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),_e=r(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),ne=r(async(e,t)=>{let n=crypto.randomUUID();return k.run({runId:n,startedAt:Date.now()},()=>Ye(e,t))},"runAgentLoop"),Ye=r(async(e,t)=>{let{input:n,signal:o}=t,s=t.history?[...t.history]:void 0,i=t.onEvent??(()=>{}),u={inputTokens:0,outputTokens:0,totalTokens:0},c={...e,emit:r(l=>{l.type==="usage"&&(u.inputTokens+=l.usage.inputTokens,u.outputTokens+=l.usage.outputTokens,u.totalTokens+=l.usage.totalTokens);let f={...l,runId:k.getStore()?.runId};try{i(f);}catch{}try{e.emit(f);}catch{}},"emit")},a;try{a=await Q(n,s,c,o);}catch(l){if(c.emit({type:"error",error:E(l),phase:"plan"}),_e(l)||o?.aborted)throw l;a={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}c.emit({type:"plan.created",plan:a});let p=[],d=a,g=0,y=0,I=0,w=e.config.maxRevisions??2,m=e.config.maxTotalTokens;for(;y<e.config.maxIterations;){if(y++,o?.aborted)throw new DOMException("Aborted","AbortError");if(g>=d.steps.length)break;if(m&&u.totalTokens>=m){c.emit({type:"budget.exceeded",tokens:u.totalTokens,cap:m});break}let l=d.steps[g];c.emit({type:"step.start",step:l,index:g});let f;try{f=await Z(n,d,l,p,s,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"execute"}),A}p.push(f),c.emit({type:"step.complete",step:l,result:f});let x=d.steps[g+1]??null;if(x===null){c.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!De(f)){c.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),g++;continue}let T;try{T=await ee(n,d,p,x,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"replan"}),A}if(c.emit({type:"replan.decision",mode:T.mode,reason:T.reason,cause:"llm-decision"}),T.mode==="finish")break;if(T.mode==="revise"){if(I>=w){c.emit({type:"revisions.exceeded",cap:w});break}I++,d=T.newPlan,c.emit({type:"plan.revised",plan:d,reason:T.reason}),g=0;continue}g++;}let h;try{h=await te(n,d,p,s,c,o);}catch(l){throw c.emit({type:"error",error:E(l),phase:"synthesize"}),l}return c.emit({type:"final",text:h}),{text:h,plan:d,trace:p,iterations:y,usage:u}},"runAgentLoopInner"),E=r(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var P={none:0,error:1,warn:2,info:3,debug:4},zt=r(async(e,t)=>{let n=P[e.logLevel]>=P.debug,o=r(m=>{if(t)try{t(m);}catch(h){n&&console.error("[agent] event handler threw:",h);}},"emit"),s=r((m,h)=>{P[e.logLevel]>=P[m]&&o({type:"log",level:m,message:h});},"log"),i=r(async()=>{let m=await Y(e.mcpServers,s,e.clientName,e.outputSanitizer),h=z(m.tools,m.catalog,e.availableTools,e.excludedTools);return {connection:m,tools:h.tools,catalog:h.catalog}},"connect"),u;try{u=await i();}catch(m){throw o({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let c=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&c>0&&!u.connection.results.some(h=>h.connected)){let h=u.connection.results.filter(f=>!f.connected).map(f=>`${f.name}: ${f.error??"unknown"}`).join("; ");await u.connection.close().catch(()=>{});let l=new Error(`All ${c} configured MCP server(s) failed to connect [${h}]`);throw o({type:"error",error:l,phase:"init"}),l}let a=v(e,e.model),p=v(e,e.plannerModel??e.model),d=v(e,e.synthesizerModel??e.model),g={config:e,executorModel:a,plannerModel:p,synthesizerModel:d,tools:u.tools,toolCatalog:u.catalog.map(m=>({name:m.name,description:m.description})),emit:o},y=0,I=false,w=false;return {run:r(async m=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Agent is reconnecting; retry shortly");y++;try{return await ne(g,m)}finally{y--;}},"run"),listTools:r(()=>g.toolCatalog.slice(),"listTools"),reconnect:r(async()=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Already reconnecting");if(y>0)throw new Error(`Cannot reconnect with ${y} active run(s)`);w=true;try{let m=u.connection,h=await i();for(let l of Object.keys(g.tools))delete g.tools[l];Object.assign(g.tools,h.tools),g.toolCatalog=h.catalog.map(l=>({name:l.name,description:l.description})),u=h,await m.close().catch(()=>{});}finally{w=false;}},"reconnect"),close:r(async m=>{I=true;let h=m?.waitForRuns??false,l=m?.timeoutMs??3e4;if(h&&y>0){let f=Date.now();for(;y>0&&Date.now()-f<l;)await new Promise(x=>setTimeout(x,50));}y>0&&o({type:"log",level:"warn",message:`[agent] close called with ${y} active run(s); they will fail mid-flight`}),await u.connection.close().catch(()=>{});},"close"),activeRuns:r(()=>y,"activeRuns")}},"createAgent");exports.createAgent=zt;exports.getCurrentRunId=he;exports.redactHeaders=Re;
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;
package/dist/index.d.cts CHANGED
@@ -1,20 +1,40 @@
1
+ import { ToolSet } from 'ai';
2
+
1
3
  type ProviderType = 'openai' | 'anthropic' | 'openai-compatible' | 'google';
2
4
  type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
3
5
  type ToolSelectionStrategy = 'all' | 'plan-narrowed';
4
- interface IMcpServerConfig {
6
+ interface IMcpHttpServerConfig {
5
7
  url: string;
6
8
  headers?: Record<string, string>;
7
9
  getHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
8
10
  }
11
+ interface IMcpStdioServerConfig {
12
+ command: string;
13
+ args?: string[];
14
+ env?: Record<string, string>;
15
+ cwd?: string;
16
+ }
17
+ type IMcpServerConfig = IMcpHttpServerConfig | IMcpStdioServerConfig;
18
+ interface IAgentStageOverride {
19
+ providerType?: ProviderType;
20
+ baseURL?: string;
21
+ apiKey?: string;
22
+ model?: string;
23
+ }
9
24
  interface IAgentConfig {
10
25
  clientName: string;
11
26
  providerType: ProviderType;
12
27
  baseURL?: string;
13
28
  apiKey: string;
14
29
  model: string;
30
+ planner?: IAgentStageOverride;
31
+ synthesizer?: IAgentStageOverride;
32
+ /** @deprecated use `planner: { model }` */
15
33
  plannerModel?: string;
34
+ /** @deprecated use `synthesizer: { model }` */
16
35
  synthesizerModel?: string;
17
36
  mcpServers: Record<string, IMcpServerConfig>;
37
+ tools?: ToolSet;
18
38
  availableTools?: string[];
19
39
  excludedTools?: string[];
20
40
  maxIterations: number;
@@ -23,10 +43,15 @@ interface IAgentConfig {
23
43
  maxTotalTokens?: number;
24
44
  llmTimeoutMs?: number;
25
45
  llmMaxRetries?: number;
46
+ maxConcurrentRuns?: number;
47
+ persistence?: IPersistence;
26
48
  toolSelectionStrategy?: ToolSelectionStrategy;
49
+ inputSanitizer?: (toolName: string, input: unknown) => unknown | Promise<unknown>;
27
50
  outputSanitizer?: (toolName: string, output: unknown) => unknown | Promise<unknown>;
28
51
  logLevel: LogLevel;
29
52
  systemPrompt?: string;
53
+ sandboxRoot?: string;
54
+ keepSandbox?: boolean;
30
55
  failOnNoTools?: boolean;
31
56
  }
32
57
  interface IConversationTurn {
@@ -65,6 +90,10 @@ type ReplanCause = 'last-step' | 'clean-step' | 'llm-decision';
65
90
  type AgentEventBody = {
66
91
  type: 'plan.thought-delta';
67
92
  delta: string;
93
+ } | {
94
+ type: 'plan.step-added';
95
+ step: IPlanStep;
96
+ index: number;
68
97
  } | {
69
98
  type: 'plan.created';
70
99
  plan: IPlan;
@@ -135,11 +164,18 @@ type AgentEvent = AgentEventBody & {
135
164
  runId?: string;
136
165
  };
137
166
  type EventHandler = (event: AgentEvent) => void;
167
+ interface IStepStartInfo {
168
+ step: IPlanStep;
169
+ index: number;
170
+ abort: () => void;
171
+ }
138
172
  interface IAgentRunOptions {
139
173
  input: string;
140
174
  history?: IConversationTurn[];
141
175
  signal?: AbortSignal;
142
176
  onEvent?: EventHandler;
177
+ onStepStart?: (info: IStepStartInfo) => void;
178
+ resumeFromRunId?: string;
143
179
  }
144
180
  interface IAgentRunResult {
145
181
  text: string;
@@ -148,8 +184,31 @@ interface IAgentRunResult {
148
184
  iterations: number;
149
185
  usage: IUsage;
150
186
  }
187
+ interface IRunSnapshot {
188
+ runId: string;
189
+ startedAt: number;
190
+ status: 'executing' | 'complete' | 'failed' | 'cancelled';
191
+ input: string;
192
+ history?: IConversationTurn[];
193
+ plan?: IPlan;
194
+ trace: IStepResult[];
195
+ usage: IUsage;
196
+ stepIndex: number;
197
+ iterations: number;
198
+ revisions: number;
199
+ text?: string;
200
+ error?: string;
201
+ completedAt?: number;
202
+ }
203
+ interface IPersistence {
204
+ onRunStart?: (snapshot: IRunSnapshot) => void | Promise<void>;
205
+ onStepComplete?: (snapshot: IRunSnapshot) => void | Promise<void>;
206
+ onRunComplete?: (snapshot: IRunSnapshot) => void | Promise<void>;
207
+ loadRun?: (runId: string) => IRunSnapshot | null | Promise<IRunSnapshot | null>;
208
+ }
151
209
 
152
210
  declare const getCurrentRunId: () => string | undefined;
211
+ declare const getCurrentRunSandbox: () => string | undefined;
153
212
 
154
213
  declare const redactHeaders: (headers: Record<string, string> | undefined) => Record<string, string> | undefined;
155
214
 
@@ -169,4 +228,4 @@ interface IAgent {
169
228
  }
170
229
  declare const createAgent: (config: IAgentConfig, baseEventHandler?: EventHandler) => Promise<IAgent>;
171
230
 
172
- export { type AgentEvent, type EventHandler, type IAgent, type IAgentConfig, type IAgentRunOptions, type IAgentRunResult, type ICloseOptions, type IConversationTurn, type IMcpServerConfig, type IPlan, type IPlanStep, type IStepResult, type IUsage, type LogLevel, type ProviderType, type ReplanCause, type ToolSelectionStrategy, createAgent, getCurrentRunId, redactHeaders };
231
+ export { type AgentEvent, type EventHandler, type IAgent, type IAgentConfig, type IAgentRunOptions, type IAgentRunResult, type IAgentStageOverride, type ICloseOptions, type IConversationTurn, type IMcpHttpServerConfig, type IMcpServerConfig, type IMcpStdioServerConfig, type IPersistence, type IPlan, type IPlanStep, type IRunSnapshot, type IStepResult, type IStepStartInfo, type IUsage, type LogLevel, type ProviderType, type ReplanCause, type ToolSelectionStrategy, createAgent, getCurrentRunId, getCurrentRunSandbox, redactHeaders };
package/dist/index.d.ts CHANGED
@@ -1,20 +1,40 @@
1
+ import { ToolSet } from 'ai';
2
+
1
3
  type ProviderType = 'openai' | 'anthropic' | 'openai-compatible' | 'google';
2
4
  type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
3
5
  type ToolSelectionStrategy = 'all' | 'plan-narrowed';
4
- interface IMcpServerConfig {
6
+ interface IMcpHttpServerConfig {
5
7
  url: string;
6
8
  headers?: Record<string, string>;
7
9
  getHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
8
10
  }
11
+ interface IMcpStdioServerConfig {
12
+ command: string;
13
+ args?: string[];
14
+ env?: Record<string, string>;
15
+ cwd?: string;
16
+ }
17
+ type IMcpServerConfig = IMcpHttpServerConfig | IMcpStdioServerConfig;
18
+ interface IAgentStageOverride {
19
+ providerType?: ProviderType;
20
+ baseURL?: string;
21
+ apiKey?: string;
22
+ model?: string;
23
+ }
9
24
  interface IAgentConfig {
10
25
  clientName: string;
11
26
  providerType: ProviderType;
12
27
  baseURL?: string;
13
28
  apiKey: string;
14
29
  model: string;
30
+ planner?: IAgentStageOverride;
31
+ synthesizer?: IAgentStageOverride;
32
+ /** @deprecated use `planner: { model }` */
15
33
  plannerModel?: string;
34
+ /** @deprecated use `synthesizer: { model }` */
16
35
  synthesizerModel?: string;
17
36
  mcpServers: Record<string, IMcpServerConfig>;
37
+ tools?: ToolSet;
18
38
  availableTools?: string[];
19
39
  excludedTools?: string[];
20
40
  maxIterations: number;
@@ -23,10 +43,15 @@ interface IAgentConfig {
23
43
  maxTotalTokens?: number;
24
44
  llmTimeoutMs?: number;
25
45
  llmMaxRetries?: number;
46
+ maxConcurrentRuns?: number;
47
+ persistence?: IPersistence;
26
48
  toolSelectionStrategy?: ToolSelectionStrategy;
49
+ inputSanitizer?: (toolName: string, input: unknown) => unknown | Promise<unknown>;
27
50
  outputSanitizer?: (toolName: string, output: unknown) => unknown | Promise<unknown>;
28
51
  logLevel: LogLevel;
29
52
  systemPrompt?: string;
53
+ sandboxRoot?: string;
54
+ keepSandbox?: boolean;
30
55
  failOnNoTools?: boolean;
31
56
  }
32
57
  interface IConversationTurn {
@@ -65,6 +90,10 @@ type ReplanCause = 'last-step' | 'clean-step' | 'llm-decision';
65
90
  type AgentEventBody = {
66
91
  type: 'plan.thought-delta';
67
92
  delta: string;
93
+ } | {
94
+ type: 'plan.step-added';
95
+ step: IPlanStep;
96
+ index: number;
68
97
  } | {
69
98
  type: 'plan.created';
70
99
  plan: IPlan;
@@ -135,11 +164,18 @@ type AgentEvent = AgentEventBody & {
135
164
  runId?: string;
136
165
  };
137
166
  type EventHandler = (event: AgentEvent) => void;
167
+ interface IStepStartInfo {
168
+ step: IPlanStep;
169
+ index: number;
170
+ abort: () => void;
171
+ }
138
172
  interface IAgentRunOptions {
139
173
  input: string;
140
174
  history?: IConversationTurn[];
141
175
  signal?: AbortSignal;
142
176
  onEvent?: EventHandler;
177
+ onStepStart?: (info: IStepStartInfo) => void;
178
+ resumeFromRunId?: string;
143
179
  }
144
180
  interface IAgentRunResult {
145
181
  text: string;
@@ -148,8 +184,31 @@ interface IAgentRunResult {
148
184
  iterations: number;
149
185
  usage: IUsage;
150
186
  }
187
+ interface IRunSnapshot {
188
+ runId: string;
189
+ startedAt: number;
190
+ status: 'executing' | 'complete' | 'failed' | 'cancelled';
191
+ input: string;
192
+ history?: IConversationTurn[];
193
+ plan?: IPlan;
194
+ trace: IStepResult[];
195
+ usage: IUsage;
196
+ stepIndex: number;
197
+ iterations: number;
198
+ revisions: number;
199
+ text?: string;
200
+ error?: string;
201
+ completedAt?: number;
202
+ }
203
+ interface IPersistence {
204
+ onRunStart?: (snapshot: IRunSnapshot) => void | Promise<void>;
205
+ onStepComplete?: (snapshot: IRunSnapshot) => void | Promise<void>;
206
+ onRunComplete?: (snapshot: IRunSnapshot) => void | Promise<void>;
207
+ loadRun?: (runId: string) => IRunSnapshot | null | Promise<IRunSnapshot | null>;
208
+ }
151
209
 
152
210
  declare const getCurrentRunId: () => string | undefined;
211
+ declare const getCurrentRunSandbox: () => string | undefined;
153
212
 
154
213
  declare const redactHeaders: (headers: Record<string, string> | undefined) => Record<string, string> | undefined;
155
214
 
@@ -169,4 +228,4 @@ interface IAgent {
169
228
  }
170
229
  declare const createAgent: (config: IAgentConfig, baseEventHandler?: EventHandler) => Promise<IAgent>;
171
230
 
172
- export { type AgentEvent, type EventHandler, type IAgent, type IAgentConfig, type IAgentRunOptions, type IAgentRunResult, type ICloseOptions, type IConversationTurn, type IMcpServerConfig, type IPlan, type IPlanStep, type IStepResult, type IUsage, type LogLevel, type ProviderType, type ReplanCause, type ToolSelectionStrategy, createAgent, getCurrentRunId, redactHeaders };
231
+ export { type AgentEvent, type EventHandler, type IAgent, type IAgentConfig, type IAgentRunOptions, type IAgentRunResult, type IAgentStageOverride, type ICloseOptions, type IConversationTurn, type IMcpHttpServerConfig, type IMcpServerConfig, type IMcpStdioServerConfig, type IPersistence, type IPlan, type IPlanStep, type IRunSnapshot, type IStepResult, type IStepStartInfo, type IUsage, type LogLevel, type ProviderType, type ReplanCause, type ToolSelectionStrategy, createAgent, getCurrentRunId, getCurrentRunSandbox, redactHeaders };
package/dist/index.js CHANGED
@@ -1,13 +1,16 @@
1
- import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {dynamicTool,jsonSchema,streamText,stepCountIs,streamObject,generateObject}from'ai';import {URL}from'url';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {createOpenAI}from'@ai-sdk/openai';import {createOpenAICompatible}from'@ai-sdk/openai-compatible';import {randomUUID}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {z as z$1}from'zod';var oe=Object.defineProperty;var r=(e,t)=>oe(e,"name",{value:t,configurable:true});var Y=r(async(e,t,n,o)=>{let s=[],i={},u=[],c=[];for(let[a,p]of Object.entries(e)){if(p.headers&&p.getHeaders)throw new Error(`MCP server "${a}": specify either headers or getHeaders, not both`);try{let d=p.getHeaders?await p.getHeaders():p.headers,g=new StreamableHTTPClientTransport(new URL(p.url),{requestInit:d?{headers:d}:void 0,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});g.onerror=m=>t("warn",`[mcp] ${a}: transport error - ${m.message}`),g.onclose=()=>t("warn",`[mcp] ${a}: transport closed`);let y=new Client({name:n,version:"0.0.0"});await y.connect(g),s.push(y);let I=await y.listTools(),w=0;for(let m of I.tools){let h=`${a}__${m.name}`,l=m.description??"";i[h]=dynamicTool({description:l,inputSchema:jsonSchema(m.inputSchema),execute:r(async(f,x)=>{let _=await y.callTool({name:m.name,arguments:f??{}},void 0,x?.abortSignal?{signal:x.abortSignal}:void 0),T=ce(_.content);if(!o)return T;try{return await o(h,T)}catch(A){return t("warn",`[mcp] ${h}: outputSanitizer threw - ${A.message}; output replaced with placeholder`),"[output redacted: sanitizer failed]"}},"execute")}),u.push({name:h,description:l,server:a}),w++;}t("info",`[mcp] ${a}: connected, ${w} tools`),c.push({name:a,connected:!0});}catch(d){let g=d.message;t("error",`[mcp] ${a}: failed to connect - ${g}`),c.push({name:a,connected:false,error:g});}}return {tools:i,catalog:u,results:c,close:r(async()=>{await Promise.allSettled(s.map(a=>a.close()));},"close")}},"connectMcpServers"),ce=r(e=>{if(!Array.isArray(e))return e;let t=e;return t.length>0&&t.every(o=>o?.type==="text"&&typeof o.text=="string")?t.map(o=>o.text).join(`
2
- `):t.map(o=>o?.type==="text"&&typeof o.text=="string"?o.text:o)},"flattenContent"),z=r((e,t,n,o)=>{let s=n?.length?new Set(n):null,i=o?.length?new Set(o):null,u={},c=[];for(let a of t){if(s&&!s.has(a.name)||!s&&i?.has(a.name))continue;let p=e[a.name];p&&(u[a.name]=p,c.push(a));}return {tools:u,catalog:c}},"filterTools");var v=r((e,t)=>{switch(e.providerType){case "openai":return createOpenAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "anthropic":return createAnthropic({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t);case "openai-compatible":{if(!e.baseURL)throw new Error("openai-compatible provider requires baseURL");return createOpenAICompatible({name:e.clientName,baseURL:e.baseURL,apiKey:e.apiKey})(t)}case "google":return createGoogleGenerativeAI({baseURL:e.baseURL||void 0,apiKey:e.apiKey})(t)}},"buildModel");var k=new AsyncLocalStorage,he=r(()=>k.getStore()?.runId,"getCurrentRunId");var M=r(e=>{if(!e?.length)return "(no prior conversation)";let t=e.slice(-8),n=e.length-t.length,o=[];n>0&&o.push(`(${n} earlier turns omitted)`);for(let s of t){let i=s.content.length>1500?`${s.content.slice(0,1500)}... [truncated]`:s.content;o.push(`${s.role}: ${i}`);}return o.join(`
3
- `)},"renderHistory"),fe={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},q=r((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:n,descChars:o}=fe[t],s=e.slice(0,n),i=e.length-s.length,u=s.map(c=>{let a=(c.description||"").replace(/\s+/g," ").trim().slice(0,o);return `- ${c.name}: ${a}`});return i>0&&u.push(`... and ${i} more tools`),u.join(`
4
- `)},"renderToolCatalog"),O=1500,ye=r(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t.length>O?`${t.slice(0,O)}... [truncated, ${t.length-O} chars]`:t},"truncateOutput"),we=r((e,t)=>{let n=e.toolCalls.length?e.toolCalls.map(o=>` - ${o.name} ${o.ok?"ok":"fail"}: ${ye(o.output)}`).join(`
1
+ 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,streamText,stepCountIs,streamObject,generateObject}from'ai';import {randomUUID}from'crypto';import {writeFile,mkdir,rm}from'fs/promises';import ve from'path';import {URL}from'url';import {AsyncLocalStorage}from'async_hooks';import {trace,SpanStatusCode}from'@opentelemetry/api';import {createAnthropic}from'@ai-sdk/anthropic';import {createGoogleGenerativeAI}from'@ai-sdk/google';import {createOpenAI}from'@ai-sdk/openai';import {createOpenAICompatible}from'@ai-sdk/openai-compatible';import {tmpdir}from'os';import {z as z$1}from'zod';var xe=Object.defineProperty;var s=(e,t)=>xe(e,"name",{value:t,configurable:true});var K={version:"0.0.3"};var j=new 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=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: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]=dynamicTool({description:f,inputSchema: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?{...getDefaultEnvironment(),...g.env}:void 0;v=new 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 StreamableHTTPClientTransport(new 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 Client({name:n,version:Ve});await w.connect(v),d.set(m,w),r&&w.setNotificationHandler(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=randomUUID().slice(0,8),i=ve.join(r,`${n}-${u}-${p}${d}`),c=Buffer.from(e,"base64");return await 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=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 createOpenAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "anthropic":return createAnthropic({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model);case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");return createOpenAICompatible({name:e,baseURL:t.baseURL,apiKey:t.apiKey})(t.model)}case "google":return createGoogleGenerativeAI({baseURL:t.baseURL||void 0,apiKey:t.apiKey})(t.model)}},"buildModelFromStage");var 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
5
  `):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",n].join(`
6
- `)},"renderTraceEntry"),$=r(e=>e.length===0?"(no steps executed yet)":e.map(we).join(`
7
- `),"renderTrace"),N=r(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,n)=>` ${n+1}. [${t.id}] ${t.description}
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
8
  expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
9
9
  suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
10
- `),"renderPlan"),H=`You are the Planner of a multi-step agent system.
10
+ `),"renderPlan"),_=s((e,t)=>t?`${e}
11
+
12
+ Domain context:
13
+ ${t}`:e,"withDomainContext"),le=`You are the Planner of a multi-step agent system.
11
14
 
12
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.
13
16
 
@@ -17,28 +20,28 @@ Rules:
17
20
  3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
18
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.
19
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).
20
- 6. Output strict JSON matching the requested schema. No prose outside JSON.`,Ie=`
23
+ 6. Output strict JSON matching the requested schema. No prose outside JSON.`,it=`
21
24
 
22
25
  ADDITIONAL RULE (tool-narrowed mode):
23
- The agent narrows the active tool set per-step using suggestedTools. You MUST set suggestedTools to the EXACT tool names the executor will use for that step. If a step is reasoning-only and needs no tools, leave suggestedTools empty. Missing or wrong suggestedTools will leave the executor without the tools it needs.`,U=r(e=>e==="compact"?H+Ie:H,"buildPlannerSystem"),B=r((e,t,n,o="full")=>[n?.length?`Conversation history:
24
- ${M(n)}
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)}
25
28
  `:"",`User request:
26
29
  ${e}`,"",`Available tools:
27
- ${q(t,o)}`,"","Produce the plan now."].filter(Boolean).join(`
28
- `),"buildPlannerUserPrompt"),L=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
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.
29
32
 
30
33
  Rules:
31
34
  1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
32
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.
33
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.
34
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.
35
- 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,K=r((e,t,n,o,s)=>[s?.length?`Conversation history:
36
- ${M(s)}
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)}
37
40
  `:"",`Original user request:
38
41
  ${e}`,"",`Overall plan:
39
- ${N(t)}`,"",`Trace so far:
40
- ${$(o)}`,"",`CURRENT STEP to execute (id=${n.id}): ${n.description}`,`Expected outcome: ${n.expectedOutcome}`,n.suggestedTools?.length?`Suggested tools: ${n.suggestedTools.join(", ")}`:"","","Execute this step now. Reply with a concise summary of what you found / did - the system uses your full reply as the step result."].filter(Boolean).join(`
41
- `),"buildExecutorUserPrompt"),W=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
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.
42
45
 
43
46
  You have three options:
44
47
  - "continue": the next planned step is still appropriate.
@@ -49,27 +52,21 @@ Rules:
49
52
  1. Prefer "continue" when the original plan still applies. Revise only when needed.
50
53
  2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
51
54
  3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
52
- 4. Output strict JSON matching the schema. No prose outside JSON.`,G=r((e,t,n,o,s,i="full")=>[`Original user request:
55
+ 4. Output strict JSON matching the schema. No prose outside JSON.`,fe=s((e,t,n,o,r,a="full")=>[`Original user request:
53
56
  ${e}`,"",`Current plan:
54
- ${N(t)}`,"",`Completed steps:
55
- ${$(n)}`,"",o?`Next planned step: [${o.id}] ${o.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
56
- ${q(s,i)}`,"","Decide now: continue, revise, or finish."].join(`
57
- `),"buildReplannerUserPrompt"),F=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
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.
58
61
 
59
62
  Rules:
60
63
  1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
61
64
  2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
62
65
  3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
63
- 4. Use the user's language.`,J=r((e,t,n,o)=>[o?.length?`Conversation history:
64
- ${M(o)}
66
+ 4. Use the user's language.`,ye=s((e,t,n,o)=>[o?.length?`Conversation history:
67
+ ${X(o)}
65
68
  `:"",`User request:
66
69
  ${e}`,"",`Plan that was executed:
67
- ${N(t)}`,"",`Execution trace:
68
- ${$(n)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
69
- `),"buildSynthesizerUserPrompt");var X=r((e,t=new Set)=>{if(!e||typeof e!="object"||t.has(e))return false;t.add(e);let n=e;if(n.name==="AbortError")return false;let o=n.statusCode??n.status;return typeof o=="number"?o===429||o>=500:n.name==="TypeError"?true:n.cause&&typeof n.cause=="object"?X(n.cause,t):false},"isRetriable"),R=r(async(e,t)=>{let n=t.baseDelayMs??500,o;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(o=i,s===t.maxRetries||!X(i))throw i;t.onRetry?.(s+1,i);let u=n*2**s+Math.random()*250;await Te(u,t.signal);}}throw o},"withRetry"),Te=r((e,t)=>new Promise((n,o)=>{if(t?.aborted){o(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",i),n();},e),i=r(()=>{clearTimeout(s),o(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),be=r(e=>{let t=e.filter(n=>!!n);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),C=r((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:be([e,AbortSignal.timeout(t)]),"withTimeout"),Se=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),Re=r(e=>{if(!e)return e;let t={};for(let[n,o]of Object.entries(e))t[n]=Se.has(n.toLowerCase())?"***redacted***":o;return t},"redactHeaders");var Ae=r((e,t)=>{if(e.config.toolSelectionStrategy!=="plan-narrowed")return e.tools;let n=new Set(t.suggestedTools??[]);if(n.size===0)return t.requiresTools?e.tools:{};let o={};for(let s of n){let i=e.tools[s];i&&(o[s]=i);}return o},"buildActiveToolSet"),V="[BLOCKER]",ve=r(e=>{let t=e.indexOf(V);return t===-1?{summary:e,blocked:false}:{summary:(e.slice(0,t)+e.slice(t+V.length)).trim(),blocked:true}},"splitBlockerSentinel"),j=4e3,ke=r(e=>e.length>j?`${e.slice(0,j)}... [truncated, ${e.length-j} chars]`:e,"truncateForTrace"),Z=r(async(e,t,n,o,s,i,u)=>{let c=Date.now(),a=await R(()=>Ee(e,t,n,o,s,i,u),{maxRetries:i.config.llmMaxRetries??2,signal:u,onRetry:r((p,d)=>i.emit({type:"retry",phase:"execute",attempt:p,error:d.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:a.usage}),{step:n,summary:a.summary,toolCalls:a.toolCalls,durationMs:Date.now()-c,blocked:a.blocked}},"executeStep"),Ee=r(async(e,t,n,o,s,i,u)=>{let c=[],a=new Map,p=Ae(i,n),d=i.config.toolSelectionStrategy==="plan-narrowed",g=streamText({model:i.executorModel,tools:p,...d?{activeTools:Object.keys(p)}:{},stopWhen:stepCountIs(i.config.maxStepsPerTask),system:i.config.systemPrompt?`${L}
70
-
71
- Domain context:
72
- ${i.config.systemPrompt}`:L,prompt:K(e,t,n,o,s),abortSignal:C(u,i.config.llmTimeoutMs??0)});for await(let l of g.fullStream)switch(l.type){case "text-delta":l.text&&i.emit({type:"step.text-delta",step:n,delta:l.text});break;case "tool-call":{a.set(l.toolCallId,{name:l.toolName,input:l.input}),i.emit({type:"step.tool-call",step:n,name:l.toolName,input:l.input});break}case "tool-result":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.output,ok:true}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.output,ok:true}),a.delete(l.toolCallId);break}case "tool-error":{let f=a.get(l.toolCallId);c.push({name:l.toolName,input:f?.input??l.input,output:l.error,ok:false}),i.emit({type:"step.tool-result",step:n,name:l.toolName,output:l.error,ok:false}),a.delete(l.toolCallId);break}case "error":{let f=l.error;throw f instanceof Error?f:new Error(String(f))}}let[y,I]=await Promise.all([g.text,g.usage]),{summary:w,blocked:m}=ve(y.trim());return {summary:w.length>0?ke(w):c.length>0?`Executed ${c.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:c,blocked:m,usage:{inputTokens:I.inputTokens??0,outputTokens:I.outputTokens??0,totalTokens:I.totalTokens??0}}},"runOnce");var Oe=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")}),D=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array(Oe).min(1).max(8)}),Q=r(async(e,t,n,o)=>{let s=new Set(n.toolCatalog.map(a=>a.name)),i=n.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:u,usage:c}=await R(()=>Me(e,t,i,n,o),{maxRetries:n.config.llmMaxRetries??2,signal:o,onRetry:r((a,p)=>n.emit({type:"retry",phase:"plan",attempt:a,error:p.message}),"onRetry")});return n.emit({type:"usage",phase:"plan",usage:c}),{thought:u.thought,steps:u.steps.map(a=>{if(!a.suggestedTools?.length)return a;let p=a.suggestedTools.filter(g=>s.has(g)),d=a.suggestedTools.length-p.length;return d>0&&n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had ${d} unknown suggestedTools, stripped`}),p.length===0?(n.emit({type:"log",level:"warn",message:`[plan] step "${a.id}" had no valid suggestedTools left; falling back to full toolset`}),{...a,suggestedTools:void 0,requiresTools:true}):{...a,suggestedTools:p}})}},"createInitialPlan"),Me=r(async(e,t,n,o,s)=>{let i=streamObject({model:o.plannerModel,schema:D,system:o.config.systemPrompt?`${U(n)}
73
-
74
- Domain context:
75
- ${o.config.systemPrompt}`:U(n),prompt:B(e,o.toolCatalog,t,n),abortSignal:C(s,o.config.llmTimeoutMs??0)}),u="",c=false;for await(let d of i.partialObjectStream){let g=d?.thought;typeof g!="string"||g===u||(g.startsWith(u)?o.emit({type:"plan.thought-delta",delta:g.slice(u.length)}):c||(o.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),c=true),u=g);}let[a,p]=await Promise.all([i.object,i.usage]);return {object:a,usage:{inputTokens:p.inputTokens??0,outputTokens:p.outputTokens??0,totalTokens:p.totalTokens??0}}},"streamPlanOnce");var Ne=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:D.describe("Plan covering ONLY the remaining work")})]),ee=r(async(e,t,n,o,s,i)=>{let u=s.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:c,usage:a}=await R(async()=>{let p=await generateObject({model:s.plannerModel,schema:Ne,system:W,prompt:G(e,t,n,o,s.toolCatalog,u),abortSignal:C(i,s.config.llmTimeoutMs??0)}),d={inputTokens:p.usage.inputTokens??0,outputTokens:p.usage.outputTokens??0,totalTokens:p.usage.totalTokens??0};return {object:p.object,usage:d}},{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((p,d)=>s.emit({type:"retry",phase:"replan",attempt:p,error:d.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:a}),c},"decideNextAction");var te=r(async(e,t,n,o,s,i)=>{let{text:u,usage:c}=await R(()=>Le(e,t,n,o,s,i),{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((a,p)=>s.emit({type:"retry",phase:"synthesize",attempt:a,error:p.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:c}),u},"synthesizeAnswer"),Le=r(async(e,t,n,o,s,i)=>{let u=streamText({model:s.synthesizerModel,system:F,prompt:J(e,t,n,o),abortSignal:C(i,s.config.llmTimeoutMs??0)});for await(let p of u.fullStream)if(p.type==="text-delta")p.text&&s.emit({type:"final.text-delta",delta:p.text});else if(p.type==="error"){let d=p.error;throw d instanceof Error?d:new Error(String(d))}let[c,a]=await Promise.all([u.text,u.usage]);return {text:c,usage:{inputTokens:a.inputTokens??0,outputTokens:a.outputTokens??0,totalTokens:a.totalTokens??0}}},"streamOnce");var De=r(e=>!!(e.blocked||e.toolCalls.some(t=>!t.ok)),"shouldCallReplanner"),_e=r(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),ne=r(async(e,t)=>{let n=randomUUID();return k.run({runId:n,startedAt:Date.now()},()=>Ye(e,t))},"runAgentLoop"),Ye=r(async(e,t)=>{let{input:n,signal:o}=t,s=t.history?[...t.history]:void 0,i=t.onEvent??(()=>{}),u={inputTokens:0,outputTokens:0,totalTokens:0},c={...e,emit:r(l=>{l.type==="usage"&&(u.inputTokens+=l.usage.inputTokens,u.outputTokens+=l.usage.outputTokens,u.totalTokens+=l.usage.totalTokens);let f={...l,runId:k.getStore()?.runId};try{i(f);}catch{}try{e.emit(f);}catch{}},"emit")},a;try{a=await Q(n,s,c,o);}catch(l){if(c.emit({type:"error",error:E(l),phase:"plan"}),_e(l)||o?.aborted)throw l;a={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}c.emit({type:"plan.created",plan:a});let p=[],d=a,g=0,y=0,I=0,w=e.config.maxRevisions??2,m=e.config.maxTotalTokens;for(;y<e.config.maxIterations;){if(y++,o?.aborted)throw new DOMException("Aborted","AbortError");if(g>=d.steps.length)break;if(m&&u.totalTokens>=m){c.emit({type:"budget.exceeded",tokens:u.totalTokens,cap:m});break}let l=d.steps[g];c.emit({type:"step.start",step:l,index:g});let f;try{f=await Z(n,d,l,p,s,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"execute"}),A}p.push(f),c.emit({type:"step.complete",step:l,result:f});let x=d.steps[g+1]??null;if(x===null){c.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!De(f)){c.emit({type:"replan.decision",mode:"continue",reason:"step succeeded cleanly, skipping LLM replanner",cause:"clean-step"}),g++;continue}let T;try{T=await ee(n,d,p,x,c,o);}catch(A){throw c.emit({type:"error",error:E(A),phase:"replan"}),A}if(c.emit({type:"replan.decision",mode:T.mode,reason:T.reason,cause:"llm-decision"}),T.mode==="finish")break;if(T.mode==="revise"){if(I>=w){c.emit({type:"revisions.exceeded",cap:w});break}I++,d=T.newPlan,c.emit({type:"plan.revised",plan:d,reason:T.reason}),g=0;continue}g++;}let h;try{h=await te(n,d,p,s,c,o);}catch(l){throw c.emit({type:"error",error:E(l),phase:"synthesize"}),l}return c.emit({type:"final",text:h}),{text:h,plan:d,trace:p,iterations:y,usage:u}},"runAgentLoopInner"),E=r(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var P={none:0,error:1,warn:2,info:3,debug:4},zt=r(async(e,t)=>{let n=P[e.logLevel]>=P.debug,o=r(m=>{if(t)try{t(m);}catch(h){n&&console.error("[agent] event handler threw:",h);}},"emit"),s=r((m,h)=>{P[e.logLevel]>=P[m]&&o({type:"log",level:m,message:h});},"log"),i=r(async()=>{let m=await Y(e.mcpServers,s,e.clientName,e.outputSanitizer),h=z(m.tools,m.catalog,e.availableTools,e.excludedTools);return {connection:m,tools:h.tools,catalog:h.catalog}},"connect"),u;try{u=await i();}catch(m){throw o({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let c=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&c>0&&!u.connection.results.some(h=>h.connected)){let h=u.connection.results.filter(f=>!f.connected).map(f=>`${f.name}: ${f.error??"unknown"}`).join("; ");await u.connection.close().catch(()=>{});let l=new Error(`All ${c} configured MCP server(s) failed to connect [${h}]`);throw o({type:"error",error:l,phase:"init"}),l}let a=v(e,e.model),p=v(e,e.plannerModel??e.model),d=v(e,e.synthesizerModel??e.model),g={config:e,executorModel:a,plannerModel:p,synthesizerModel:d,tools:u.tools,toolCatalog:u.catalog.map(m=>({name:m.name,description:m.description})),emit:o},y=0,I=false,w=false;return {run:r(async m=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Agent is reconnecting; retry shortly");y++;try{return await ne(g,m)}finally{y--;}},"run"),listTools:r(()=>g.toolCatalog.slice(),"listTools"),reconnect:r(async()=>{if(I)throw new Error("Agent is closed");if(w)throw new Error("Already reconnecting");if(y>0)throw new Error(`Cannot reconnect with ${y} active run(s)`);w=true;try{let m=u.connection,h=await i();for(let l of Object.keys(g.tools))delete g.tools[l];Object.assign(g.tools,h.tools),g.toolCatalog=h.catalog.map(l=>({name:l.name,description:l.description})),u=h,await m.close().catch(()=>{});}finally{w=false;}},"reconnect"),close:r(async m=>{I=true;let h=m?.waitForRuns??false,l=m?.timeoutMs??3e4;if(h&&y>0){let f=Date.now();for(;y>0&&Date.now()-f<l;)await new Promise(x=>setTimeout(x,50));}y>0&&o({type:"log",level:"warn",message:`[agent] close called with ${y} active run(s); they will fail mid-flight`}),await u.connection.close().catch(()=>{});},"close"),activeRuns:r(()=>y,"activeRuns")}},"createAgent");export{zt as createAgent,he as getCurrentRunId,Re as redactHeaders};
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=streamText({model:a.executorModel,tools:i,...c?{activeTools:Object.keys(i)}:{},stopWhen: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=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")}),ne=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.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=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=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: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 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=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.join(tmpdir(),"agent-sandbox");return ve.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??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 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");export{eo as createAgent,Pe as getCurrentRunId,G as getCurrentRunSandbox,pt as redactHeaders};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "type": "module",
5
5
  "description": "Tool-using planning agent over MCP servers, built on the Vercel AI SDK.",
6
6
  "keywords": [
@@ -85,8 +85,9 @@
85
85
  "@ai-sdk/openai": "^2.0.0",
86
86
  "@ai-sdk/openai-compatible": "^1.0.0",
87
87
  "@modelcontextprotocol/sdk": "^1.0.4",
88
+ "@opentelemetry/api": "^1.9.1",
88
89
  "ai": "^5.0.0",
89
- "zod": "^3.23.8"
90
+ "zod": "^4.3.6"
90
91
  },
91
92
  "devDependencies": {
92
93
  "@types/node": "^22.9.0",