@dudko.dev/agent 0.0.20 → 0.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +30 -3
- package/dist/cli.js +46 -46
- package/dist/index.cjs +35 -35
- package/dist/index.d.cts +149 -1
- package/dist/index.d.ts +149 -1
- package/dist/index.js +35 -35
- package/package.json +21 -21
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { OAuthClientProvider } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
2
|
+
import { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
|
|
1
3
|
import { ToolSet } from 'ai';
|
|
4
|
+
import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens } from '@modelcontextprotocol/sdk/shared/auth.js';
|
|
2
5
|
|
|
3
6
|
type ProviderType = 'openai' | 'anthropic' | 'openai-compatible' | 'google' | 'xai' | 'azure' | 'amazon-bedrock' | 'google-vertex' | 'deepseek' | 'gateway' | 'cloudflare';
|
|
4
7
|
type LogLevel = 'none' | 'error' | 'warn' | 'info' | 'debug';
|
|
@@ -7,6 +10,8 @@ interface IMcpHttpServerConfig {
|
|
|
7
10
|
url: string;
|
|
8
11
|
headers?: Record<string, string>;
|
|
9
12
|
getHeaders?: () => Promise<Record<string, string>> | Record<string, string>;
|
|
13
|
+
authProvider?: OAuthClientProvider;
|
|
14
|
+
fetch?: FetchLike;
|
|
10
15
|
}
|
|
11
16
|
interface IMcpStdioServerConfig {
|
|
12
17
|
command: string;
|
|
@@ -216,6 +221,149 @@ declare const getCurrentRunSandbox: () => string | undefined;
|
|
|
216
221
|
|
|
217
222
|
declare const redactHeaders: (headers: Record<string, string> | undefined) => Record<string, string> | undefined;
|
|
218
223
|
|
|
224
|
+
/**
|
|
225
|
+
* OAuth 2.1 for remote MCP servers, from Node.
|
|
226
|
+
*
|
|
227
|
+
* The MCP SDK owns the protocol - discovery (RFC 9728), dynamic client
|
|
228
|
+
* registration (RFC 7591), PKCE, the code exchange and the refresh on 401.
|
|
229
|
+
* What it does not own, and what this module supplies, is WHERE the resulting
|
|
230
|
+
* tokens live between processes and HOW an operator is asked to authorize.
|
|
231
|
+
*
|
|
232
|
+
* Pass the result to `mcpServers[name].authProvider`.
|
|
233
|
+
*/
|
|
234
|
+
/** Where a provider persists tokens, registration and the PKCE verifier. */
|
|
235
|
+
interface IOAuthStore {
|
|
236
|
+
get(key: string): Promise<string | undefined>;
|
|
237
|
+
set(key: string, value: string): Promise<void>;
|
|
238
|
+
delete(key: string): Promise<void>;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* A JSON file, written 0600 in a 0700 directory (tokens are bearer credentials:
|
|
242
|
+
* anything that can read the file can act as the user). Each write goes through
|
|
243
|
+
* a temp file + rename, so a reader never sees a half-written store and a crash
|
|
244
|
+
* cannot lose one.
|
|
245
|
+
*
|
|
246
|
+
* Writes are serialized in-process only. Two PROCESSES sharing one file can
|
|
247
|
+
* still lose an update (both read, both write, the later wins) - the default
|
|
248
|
+
* path is shared, so give each process its own `filePath` when they authorize
|
|
249
|
+
* against different servers concurrently.
|
|
250
|
+
*/
|
|
251
|
+
declare class FileOAuthStore implements IOAuthStore {
|
|
252
|
+
private readonly filePath;
|
|
253
|
+
private queue;
|
|
254
|
+
constructor(filePath?: string);
|
|
255
|
+
private readAll;
|
|
256
|
+
/**
|
|
257
|
+
* Write via a temp file + rename, which is atomic on POSIX. A plain
|
|
258
|
+
* `writeFile` truncates first, so a concurrent reader can see an empty file
|
|
259
|
+
* (and start a whole new authorization), and a crash mid-write loses every
|
|
260
|
+
* token in the store.
|
|
261
|
+
*/
|
|
262
|
+
private writeAll;
|
|
263
|
+
private enqueue;
|
|
264
|
+
get(key: string): Promise<string | undefined>;
|
|
265
|
+
set(key: string, value: string): Promise<void>;
|
|
266
|
+
delete(key: string): Promise<void>;
|
|
267
|
+
}
|
|
268
|
+
/** Non-persistent store: tokens die with the process. */
|
|
269
|
+
declare class MemoryOAuthStore implements IOAuthStore {
|
|
270
|
+
private readonly map;
|
|
271
|
+
get(key: string): Promise<string | undefined>;
|
|
272
|
+
set(key: string, value: string): Promise<void>;
|
|
273
|
+
delete(key: string): Promise<void>;
|
|
274
|
+
}
|
|
275
|
+
interface INodeOAuthProviderOptions {
|
|
276
|
+
/** The MCP endpoint being authorized. */
|
|
277
|
+
serverUrl: string;
|
|
278
|
+
/**
|
|
279
|
+
* Where the authorization server sends the operator back. For a CLI this is
|
|
280
|
+
* usually a loopback URL you listen on (`http://127.0.0.1:PORT/callback`);
|
|
281
|
+
* whatever you pick is what gets registered, so it must match on return.
|
|
282
|
+
*/
|
|
283
|
+
redirectUrl: string;
|
|
284
|
+
/** `client_name` submitted during dynamic registration. */
|
|
285
|
+
clientName?: string;
|
|
286
|
+
/** Fallback scope when the server advertises none. */
|
|
287
|
+
scope?: string;
|
|
288
|
+
/** Merged over the defaults (e.g. `software_id`, `contacts`). */
|
|
289
|
+
clientMetadata?: Partial<OAuthClientMetadata>;
|
|
290
|
+
/** Defaults to a 0600 JSON file under ~/.agent. */
|
|
291
|
+
store?: IOAuthStore;
|
|
292
|
+
/** Treat the access token as expired this many seconds early. Default 30. */
|
|
293
|
+
expirySkewSeconds?: number;
|
|
294
|
+
/**
|
|
295
|
+
* Invoked with the URL the operator must open. Nothing is printed or spawned
|
|
296
|
+
* on your behalf - a library that writes to stdout breaks piped output, and
|
|
297
|
+
* one that opens a browser surprises a server process.
|
|
298
|
+
*/
|
|
299
|
+
onAuthorizationUrl?: (url: URL) => void | Promise<void>;
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* A persistent `OAuthClientProvider`. Also exposes `isAccessTokenExpired`,
|
|
303
|
+
* which `connectMcpServers` uses to refresh a known-dead token before the
|
|
304
|
+
* first request instead of paying for a guaranteed 401.
|
|
305
|
+
*/
|
|
306
|
+
declare class NodeOAuthProvider implements OAuthClientProvider {
|
|
307
|
+
/** Set when an interactive authorization is required. */
|
|
308
|
+
authorizationUrl?: URL;
|
|
309
|
+
readonly serverUrl: string;
|
|
310
|
+
private readonly store;
|
|
311
|
+
private readonly ns;
|
|
312
|
+
private readonly _redirectUrl;
|
|
313
|
+
private readonly _clientMetadata;
|
|
314
|
+
private readonly skewMs;
|
|
315
|
+
private readonly onAuthorizationUrl?;
|
|
316
|
+
constructor(opts: INodeOAuthProviderOptions);
|
|
317
|
+
get redirectUrl(): string;
|
|
318
|
+
get clientMetadata(): OAuthClientMetadata;
|
|
319
|
+
private key;
|
|
320
|
+
private readJSON;
|
|
321
|
+
state(): Promise<string>;
|
|
322
|
+
/** Single-use CSRF check for the value that comes back on the redirect. */
|
|
323
|
+
verifyState(returned: string | undefined): Promise<boolean>;
|
|
324
|
+
clientInformation(): Promise<OAuthClientInformationMixed | undefined>;
|
|
325
|
+
saveClientInformation(info: OAuthClientInformationMixed): Promise<void>;
|
|
326
|
+
tokens(): Promise<OAuthTokens | undefined>;
|
|
327
|
+
saveTokens(tokens: OAuthTokens): Promise<void>;
|
|
328
|
+
saveCodeVerifier(verifier: string): Promise<void>;
|
|
329
|
+
codeVerifier(): Promise<string>;
|
|
330
|
+
redirectToAuthorization(url: URL): Promise<void>;
|
|
331
|
+
/**
|
|
332
|
+
* Called by the SDK when the server rejects what we hold: `'tokens'` on an
|
|
333
|
+
* `invalid_grant` (dead refresh token), `'client'` / `'all'` on an
|
|
334
|
+
* `invalid_client` (the AS forgot our dynamic registration).
|
|
335
|
+
*/
|
|
336
|
+
invalidateCredentials(scope: 'all' | 'client' | 'tokens' | 'verifier'): Promise<void>;
|
|
337
|
+
/** True when there is no access token, or it expires within the skew window. */
|
|
338
|
+
isAccessTokenExpired(): Promise<boolean>;
|
|
339
|
+
isAuthorized(): Promise<boolean>;
|
|
340
|
+
/** Forget tokens, registration, verifier and state for this server. */
|
|
341
|
+
reset(): Promise<void>;
|
|
342
|
+
}
|
|
343
|
+
/** Convenience factory mirroring the rest of the package's `createX` style. */
|
|
344
|
+
declare const createNodeOAuthProvider: (opts: INodeOAuthProviderOptions) => NodeOAuthProvider;
|
|
345
|
+
interface IOAuthRequestOptions {
|
|
346
|
+
/** Custom fetch for discovery / registration / token requests. */
|
|
347
|
+
fetch?: FetchLike;
|
|
348
|
+
}
|
|
349
|
+
/**
|
|
350
|
+
* Start (or silently renew) an authorization. `'AUTHORIZED'` means a usable
|
|
351
|
+
* token is in hand - possibly obtained by exchanging a refresh token without
|
|
352
|
+
* bothering anyone. `'REDIRECT'` means the operator must visit
|
|
353
|
+
* `provider.authorizationUrl` and the code has to come back through
|
|
354
|
+
* {@link finishMcpOAuth}.
|
|
355
|
+
*/
|
|
356
|
+
declare const beginMcpOAuth: (provider: NodeOAuthProvider, opts?: IOAuthRequestOptions) => Promise<"AUTHORIZED" | "REDIRECT">;
|
|
357
|
+
/**
|
|
358
|
+
* Complete the flow with the `code` (and `state`) the authorization server sent
|
|
359
|
+
* back. Verifies `state`, exchanges the code with the stored PKCE verifier and
|
|
360
|
+
* persists the tokens. Throws unless the exchange fully succeeded.
|
|
361
|
+
*/
|
|
362
|
+
declare const finishMcpOAuth: (provider: NodeOAuthProvider, callback: {
|
|
363
|
+
code: string;
|
|
364
|
+
state?: string;
|
|
365
|
+
}, opts?: IOAuthRequestOptions) => Promise<void>;
|
|
366
|
+
|
|
219
367
|
interface ICloseOptions {
|
|
220
368
|
waitForRuns?: boolean;
|
|
221
369
|
timeoutMs?: number;
|
|
@@ -232,4 +380,4 @@ interface IAgent {
|
|
|
232
380
|
}
|
|
233
381
|
declare const createAgent: (config: IAgentConfig, baseEventHandler?: EventHandler) => Promise<IAgent>;
|
|
234
382
|
|
|
235
|
-
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 ReplanTrigger, type ToolSelectionStrategy, createAgent, getCurrentRunId, getCurrentRunSandbox, redactHeaders };
|
|
383
|
+
export { type AgentEvent, type EventHandler, FileOAuthStore, type IAgent, type IAgentConfig, type IAgentRunOptions, type IAgentRunResult, type IAgentStageOverride, type ICloseOptions, type IConversationTurn, type IMcpHttpServerConfig, type IMcpServerConfig, type IMcpStdioServerConfig, type INodeOAuthProviderOptions, type IOAuthRequestOptions, type IOAuthStore, type IPersistence, type IPlan, type IPlanStep, type IRunSnapshot, type IStepResult, type IStepStartInfo, type IUsage, type LogLevel, MemoryOAuthStore, NodeOAuthProvider, type ProviderType, type ReplanCause, type ReplanTrigger, type ToolSelectionStrategy, beginMcpOAuth, createAgent, createNodeOAuthProvider, finishMcpOAuth, getCurrentRunId, getCurrentRunSandbox, redactHeaders };
|
package/dist/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
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 Ae from'path';import {URL}from'url';import {AsyncLocalStorage}from'async_hooks';import {trace,SpanStatusCode}from'@opentelemetry/api';import {tmpdir}from'os';import {z as z$1}from'zod';var Pe=Object.defineProperty;var s=(e,t)=>Pe(e,"name",{value:t,configurable:true});var H={version:"0.0.20"};var z=new AsyncLocalStorage,Le=s(()=>z.getStore()?.runId,"getCurrentRunId"),W=s(()=>z.getStore()?.sandboxDir,"getCurrentRunSandbox");var Ne="@dudko.dev/agent",_e=H.version,J,De=s(()=>(J||(J=trace.getTracer(Ne,_e)),J),"tracer"),v={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"},O=s(async(e,t,o)=>De().startActiveSpan(e,async n=>{for(let[r,a]of Object.entries(t))a!==void 0&&n.setAttribute(r,a);try{let r=await o(n);return n.end(),r}catch(r){let a=r instanceof Error?r:new Error(String(r));throw n.recordException(a),n.setStatus({code:SpanStatusCode.ERROR,message:a.message}),n.end(),r}}),"withSpan");var Xe=s(e=>"command"in e&&!!e.command,"isStdioConfig"),Ze=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Qe=H.version,se=64,le=s(async(e,t,o,n,r,a)=>{let d=new Map,p={},l=[],c=[],i=s(async(m,h)=>{for(let b of Object.keys(p))b.startsWith(`${m}__`)&&delete p[b];for(let b=l.length-1;b>=0;b--)l[b].server===m&&l.splice(b,1);let w=await h.listTools(),f=0,I=0;for(let b of w.tools){let R=`${m}__${b.name}`;if(R.length>se){t("warn",`[mcp] ${m}: tool "${b.name}" prefixed name (${R.length} chars) exceeds the ${se}-char limit enforced by major LLM providers; skipping`),I++;continue}let y=b.description??"";p[R]=dynamicTool({description:y,inputSchema:jsonSchema(b.inputSchema),execute:s(async(E,x)=>O("agent.tool_call",{[v.TOOL_NAME]:R},async u=>{let T=E??{};if(a)try{let k=await a(R,T);T=k&&typeof k=="object"&&!Array.isArray(k)?k:{value:k};}catch(k){t("warn",`[mcp] ${R}: inputSanitizer threw - ${k.message}; input replaced with placeholder`),T={_redacted:"inputSanitizer failed"};}let S;try{S=await h.callTool({name:b.name,arguments:T},void 0,x?.abortSignal?{signal:x.abortSignal}:void 0);}catch(k){throw u.setAttribute(v.TOOL_OK,false),k}let g=S.content;if(n)try{g=await n(R,g);}catch(k){return t("warn",`[mcp] ${R}: outputSanitizer threw - ${k.message}; output replaced with placeholder`),u.setAttribute(v.TOOL_OK,false),"[output redacted: sanitizer failed]"}let A=await ot(g,{toolName:R,sandboxDir:W()});return u.setAttribute(v.TOOL_OK,true),A}),"execute")}),l.push({name:R,description:y,server:m}),f++;}I>0?t("info",`[mcp] ${m}: ${f} tools mounted, ${I} skipped (length cap)`):t("info",`[mcp] ${m}: ${f} tools mounted`);},"registerServerTools");for(let[m,h]of Object.entries(e))try{let w;if(Xe(h)){let I=h.env?{...getDefaultEnvironment(),...h.env}:void 0;w=new StdioClientTransport({command:h.command,args:h.args,env:I,cwd:h.cwd});}else if(Ze(h)){if(h.headers&&h.getHeaders)throw new Error(`MCP server "${m}": specify either headers or getHeaders, not both`);let I=h.getHeaders?await h.getHeaders():h.headers;w=new StreamableHTTPClientTransport(new URL(h.url),{requestInit:I?{headers:I}: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)`);w.onerror=I=>t("warn",`[mcp] ${m}: transport error - ${I.message}`),w.onclose=()=>t("warn",`[mcp] ${m}: transport closed`);let f=new Client({name:o,version:Qe});await f.connect(w),d.set(m,f),r&&f.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(m);}),await i(m,f),c.push({name:m,connected:!0});}catch(w){let f=w.message;t("error",`[mcp] ${m}: failed to connect - ${f}`),c.push({name:m,connected:false,error:f});}return {tools:p,catalog:l,results:c,close:s(async()=>{await Promise.allSettled([...d.values()].map(m=>m.close()));},"close"),refreshServer:s(async m=>{let h=d.get(m);if(!h)throw new Error(`MCP server "${m}" is not connected`);await i(m,h);},"refreshServer")}},"connectMcpServers"),ae={image:".bin",audio:".bin",resource:".bin"},et=s((e,t)=>{if(!e)return ae[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?ae[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"),tt=/[^a-zA-Z0-9_-]/g,ie=s(async(e,t,o,n,r,a)=>{await a();let d=et(t,o),p=n.replace(tt,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),c=Ae.join(r,`${o}-${p}-${l}${d}`),i=Buffer.from(e,"base64");return await writeFile(c,i),{type:"file",kind:o,path:c,mimeType:t,bytes:i.byteLength}},"spillBase64"),ot=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(c=>c?.type==="text"&&typeof c.text=="string"))return o.map(c=>c.text).join(`
|
|
2
|
-
`);let r=
|
|
3
|
-
`)},"renderHistory"),
|
|
4
|
-
`)},"renderToolCatalog"),
|
|
5
|
-
`):" (no tool calls)";return [`Step ${
|
|
6
|
-
`)},"renderTraceEntry"),
|
|
7
|
-
`),"renderTrace"),
|
|
8
|
-
expected: ${
|
|
9
|
-
suggested tools: ${
|
|
10
|
-
`),"renderPlan"),
|
|
1
|
+
import {auth,UnauthorizedError}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {dynamicTool,jsonSchema,streamText,stepCountIs,streamObject,generateObject}from'ai';import {randomBytes,randomUUID}from'crypto';import {readFile,writeFile,chmod,rename,mkdir,rm}from'fs/promises';import we from'path';import {URL as URL$1}from'url';import {AsyncLocalStorage}from'async_hooks';import Qe,{tmpdir}from'os';import {trace,SpanStatusCode}from'@opentelemetry/api';import {z as z$1}from'zod';var qe=Object.defineProperty;var s=(t,e)=>qe(t,"name",{value:e,configurable:true});var W={version:"0.0.23"};var F=new AsyncLocalStorage,Ye=s(()=>F.getStore()?.runId,"getCurrentRunId"),ne=s(()=>F.getStore()?.sandboxDir,"getCurrentRunSandbox");var et=we.join(Qe.homedir(),".agent","mcp-oauth.json"),V=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(e=et){this.filePath=e;}async readAll(){try{let e=JSON.parse(await readFile(this.filePath,"utf8"));return !e||typeof e!="object"||Array.isArray(e)?{}:e}catch{return {}}}async writeAll(e){let o=`${this.filePath}.${process.pid}.tmp`;await writeFile(o,JSON.stringify(e,null,2),{mode:384}),await chmod(o,384).catch(()=>{}),await rename(o,this.filePath);}enqueue(e){let o=this.queue.then(e,e);return this.queue=o.catch(()=>{}),o}async get(e){return this.enqueue(async()=>(await this.readAll())[e])}async set(e,o){await this.enqueue(async()=>{let n=await this.readAll();n[e]=o,await mkdir(we.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(e){await this.enqueue(async()=>{let o=await this.readAll();e in o&&(delete o[e],await this.writeAll(o));});}},re=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(e){return this.map.get(e)}async set(e,o){this.map.set(e,o);}async delete(e){this.map.delete(e);}},tt=30,ot=s(t=>{let e=new URL(t);return `mcp-oauth:${e.origin}${e.pathname.replace(/\/+$/,"")}${e.search}`},"namespaceFor"),nt=new Set(["localhost","127.0.0.1","[::1]","::1"]),se=s((t,e="MCP OAuth")=>{let o;try{o=new URL(t);}catch{throw new Error(`${e}: "${t}" is not a valid URL`)}if(!(o.protocol==="https:"||nt.has(o.hostname)))throw new Error(`${e}: requires https (or a loopback host) - refusing to send tokens to "${t}"`)},"assertSecureOAuthUrl"),X=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(e){this.serverUrl=e.serverUrl,this.store=e.store??new V,this.ns=ot(e.serverUrl),this._redirectUrl=e.redirectUrl,this.skewMs=(e.expirySkewSeconds??tt)*1e3,this.onAuthorizationUrl=e.onAuthorizationUrl,this._clientMetadata={client_name:e.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...e.scope?{scope:e.scope}:{},...e.clientMetadata},se(e.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(e){return `${this.ns}:${e}`}async readJSON(e){let o=await this.store.get(this.key(e));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(e));return}}async state(){let e=randomBytes(32).toString("hex");return await this.store.set(this.key("state"),e),e}async verifyState(e){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&e!==void 0&&o===e}async clientInformation(){return this.readJSON("client")}async saveClientInformation(e){await this.store.set(this.key("client"),JSON.stringify(e));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(e){let o={tokens:e,expiresAt:typeof e.expires_in=="number"?Date.now()+e.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(e){await this.store.set(this.key("verifier"),e);}async codeVerifier(){let e=await this.store.get(this.key("verifier"));if(!e)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return e}async redirectToAuthorization(e){this.authorizationUrl=e,await this.onAuthorizationUrl?.(e);}async invalidateCredentials(e){let o=e==="all"?["tokens","client","verifier","state"]:[e];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let e=await this.readJSON("tokens");return e?.tokens?.access_token?e.expiresAt===void 0?false:Date.now()+this.skewMs>=e.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},rt=s(t=>new X(t),"createNodeOAuthProvider"),st=s(async(t,e={})=>(t.authorizationUrl=void 0,auth(t,{serverUrl:t.serverUrl,fetchFn:e.fetch})),"beginMcpOAuth"),it=s(async(t,e,o={})=>{if(!await t.verifyState(e.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth(t,{serverUrl:t.serverUrl,authorizationCode:e.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var ct="@dudko.dev/agent",dt=W.version,ie,pt=s(()=>(ie||(ie=trace.getTracer(ct,dt)),ie),"tracer"),k={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"},U=s(async(t,e,o)=>pt().startActiveSpan(t,async n=>{for(let[r,a]of Object.entries(e))a!==void 0&&n.setAttribute(r,a);try{let r=await o(n);return n.end(),r}catch(r){let a=r instanceof Error?r:new Error(String(r));throw n.recordException(a),n.setStatus({code:SpanStatusCode.ERROR,message:a.message}),n.end(),r}}),"withSpan");var Rt=s(t=>"command"in t&&!!t.command,"isStdioConfig"),Et=s(t=>"url"in t&&!!t.url,"isHttpConfig"),xt=W.version,ae=64,B=s(t=>t.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),Pt=s((t,e)=>{if(!e[t])return t;for(let o=2;o<100;o++){let n=`_${o}`,r=t.slice(0,ae-n.length)+n;if(!e[r])return r}return ""},"uniqueKey"),Z=class extends Error{static{s(this,"McpToolError");}constructor(e){super(e),this.name="McpToolError";}toJSON(){return this.message}},q=class extends Error{static{s(this,"RefreshOnlyAbort");}},Ot=s(t=>({get redirectUrl(){return t.redirectUrl},get clientMetadata(){return t.clientMetadata},clientInformation:s(()=>t.clientInformation(),"clientInformation"),saveClientInformation:t.saveClientInformation?.bind(t),tokens:s(()=>t.tokens(),"tokens"),saveTokens:s(e=>t.saveTokens(e),"saveTokens"),invalidateCredentials:t.invalidateCredentials?.bind(t),addClientAuthentication:t.addClientAuthentication?.bind(t),validateResourceURL:t.validateResourceURL?.bind(t),codeVerifier:s(()=>t.codeVerifier(),"codeVerifier"),state:s(()=>{throw new q},"state"),saveCodeVerifier:s(()=>{throw new q},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new q},"redirectToAuthorization")}),"refreshOnly"),Ct=s(async(t,e,o,n,r)=>{let a=t.isAccessTokenExpired;if(!(typeof a!="function"||!await a.call(t)||!(await t.tokens())?.refresh_token))try{await auth(Ot(t),{serverUrl:e,fetchFn:o});}catch(d){n("info",d instanceof q?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${d.message}); continuing`);}},"refreshIfExpired"),Se=s(async(t,e,o,n,r,a)=>{let g=new Map,d={},l=[],c=[],i=new Map,w=s((p,h,R)=>{let f=`${B(p)}__`;for(let y of i.get(p)??[])delete d[y];for(let y=l.length-1;y>=0;y--)l[y].server===p&&l.splice(y,1);let b=[],E=0,m=0;for(let y of R){let S=f+B(y.name);if(S.length>ae){e("warn",`[mcp] ${p}: tool "${y.name}" prefixed name (${S.length} chars) exceeds the ${ae}-char limit enforced by major LLM providers; skipping`),m++;continue}let u=Pt(S,d);if(!u){e("warn",`[mcp] ${p}: no free name left for tool "${y.name}"; skipping`),m++;continue}u!==S&&e("warn",`[mcp] ${p}: tool name "${S}" already taken; mounted as "${u}"`);let A=y.description??"";d[u]=dynamicTool({description:A,inputSchema:jsonSchema(y.inputSchema),execute:s(async(C,P)=>U("agent.tool_call",{[k.TOOL_NAME]:u},async $=>{let H=C??{};if(a)try{let O=await a(u,H);H=O&&typeof O=="object"&&!Array.isArray(O)?O:{value:O};}catch(O){e("warn",`[mcp] ${u}: inputSanitizer threw - ${O.message}; input replaced with placeholder`),H={_redacted:"inputSanitizer failed"};}let G;try{G=await h.callTool({name:y.name,arguments:H},void 0,P?.abortSignal?{signal:P.abortSignal}:void 0);}catch(O){throw $.setAttribute(k.TOOL_OK,false),O}let M=G.isError===true,x=G.content;if(n)try{x=await n(u,x);}catch(O){if(e("warn",`[mcp] ${u}: outputSanitizer threw - ${O.message}; output replaced with placeholder`),$.setAttribute(k.TOOL_OK,false),M)throw new Z("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let J=await Mt(x,{toolName:u,sandboxDir:M?void 0:ne()});if(M){$.setAttribute(k.TOOL_OK,false);let O=typeof J=="string"?J:JSON.stringify(J);throw new Z(O&&O!=="[]"?O:`MCP tool "${y.name}" reported an error with no content`)}return $.setAttribute(k.TOOL_OK,true),J}),"execute")}),l.push({name:u,description:A,server:p}),b.push(u),E++;}i.set(p,b),m>0?e("info",`[mcp] ${p}: ${E} tools mounted, ${m} skipped (length cap)`):e("info",`[mcp] ${p}: ${E} tools mounted`);},"mountServerTools"),T=s(async(p,h)=>{w(p,h,(await h.listTools()).tools);},"registerServerTools"),I=s(async(p,h)=>{let R;try{let f;if(Rt(h)){let b=h.env?{...getDefaultEnvironment(),...h.env}:void 0;f=new StdioClientTransport({command:h.command,args:h.args,env:b,cwd:h.cwd});}else if(Et(h)){if(h.headers&&h.getHeaders)throw new Error(`MCP server "${p}": specify either headers or getHeaders, not both`);let b=h.getHeaders?await h.getHeaders():h.headers;h.authProvider&&(b&&"Authorization"in b&&e("warn",`[mcp] ${p}: an explicit Authorization header shadows the OAuth token from authProvider`),se(h.url,`MCP server "${p}"`),await Ct(h.authProvider,h.url,h.fetch,e,p)),f=new StreamableHTTPClientTransport(new URL$1(h.url),{requestInit:b?{headers:b}:void 0,authProvider:h.authProvider,fetch:h.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${p}": config must specify either { url } (HTTP) or { command } (stdio)`);return f.onerror=b=>e("warn",`[mcp] ${p}: transport error - ${b.message}`),f.onclose=()=>e("warn",`[mcp] ${p}: transport closed`),R=new Client({name:o,version:xt}),await R.connect(f),r&&R.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(p);}),{name:p,client:R,listed:(await R.listTools()).tools}}catch(f){R&&await R.close().catch(()=>{});let b=f.message,E=f instanceof UnauthorizedError;return e("error",E?`[mcp] ${p}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${p}: failed to connect - ${b}`),{name:p,error:b,needsAuthorization:E}}},"openConnection"),v=await Promise.all(Object.entries(t).map(([p,h])=>I(p,h)));for(let p of v){if(!p.client||!p.listed){c.push({name:p.name,connected:false,error:p.error,...p.needsAuthorization?{needsAuthorization:true}:{}});continue}g.set(p.name,p.client),w(p.name,p.client,p.listed),c.push({name:p.name,connected:true});}return {tools:d,catalog:l,results:c,close:s(async()=>{await Promise.allSettled([...g.values()].map(p=>p.close()));},"close"),refreshServer:s(async p=>{let h=g.get(p);if(!h)throw new Error(`MCP server "${p}" is not connected`);await T(p,h);},"refreshServer")}},"connectMcpServers"),ve={image:".bin",audio:".bin",resource:".bin"},Ut=s((t,e)=>{if(!t)return ve[e];let o=t.indexOf("/"),r=(o>=0?t.slice(o+1):t).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?ve[e]:{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"),$t=/[^a-zA-Z0-9_-]/g,Te=s(async(t,e,o,n,r,a)=>{await a();let g=Ut(e,o),d=n.replace($t,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),c=we.join(r,`${o}-${d}-${l}${g}`),i=Buffer.from(t,"base64");return await writeFile(c,i),{type:"file",kind:o,path:c,mimeType:e,bytes:i.byteLength}},"spillBase64"),Mt=s(async(t,e)=>{if(!Array.isArray(t))return t;let o=t;if(o.length>0&&o.every(c=>c?.type==="text"&&typeof c.text=="string"))return o.map(c=>c.text).join(`
|
|
2
|
+
`);let r=e?.sandboxDir,a=e?.toolName??"tool",g,d=s(()=>r?(g||(g=mkdir(r,{recursive:true}).then(()=>{})),g):Promise.resolve(),"ensureDir"),l=[];for(let c of o){if(c?.type==="text"&&typeof c.text=="string"){l.push(c.text);continue}if(r&&(c?.type==="image"||c?.type==="audio")&&typeof c.data=="string"){let i=await Te(c.data,typeof c.mimeType=="string"?c.mimeType:void 0,c.type,a,r,d);l.push(i);continue}if(r&&c?.type==="resource"&&c.resource&&typeof c.resource=="object"){let i=c.resource;if(typeof i.blob=="string"){let w=await Te(i.blob,typeof i.mimeType=="string"?i.mimeType:void 0,"resource",a,r,d);typeof i.uri=="string"&&(w.uri=i.uri),l.push(w);continue}if(typeof i.text=="string"){l.push(i.text);continue}}l.push(c);}return l},"flattenContent"),le=s((t,e,o,n,r)=>{let a=o?.length?new Set(o.map(B)):null,g=n?.length?new Set(n.map(B)):null,d=new Set,l={},c=[];for(let i of e){if((a?.has(i.name)||g?.has(i.name))&&d.add(i.name),a&&!a.has(i.name)||!a&&g?.has(i.name))continue;let w=t[i.name];w&&(l[i.name]=w,c.push(i));}if(r)for(let[i,w]of [["availableTools",o],["excludedTools",n]])for(let T of w??[])d.has(B(T))||r("warn",`[mcp] ${i}: "${T}" matches no discovered tool`);return {tools:l,catalog:c}},"filterTools");var Q=s((t,e,o,n)=>{let r=e?.providerType??t.providerType,a=e?.apiKey??t.apiKey,g=e?.baseURL??t.baseURL,d=e?.model??o??t.model,l=e?.providerOptions??t.providerOptions??{};if(e?.providerType&&e.providerType!==t.providerType&&!e.apiKey)throw new Error(`${n}: providerType "${e.providerType}" differs from the default "${t.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(Lt.has(r)&&!g)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:g,apiKey:a,model:d,providerOptions:l}},"resolveStage"),Lt=new Set(["openai-compatible","azure"]),L={openai:"@ai-sdk/openai",anthropic:"@ai-sdk/anthropic",google:"@ai-sdk/google","openai-compatible":"@ai-sdk/openai-compatible",xai:"@ai-sdk/xai",azure:"@ai-sdk/azure","amazon-bedrock":"@ai-sdk/amazon-bedrock","google-vertex":"@ai-sdk/google-vertex",deepseek:"@ai-sdk/deepseek",cloudflare:"workers-ai-provider"},_=s(async t=>{try{return await import(t)}catch(e){let o=e;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${t}" is not installed. Add it to your project: npm install ${t}`):e}},"loadProvider"),ee=s(async(t,e)=>{let o=e.providerOptions??{};switch(e.providerType){case "openai":{let{createOpenAI:n}=await _(L.openai);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "anthropic":{let{createAnthropic:n}=await _(L.anthropic);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "openai-compatible":{if(!e.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await _(L["openai-compatible"]);return n({name:t,baseURL:e.baseURL,apiKey:e.apiKey,...o})(e.model)}case "google":{let{createGoogleGenerativeAI:n}=await _(L.google);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "xai":{let{createXai:n}=await _(L.xai);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "azure":{if(!e.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await _(L.azure);return n({baseURL:e.baseURL,apiKey:e.apiKey,...o})(e.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await _(L["amazon-bedrock"]);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "google-vertex":{let{createVertex:n}=await _(L["google-vertex"]);return n({baseURL:e.baseURL||void 0,...o})(e.model)}case "deepseek":{let{createDeepSeek:n}=await _(L.deepseek);return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:e.baseURL||void 0,apiKey:e.apiKey,...o})(e.model)}case "cloudflare":{let r=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:a,...g}=o;if(!r&&!("binding"in g))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:d}=await _(L.cloudflare),l="binding"in g?g:{accountId:r,apiKey:e.apiKey,...g};return d(l)(e.model)}}},"buildModelFromStage");var de=s(t=>{if(!t?.length)return "(no prior conversation)";let e=t.slice(-8),o=t.length-e.length,n=[];o>0&&n.push(`(${o} earlier turns omitted)`);for(let r of e){let a=r.content.length>1500?`${r.content.slice(0,1500)}... [truncated]`:r.content;n.push(`${r.role}: ${a}`);}return n.join(`
|
|
3
|
+
`)},"renderHistory"),_t={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},be=s((t,e="full")=>{if(t.length===0)return "(no tools available)";let{tools:o,descChars:n}=_t[e],r=t.slice(0,o),a=t.length-r.length,g=r.map(d=>{let l=(d.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${d.name}: ${l}`});return a>0&&g.push(`... and ${a} more tools`),g.join(`
|
|
4
|
+
`)},"renderToolCatalog"),ce=1500,Nt=s(t=>{let e;try{e=typeof t=="string"?t:JSON.stringify(t);}catch{e=String(t);}return e.length>ce?`${e.slice(0,ce)}... [truncated, ${e.length-ce} chars]`:e},"truncateOutput"),Dt=s((t,e)=>{let o=t.toolCalls.length?t.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${Nt(n.output)}`).join(`
|
|
5
|
+
`):" (no tool calls)";return [`Step ${e+1}: ${t.step.description}`,` Result: ${t.summary}`," Tool calls:",o].join(`
|
|
6
|
+
`)},"renderTraceEntry"),pe=s(t=>t.length===0?"(no steps executed yet)":t.map(Dt).join(`
|
|
7
|
+
`),"renderTrace"),ue=s(t=>[`Plan thought: ${t.thought}`,"Steps:",...t.steps.map((e,o)=>` ${o+1}. [${e.id}] ${e.description}
|
|
8
|
+
expected: ${e.expectedOutcome}`+(e.suggestedTools?.length?`
|
|
9
|
+
suggested tools: ${e.suggestedTools.join(", ")}`:""))].join(`
|
|
10
|
+
`),"renderPlan"),z=s((t,e)=>e?`${t}
|
|
11
11
|
|
|
12
12
|
Domain context:
|
|
13
|
-
${
|
|
13
|
+
${e}`:t,"withDomainContext"),Ie=`You are the Planner of a multi-step agent system.
|
|
14
14
|
|
|
15
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.
|
|
16
16
|
|
|
@@ -20,28 +20,28 @@ Rules:
|
|
|
20
20
|
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
21
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.
|
|
22
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).
|
|
23
|
-
6. Output strict JSON matching the requested schema. No prose outside JSON.`,
|
|
23
|
+
6. Output strict JSON matching the requested schema. No prose outside JSON.`,zt=`
|
|
24
24
|
|
|
25
25
|
ADDITIONAL RULE (tool-narrowed mode):
|
|
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.`,
|
|
27
|
-
${
|
|
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.`,ke=s(t=>t==="compact"?Ie+zt:Ie,"buildPlannerSystem"),Ae=s((t,e,o,n="full")=>[o?.length?`Conversation history:
|
|
27
|
+
${de(o)}
|
|
28
28
|
`:"",`User request:
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
`),"buildPlannerUserPrompt"),
|
|
29
|
+
${t}`,"",`Available tools:
|
|
30
|
+
${be(e,n)}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
31
|
+
`),"buildPlannerUserPrompt"),Re=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
|
|
32
32
|
|
|
33
33
|
Rules:
|
|
34
34
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
35
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.
|
|
36
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.
|
|
37
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.
|
|
38
|
-
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,
|
|
39
|
-
${
|
|
38
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,Ee=s((t,e,o,n,r)=>[r?.length?`Conversation history:
|
|
39
|
+
${de(r)}
|
|
40
40
|
`:"",`Original user request:
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${
|
|
44
|
-
`),"buildExecutorUserPrompt"),
|
|
41
|
+
${t}`,"",`Overall plan:
|
|
42
|
+
${ue(e)}`,"",`Trace so far:
|
|
43
|
+
${pe(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(`
|
|
44
|
+
`),"buildExecutorUserPrompt"),xe=`You are the Replanner of a multi-step agent system. After each Executor step you decide what should happen next.
|
|
45
45
|
|
|
46
46
|
You have three options:
|
|
47
47
|
- "continue": the next planned step is still appropriate.
|
|
@@ -52,21 +52,21 @@ Rules:
|
|
|
52
52
|
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
53
53
|
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
54
54
|
3. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
|
|
55
|
-
4. Output strict JSON matching the schema. No prose outside JSON.`,
|
|
56
|
-
${
|
|
57
|
-
${
|
|
58
|
-
${
|
|
59
|
-
${
|
|
60
|
-
`),"buildReplannerUserPrompt"),
|
|
55
|
+
4. Output strict JSON matching the schema. No prose outside JSON.`,Pe=s((t,e,o,n,r,a="full")=>[`Original user request:
|
|
56
|
+
${t}`,"",`Current plan:
|
|
57
|
+
${ue(e)}`,"",`Completed steps:
|
|
58
|
+
${pe(o)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","",`Available tools (for revise option):
|
|
59
|
+
${be(r,a)}`,"","Decide now: continue, revise, or finish."].join(`
|
|
60
|
+
`),"buildReplannerUserPrompt"),Oe=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
61
61
|
|
|
62
62
|
Rules:
|
|
63
63
|
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
64
64
|
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
65
65
|
3. If the trace shows the request could not be completed, say so plainly and explain what blocked it.
|
|
66
|
-
4. Use the user's language.`,
|
|
67
|
-
${
|
|
66
|
+
4. Use the user's language.`,Ce=s((t,e,o,n)=>[n?.length?`Conversation history:
|
|
67
|
+
${de(n)}
|
|
68
68
|
`:"",`User request:
|
|
69
|
-
${
|
|
70
|
-
${
|
|
71
|
-
${
|
|
72
|
-
`),"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"),_=s(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let r=0;r<=t.maxRetries;r++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(a){if(n=a,r===t.maxRetries||!Te(a))throw a;t.onRetry?.(r+1,a);let d=o*2**r+Math.random()*250;await lt(d,t.signal);}}throw n},"withRetry"),lt=s((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let r=setTimeout(()=>{t?.removeEventListener("abort",a),o();},e),a=s(()=>{clearTimeout(r),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",a,{once:true});}),"sleep"),te=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),D=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:te([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[o,n]of Object.entries(e))t[o]=ct.has(o.toLowerCase())?"***redacted***":n;return t},"redactHeaders");var mt=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 r of o){let a=e.tools[r];a&&(n[r]=a);}return n},"buildActiveToolSet"),be="[BLOCKER]",gt=s(e=>e.includes(be)?{summary:e.split(be).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),oe=4e3,ft=s(e=>e.length>oe?`${e.slice(0,oe)}... [truncated, ${e.length-oe} chars]`:e,"truncateForTrace"),Ie=s(async(e,t,o,n,r,a,d)=>O("agent.execute_step",{[v.PHASE]:"execute",[v.STEP_ID]:o.id},async p=>{let l=Date.now(),c=await _(()=>ht(e,t,o,n,r,a,d),{maxRetries:a.config.llmMaxRetries??2,signal:d,onRetry:s((i,m)=>a.emit({type:"retry",phase:"execute",attempt:i,error:m.message}),"onRetry")});return a.emit({type:"usage",phase:"execute",usage:c.usage}),p.setAttribute(v.USAGE_TOTAL_TOKENS,c.usage.totalTokens),p.setAttribute(v.STEP_BLOCKED,c.blocked),p.setAttribute(v.TOOL_COUNT,c.toolCalls.length),{step:o,summary:c.summary,toolCalls:c.toolCalls,durationMs:Date.now()-l,blocked:c.blocked}}),"executeStep"),ht=s(async(e,t,o,n,r,a,d)=>{let p=[],l=new Map,c=mt(a,o),i=a.config.toolSelectionStrategy==="plan-narrowed",m=s(async(y,E)=>{let x=a.config.inputSanitizer;if(!x)return E;try{return await x(y,E)}catch(u){return a.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${y} - ${u.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),h=streamText({model:a.executorModel,tools:c,...i?{activeTools:Object.keys(c)}:{},stopWhen:stepCountIs(a.config.maxStepsPerTask),system:N(me,a.config.systemPrompt),prompt:ge(e,t,o,n,r),abortSignal:D(d,a.config.llmTimeoutMs??0)});for await(let y of h.fullStream)switch(y.type){case "text-delta":y.text&&a.emit({type:"step.text-delta",step:o,delta:y.text});break;case "tool-call":{let E=await m(y.toolName,y.input);l.set(y.toolCallId,{name:y.toolName,input:E}),a.emit({type:"step.tool-call",step:o,name:y.toolName,input:E});break}case "tool-result":{let x=l.get(y.toolCallId)?.input??await m(y.toolName,y.input);p.push({name:y.toolName,input:x,output:y.output,ok:true}),a.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.output,ok:true}),l.delete(y.toolCallId);break}case "tool-error":{let x=l.get(y.toolCallId)?.input??await m(y.toolName,y.input);p.push({name:y.toolName,input:x,output:y.error,ok:false}),a.emit({type:"step.tool-result",step:o,name:y.toolName,output:y.error,ok:false}),l.delete(y.toolCallId);break}case "error":{let E=y.error;throw E instanceof Error?E:new Error(String(E))}}let[w,f]=await Promise.all([h.text,h.usage]),{summary:I,blocked:b}=gt(w.trim());return {summary:I.length>0?ft(I):p.length>0?`Executed ${p.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:p,blocked:b,usage:{inputTokens:f.inputTokens??0,outputTokens:f.outputTokens??0,totalTokens:f.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")}),Se=8,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)}),ve=s(async(e,t,o,n)=>O("agent.plan",{[v.PHASE]:"plan"},async r=>{let a=new Set(o.toolCatalog.map(i=>i.name)),d=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:p,usage:l}=await _(()=>Tt(e,t,d,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((i,m)=>o.emit({type:"retry",phase:"plan",attempt:i,error:m.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:l}),r.setAttribute(v.USAGE_TOTAL_TOKENS,l.totalTokens);let c=p.steps.slice(0,Se);return c.length<p.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${p.steps.length} steps; truncated to hard cap ${Se}`}),{thought:p.thought,steps:c.map(i=>{if(!i.suggestedTools?.length)return i;let m=i.suggestedTools.filter(w=>a.has(w)),h=i.suggestedTools.length-m.length;return h>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${i.id}" had ${h} unknown suggestedTools, stripped`}),m.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:m}})}}),"createInitialPlan"),Tt=s(async(e,t,o,n,r)=>{let a=streamObject({model:n.plannerModel,schema:ne,system:N(ue(o),n.config.systemPrompt),prompt:de(e,n.toolCatalog,t,o),abortSignal:D(r,n.config.llmTimeoutMs??0)}),d="",p=false,l=0;for await(let m of a.partialObjectStream){let h=m?.thought;typeof h=="string"&&h!==d&&(h.startsWith(d)?n.emit({type:"plan.thought-delta",delta:h.slice(d.length)}):p||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),p=true),d=h);let w=m?.steps;if(Array.isArray(w)&&w.length>l)for(;l<w.length;){let f=w[l];if(!f||typeof f.description!="string"||!f.description.length)break;let I={id:typeof f.id=="string"&&f.id?f.id:`s${l+1}`,description:f.description,expectedOutcome:typeof f.expectedOutcome=="string"?f.expectedOutcome:"",suggestedTools:Array.isArray(f.suggestedTools)?f.suggestedTools.filter(b=>typeof b=="string"):void 0};n.emit({type:"plan.step-added",step:I,index:l}),l++;}}let[c,i]=await Promise.all([a.object,a.usage]);return {object:c,usage:{inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,totalTokens:i.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")})]),Re=s(async(e,t,o,n,r,a)=>O("agent.replan",{[v.PHASE]:"replan"},async d=>{let p=r.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:l,usage:c}=await _(async()=>{let i=await generateObject({model:r.plannerModel,schema:It,system:N(fe,r.config.systemPrompt),prompt:he(e,t,o,n,r.toolCatalog,p),abortSignal:D(a,r.config.llmTimeoutMs??0)}),m={inputTokens:i.usage.inputTokens??0,outputTokens:i.usage.outputTokens??0,totalTokens:i.usage.totalTokens??0};return {object:i.object,usage:m}},{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((i,m)=>r.emit({type:"retry",phase:"replan",attempt:i,error:m.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:c}),d.setAttribute(v.REPLAN_MODE,l.mode),d.setAttribute(v.USAGE_TOTAL_TOKENS,c.totalTokens),l}),"decideNextAction");var ke=s(async(e,t,o,n,r,a)=>O("agent.synthesize",{[v.PHASE]:"synthesize"},async d=>{let{text:p,usage:l}=await _(()=>vt(e,t,o,n,r,a),{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((c,i)=>r.emit({type:"retry",phase:"synthesize",attempt:c,error:i.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:l}),d.setAttribute(v.USAGE_TOTAL_TOKENS,l.totalTokens),p}),"synthesizeAnswer"),vt=s(async(e,t,o,n,r,a)=>{let d=streamText({model:r.synthesizerModel,system:N(ye,r.config.systemPrompt),prompt:we(e,t,o,n),abortSignal:D(a,r.config.llmTimeoutMs??0)});for await(let c of d.fullStream)if(c.type==="text-delta")c.text&&r.emit({type:"final.text-delta",delta:c.text});else if(c.type==="error"){let i=c.error;throw i instanceof Error?i:new Error(String(i))}let[p,l]=await Promise.all([d.text,d.usage]);return {text:p,usage:{inputTokens:l.inputTokens??0,outputTokens:l.outputTokens??0,totalTokens:l.totalTokens??0}}},"streamOnce");var Ee=s(e=>{if(e.blocked)return true;let{toolCalls:t}=e;return t.some((o,n)=>!o.ok&&!t.slice(n+1).some(r=>r.ok&&r.name===o.name))},"shouldCallReplanner"),Et=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return Ee(t);let n=s(()=>Ee(t),"fallback"),{signal:r}=o,a=o.timeoutMs??0;if(r?.aborted)return n();let d=(async()=>{try{return !!await e(t)}catch(l){return o.onError?.(l),n()}})(),p=Number.isFinite(a)&&a>0;return !p&&!r?d:new Promise(l=>{let c=false,i,m=s(w=>{c||(c=true,i!==void 0&&clearTimeout(i),r?.removeEventListener("abort",h),l(w));},"finish");function h(){m(n());}s(h,"onAbort"),p&&(i=setTimeout(()=>m(n()),a)),r?.addEventListener("abort",h,{once:true}),d.then(m,()=>m(n()));})},"replanTriggered"),q=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),xt=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||Ae.join(tmpdir(),"agent-sandbox");return Ae.join(o,t)},"resolveSandboxDir"),xe=/^[a-zA-Z0-9_-]{1,128}$/,re=s((e,t)=>{if(!xe.test(e))throw new Error(`Unsafe runId from ${t}: must match ${xe}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Ct=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(re(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(re(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"),Ce=s(async(e,t)=>{let o=await Ct(e,t),n=o?.runId??randomUUID();re(n,"runId");let r=o?.startedAt??Date.now(),a=xt(e,n);return z.run({runId:n,startedAt:r,sandboxDir:a},async()=>O("agent.run",{[v.RUN_ID]:n,[v.PROVIDER]:e.config.providerType,[v.MODEL]:e.config.model},async d=>{try{let p=await Pt(e,t,o);return d.setAttribute(v.ITERATIONS,p.iterations),d.setAttribute(v.USAGE_TOTAL_TOKENS,p.usage.totalTokens),d.setAttribute(v.USAGE_INPUT_TOKENS,p.usage.inputTokens),d.setAttribute(v.USAGE_OUTPUT_TOKENS,p.usage.outputTokens),p}finally{e.config.keepSandbox||await rm(a,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Pt=s(async(e,t,o)=>{let{signal:n}=t,r=o?.input??t.input,a=o?.history?[...o.history]:t.history?[...t.history]:void 0,d=t.onEvent??(()=>{}),p=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},l=z.getStore()?.startedAt??Date.now(),c=z.getStore()?.runId??"<unknown>",i={...e,emit:s(g=>{g.type==="usage"&&(p.inputTokens+=g.usage.inputTokens,p.outputTokens+=g.usage.outputTokens,p.totalTokens+=g.usage.totalTokens);let A={...g,runId:z.getStore()?.runId};try{d(A);}catch{}try{e.emit(A);}catch{}},"emit")},m=e.config.persistence,h=s(async(g,A)=>{let k=m?.[g];if(k)try{await k(A);}catch(P){i.emit({type:"log",level:"warn",message:`[persistence] ${g} threw: ${P.message}`});}},"callPersistence"),w;if(o)w=o.plan,i.emit({type:"log",level:"info",message:`[resume] continuing run ${c} from step ${o.stepIndex}/${w.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),i.emit({type:"plan.created",plan:w});else {try{w=await ve(r,a,i,n);}catch(g){if(i.emit({type:"error",error:F(g),phase:"plan"}),q(g)||n?.aborted)throw await h("onRunComplete",{runId:c,startedAt:l,status:"cancelled",input:r,history:a,trace:[],usage:p,stepIndex:0,iterations:0,revisions:0,error:g.message,completedAt:Date.now()}),g;w={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."}]};}i.emit({type:"plan.created",plan:w});}let f=o?[...o.trace]:[],I=w,b=o?.stepIndex??0,R=o?.iterations??0,y=o?.revisions??0,E=e.config.maxRevisions??2,x=e.config.maxTotalTokens,u=s((g,A={})=>({runId:c,startedAt:l,status:g,input:r,history:a,plan:I,trace:f,usage:p,stepIndex:b,iterations:R,revisions:y,...A}),"buildSnapshot");o||await h("onRunStart",u("executing"));let T=s(async()=>{await h("onStepComplete",u("executing"));},"persistCheckpoint");for(;R<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(b>=I.steps.length)break;if(x&&p.totalTokens>=x){i.emit({type:"budget.exceeded",tokens:p.totalTokens,cap:x});break}R++;let g=I.steps[b];i.emit({type:"step.start",step:g,index:b});let A=new AbortController;if(t.onStepStart)try{t.onStepStart({step:g,index:b,abort:s(()=>A.abort(),"abort")});}catch(C){i.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${C.message}`});}let k=te([n,A.signal]),P;try{P=await Ie(r,I,g,f,a,i,k);}catch(C){if(n?.aborted)throw i.emit({type:"error",error:F(C),phase:"execute"}),await h("onRunComplete",u("cancelled",{error:C.message,completedAt:Date.now()})),C;if(A.signal.aborted&&q(C))i.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),P={step:g,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw i.emit({type:"error",error:F(C),phase:"execute"}),await h("onRunComplete",u("failed",{error:C.message,completedAt:Date.now()})),C}f.push(P),i.emit({type:"step.complete",step:g,result:P});let K=I.steps[b+1]??null;if(K===null){i.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await Et(e.config.replanAfter,P,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:s(C=>i.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${C.message}`}),"onError")})){i.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),b++,await T();continue}let j;try{j=await Re(r,I,f,K,i,n);}catch(C){throw i.emit({type:"error",error:F(C),phase:"replan"}),await h("onRunComplete",u(q(C)||n?.aborted?"cancelled":"failed",{error:C.message,completedAt:Date.now()})),C}if(i.emit({type:"replan.decision",mode:j.mode,reason:j.reason,cause:"llm-decision"}),j.mode==="finish")break;if(j.mode==="revise"){if(y>=E){i.emit({type:"revisions.exceeded",cap:E});break}y++,I=j.newPlan,i.emit({type:"plan.revised",plan:I,reason:j.reason}),b=0,await T();continue}b++,await T();}let S;try{S=await ke(r,I,f,a,i,n);}catch(g){throw i.emit({type:"error",error:F(g),phase:"synthesize"}),await h("onRunComplete",u(q(g)||n?.aborted?"cancelled":"failed",{error:g.message,completedAt:Date.now()})),g}return i.emit({type:"final",text:S}),await h("onRunComplete",u("complete",{text:S,completedAt:Date.now()})),{text:S,plan:I,trace:f,iterations:R,usage:p}},"runAgentLoopInner"),F=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var G={none:0,error:1,warn:2,info:3,debug:4},Zo=s(async(e,t)=>{let o=G[e.logLevel]>=G.debug,n=s(u=>{if(t)try{t(u);}catch(T){o&&console.error("[agent] event handler threw:",T);}},"emit"),r=s((u,T)=>{G[e.logLevel]>=G[u]&&n({type:"log",level:u,message:T});},"log"),a,d=s((u,T)=>{if(!e.tools)return u;let S=[];for(let[g,A]of Object.entries(e.tools)){if(u.tools[g]&&T(g),e.availableTools?.length&&!e.availableTools.includes(g)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(g))continue;u.tools[g]=A;let k=typeof A=="object"&&A&&"description"in A?A.description:"";S.push({name:g,description:typeof k=="string"?k:"",server:"<native>"});}return {tools:u.tools,catalog:[...u.catalog,...S]}},"mergeNativeTools"),p=s(async()=>{let u=await le(e.mcpServers,r,e.clientName,e.outputSanitizer,g=>a?.(g),e.inputSanitizer),T=V(u.tools,u.catalog,e.availableTools,e.excludedTools),S=d(T,g=>{throw u.close().catch(()=>{}),new Error(`Native tool "${g}" collides with an MCP-registered tool of the same name`)});return {connection:u,tools:S.tools,catalog:S.catalog}},"connect"),l;try{l=await p();}catch(u){throw n({type:"error",error:u instanceof Error?u:new Error(String(u)),phase:"init"}),u}let c=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&c>0&&!l.connection.results.some(T=>T.connected)){let T=l.connection.results.filter(g=>!g.connected).map(g=>`${g.name}: ${g.error??"unknown"}`).join("; ");await l.connection.close().catch(()=>{});let S=new Error(`All ${c} configured MCP server(s) failed to connect [${T}]`);throw n({type:"error",error:S,phase:"init"}),S}let i,m,h;try{let u=Y(e,void 0,void 0,"executor"),T=Y(e,e.planner,e.plannerModel,"planner"),S=Y(e,e.synthesizer,e.synthesizerModel,"synthesizer");[i,m,h]=await Promise.all([B(e.clientName,u),B(e.clientName,T),B(e.clientName,S)]);}catch(u){throw await l.connection.close().catch(()=>{}),n({type:"error",error:u instanceof Error?u:new Error(String(u)),phase:"init"}),u}let w={config:e,executorModel:i,plannerModel:m,synthesizerModel:h,tools:l.tools,toolCatalog:l.catalog.map(u=>({name:u.name,description:u.description})),emit:n},f=0,I=false,b=false,R=false,y=new Set,E=s(async u=>{await l.connection.refreshServer(u);let T=V(l.connection.tools,l.connection.catalog,e.availableTools,e.excludedTools),S=d(T,g=>{throw new Error(`Native tool "${g}" collides with an MCP-registered tool of the same name`)});for(let g of Object.keys(w.tools))delete w.tools[g];Object.assign(w.tools,S.tools),w.toolCatalog=S.catalog.map(g=>({name:g.name,description:g.description})),r("info",`[mcp] ${u}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),x=s(async()=>{if(!(R||I||b)&&!(f>0||y.size===0)){R=true;try{for(;y.size>0&&f===0&&!I&&!b;){let u=y.values().next().value;y.delete(u);try{await E(u);}catch(T){r("warn",`[mcp] ${u}: refresh failed - ${T.message}`);}}}finally{R=false;}}},"drainPendingRefreshes");return a=s(u=>{y.add(u),x();},"onToolsChanged"),{run:s(async u=>{if(I)throw new Error("Agent is closed");if(b)throw new Error("Agent is reconnecting; retry shortly");if(R)throw new Error("Agent is refreshing tools; retry shortly");let T=e.maxConcurrentRuns;if(typeof T=="number"&&T>0&&f>=T)throw new Error(`maxConcurrentRuns reached (${f}/${T}); rate-limit on the caller side or raise the cap`);f++;try{return await Ce(w,u)}finally{f--,x();}},"run"),listTools:s(()=>w.toolCatalog.slice(),"listTools"),reconnect:s(async()=>{if(I)throw new Error("Agent is closed");if(b)throw new Error("Already reconnecting");if(R)throw new Error("Agent is refreshing tools; retry shortly");if(f>0)throw new Error(`Cannot reconnect with ${f} active run(s)`);b=true;try{let u=l.connection;y.clear();let T=await p();for(let S of Object.keys(w.tools))delete w.tools[S];Object.assign(w.tools,T.tools),w.toolCatalog=T.catalog.map(S=>({name:S.name,description:S.description})),l=T,await u.close().catch(()=>{});}finally{b=false;}},"reconnect"),close:s(async u=>{I=true;let T=u?.waitForRuns??false,S=u?.timeoutMs??3e4,g=Date.now()+S;if(T&&f>0)for(;f>0&&Date.now()<g;)await new Promise(K=>setTimeout(K,50));f>0&&n({type:"log",level:"warn",message:`[agent] close called with ${f} active run(s); they will fail mid-flight`});let A=Math.max(g-Date.now(),0),k=false,P;await Promise.race([l.connection.close().catch(()=>{}),new Promise(K=>{P=setTimeout(()=>{k=true,K();},A),P.unref?.();})]),P&&clearTimeout(P),k&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${A}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>f,"activeRuns")}},"createAgent");export{Zo as createAgent,Le as getCurrentRunId,W as getCurrentRunSandbox,pt as redactHeaders};
|
|
69
|
+
${t}`,"",`Plan that was executed:
|
|
70
|
+
${ue(e)}`,"",`Execution trace:
|
|
71
|
+
${pe(o)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
72
|
+
`),"buildSynthesizerUserPrompt");var Ue=s((t,e=new Set)=>{if(!t||typeof t!="object"||e.has(t))return false;e.add(t);let o=t;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"?Ue(o.cause,e):false},"isRetriable"),j=s(async(t,e)=>{let o=e.baseDelayMs??500,n;for(let r=0;r<=e.maxRetries;r++){if(e.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await t()}catch(a){if(n=a,r===e.maxRetries||!Ue(a))throw a;e.onRetry?.(r+1,a);let g=o*2**r+Math.random()*250;await jt(g,e.signal);}}throw n},"withRetry"),jt=s((t,e)=>new Promise((o,n)=>{if(e?.aborted){n(new DOMException("Aborted","AbortError"));return}let r=setTimeout(()=>{e?.removeEventListener("abort",a),o();},t),a=s(()=>{clearTimeout(r),n(new DOMException("Aborted","AbortError"));},"onAbort");e?.addEventListener("abort",a,{once:true});}),"sleep"),me=s(t=>{let e=t.filter(o=>!!o);return e.length===0?new AbortController().signal:e.length===1?e[0]:AbortSignal.any(e)},"combineSignals"),K=s((t,e)=>!Number.isFinite(e)||e<=0?t??new AbortController().signal:me([t,AbortSignal.timeout(e)]),"withTimeout"),Kt=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),Ft=s(t=>{if(!t)return t;let e={};for(let[o,n]of Object.entries(t))e[o]=Kt.has(o.toLowerCase())?"***redacted***":n;return e},"redactHeaders");var Bt=s((t,e)=>{if(t.config.toolSelectionStrategy!=="plan-narrowed")return t.tools;let o=new Set(e.suggestedTools??[]);if(o.size===0)return e.requiresTools?t.tools:{};let n={};for(let r of o){let a=t.tools[r];a&&(n[r]=a);}return n},"buildActiveToolSet"),$e="[BLOCKER]",Yt=s(t=>t.includes($e)?{summary:t.split($e).join("").trim(),blocked:true}:{summary:t,blocked:false},"splitBlockerSentinel"),ge=4e3,Gt=s(t=>t.length>ge?`${t.slice(0,ge)}... [truncated, ${t.length-ge} chars]`:t,"truncateForTrace"),Me=s(async(t,e,o,n,r,a,g)=>U("agent.execute_step",{[k.PHASE]:"execute",[k.STEP_ID]:o.id},async d=>{let l=Date.now(),c=await j(()=>Jt(t,e,o,n,r,a,g),{maxRetries:a.config.llmMaxRetries??2,signal:g,onRetry:s((i,w)=>a.emit({type:"retry",phase:"execute",attempt:i,error:w.message}),"onRetry")});return a.emit({type:"usage",phase:"execute",usage:c.usage}),d.setAttribute(k.USAGE_TOTAL_TOKENS,c.usage.totalTokens),d.setAttribute(k.STEP_BLOCKED,c.blocked),d.setAttribute(k.TOOL_COUNT,c.toolCalls.length),{step:o,summary:c.summary,toolCalls:c.toolCalls,durationMs:Date.now()-l,blocked:c.blocked}}),"executeStep"),Jt=s(async(t,e,o,n,r,a,g)=>{let d=[],l=new Map,c=Bt(a,o),i=a.config.toolSelectionStrategy==="plan-narrowed",w=s(async(f,b)=>{let E=a.config.inputSanitizer;if(!E)return b;try{return await E(f,b)}catch(m){return a.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${f} - ${m.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),T=streamText({model:a.executorModel,tools:c,...i?{activeTools:Object.keys(c)}:{},stopWhen:stepCountIs(a.config.maxStepsPerTask),system:z(Re,a.config.systemPrompt),prompt:Ee(t,e,o,n,r),abortSignal:K(g,a.config.llmTimeoutMs??0)});for await(let f of T.fullStream)switch(f.type){case "text-delta":f.text&&a.emit({type:"step.text-delta",step:o,delta:f.text});break;case "tool-call":{let b=await w(f.toolName,f.input);l.set(f.toolCallId,{name:f.toolName,input:b}),a.emit({type:"step.tool-call",step:o,name:f.toolName,input:b});break}case "tool-result":{let E=l.get(f.toolCallId)?.input??await w(f.toolName,f.input);d.push({name:f.toolName,input:E,output:f.output,ok:true}),a.emit({type:"step.tool-result",step:o,name:f.toolName,output:f.output,ok:true}),l.delete(f.toolCallId);break}case "tool-error":{let E=l.get(f.toolCallId)?.input??await w(f.toolName,f.input);d.push({name:f.toolName,input:E,output:f.error,ok:false}),a.emit({type:"step.tool-result",step:o,name:f.toolName,output:f.error,ok:false}),l.delete(f.toolCallId);break}case "error":{let b=f.error;throw b instanceof Error?b:new Error(String(b))}}let[I,v]=await Promise.all([T.text,T.usage]),{summary:p,blocked:h}=Yt(I.trim());return {summary:p.length>0?Gt(p):d.length>0?`Executed ${d.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:d,blocked:h,usage:{inputTokens:v.inputTokens??0,outputTokens:v.outputTokens??0,totalTokens:v.totalTokens??0}}},"runOnce");var Vt=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")}),Le=8,he=z$1.object({thought:z$1.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z$1.array(Vt).min(1)}),_e=s(async(t,e,o,n)=>U("agent.plan",{[k.PHASE]:"plan"},async r=>{let a=new Set(o.toolCatalog.map(i=>i.name)),g=o.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:d,usage:l}=await j(()=>Xt(t,e,g,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((i,w)=>o.emit({type:"retry",phase:"plan",attempt:i,error:w.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:l}),r.setAttribute(k.USAGE_TOTAL_TOKENS,l.totalTokens);let c=d.steps.slice(0,Le);return c.length<d.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${d.steps.length} steps; truncated to hard cap ${Le}`}),{thought:d.thought,steps:c.map(i=>{if(!i.suggestedTools?.length)return i;let w=i.suggestedTools.filter(I=>a.has(I)),T=i.suggestedTools.length-w.length;return T>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${i.id}" had ${T} unknown suggestedTools, stripped`}),w.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:w}})}}),"createInitialPlan"),Xt=s(async(t,e,o,n,r)=>{let a=streamObject({model:n.plannerModel,schema:he,system:z(ke(o),n.config.systemPrompt),prompt:Ae(t,n.toolCatalog,e,o),abortSignal:K(r,n.config.llmTimeoutMs??0)}),g="",d=false,l=0;for await(let w of a.partialObjectStream){let T=w?.thought;typeof T=="string"&&T!==g&&(T.startsWith(g)?n.emit({type:"plan.thought-delta",delta:T.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=T);let I=w?.steps;if(Array.isArray(I)&&I.length>l)for(;l<I.length;){let v=I[l];if(!v||typeof v.description!="string"||!v.description.length)break;let p={id:typeof v.id=="string"&&v.id?v.id:`s${l+1}`,description:v.description,expectedOutcome:typeof v.expectedOutcome=="string"?v.expectedOutcome:"",suggestedTools:Array.isArray(v.suggestedTools)?v.suggestedTools.filter(h=>typeof h=="string"):void 0};n.emit({type:"plan.step-added",step:p,index:l}),l++;}}let[c,i]=await Promise.all([a.object,a.usage]);return {object:c,usage:{inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,totalTokens:i.totalTokens??0}}},"streamPlanOnce");var Qt=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:he.describe("Plan covering ONLY the remaining work")})]),Ne=s(async(t,e,o,n,r,a)=>U("agent.replan",{[k.PHASE]:"replan"},async g=>{let d=r.config.toolSelectionStrategy==="plan-narrowed"?"compact":"full",{object:l,usage:c}=await j(async()=>{let i=await generateObject({model:r.plannerModel,schema:Qt,system:z(xe,r.config.systemPrompt),prompt:Pe(t,e,o,n,r.toolCatalog,d),abortSignal:K(a,r.config.llmTimeoutMs??0)}),w={inputTokens:i.usage.inputTokens??0,outputTokens:i.usage.outputTokens??0,totalTokens:i.usage.totalTokens??0};return {object:i.object,usage:w}},{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((i,w)=>r.emit({type:"retry",phase:"replan",attempt:i,error:w.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:c}),g.setAttribute(k.REPLAN_MODE,l.mode),g.setAttribute(k.USAGE_TOTAL_TOKENS,c.totalTokens),l}),"decideNextAction");var De=s(async(t,e,o,n,r,a)=>U("agent.synthesize",{[k.PHASE]:"synthesize"},async g=>{let{text:d,usage:l}=await j(()=>to(t,e,o,n,r,a),{maxRetries:r.config.llmMaxRetries??2,signal:a,onRetry:s((c,i)=>r.emit({type:"retry",phase:"synthesize",attempt:c,error:i.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:l}),g.setAttribute(k.USAGE_TOTAL_TOKENS,l.totalTokens),d}),"synthesizeAnswer"),to=s(async(t,e,o,n,r,a)=>{let g=streamText({model:r.synthesizerModel,system:z(Oe,r.config.systemPrompt),prompt:Ce(t,e,o,n),abortSignal:K(a,r.config.llmTimeoutMs??0)});for await(let c of g.fullStream)if(c.type==="text-delta")c.text&&r.emit({type:"final.text-delta",delta:c.text});else if(c.type==="error"){let i=c.error;throw i instanceof Error?i:new Error(String(i))}let[d,l]=await Promise.all([g.text,g.usage]);return {text:d,usage:{inputTokens:l.inputTokens??0,outputTokens:l.outputTokens??0,totalTokens:l.totalTokens??0}}},"streamOnce");var je=s(t=>{if(t.blocked)return true;let{toolCalls:e}=t;return e.some((o,n)=>!o.ok&&!e.slice(n+1).some(r=>r.ok&&r.name===o.name))},"shouldCallReplanner"),so=s(async(t,e,o={})=>{if(t==="always")return true;if(typeof t!="function")return je(e);let n=s(()=>je(e),"fallback"),{signal:r}=o,a=o.timeoutMs??0;if(r?.aborted)return n();let g=(async()=>{try{return !!await t(e)}catch(l){return o.onError?.(l),n()}})(),d=Number.isFinite(a)&&a>0;return !d&&!r?g:new Promise(l=>{let c=false,i,w=s(I=>{c||(c=true,i!==void 0&&clearTimeout(i),r?.removeEventListener("abort",T),l(I));},"finish");function T(){w(n());}s(T,"onAbort"),d&&(i=setTimeout(()=>w(n()),a)),r?.addEventListener("abort",T,{once:true}),g.then(w,()=>w(n()));})},"replanTriggered"),te=s(t=>!!t&&typeof t=="object"&&t.name==="AbortError","isAbortError"),io=s((t,e)=>{let o=t.config.sandboxRoot?.trim()||we.join(tmpdir(),"agent-sandbox");return we.join(o,e)},"resolveSandboxDir"),Ke=/^[a-zA-Z0-9_-]{1,128}$/,fe=s((t,e)=>{if(!Ke.test(t))throw new Error(`Unsafe runId from ${e}: must match ${Ke}, got ${JSON.stringify(t)}`)},"assertSafeRunId"),ao=s(async(t,e)=>{if(!e.resumeFromRunId)return;if(fe(e.resumeFromRunId,"options.resumeFromRunId"),!t.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await t.config.persistence.loadRun(e.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${e.resumeFromRunId}"`);if(fe(o.runId,"snapshot.runId"),o.runId!==e.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${e.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${e.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${e.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Fe=s(async(t,e)=>{let o=await ao(t,e),n=o?.runId??randomUUID();fe(n,"runId");let r=o?.startedAt??Date.now(),a=io(t,n);return F.run({runId:n,startedAt:r,sandboxDir:a},async()=>U("agent.run",{[k.RUN_ID]:n,[k.PROVIDER]:t.config.providerType,[k.MODEL]:t.config.model},async g=>{try{let d=await lo(t,e,o);return g.setAttribute(k.ITERATIONS,d.iterations),g.setAttribute(k.USAGE_TOTAL_TOKENS,d.usage.totalTokens),g.setAttribute(k.USAGE_INPUT_TOKENS,d.usage.inputTokens),g.setAttribute(k.USAGE_OUTPUT_TOKENS,d.usage.outputTokens),d}finally{t.config.keepSandbox||await rm(a,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),lo=s(async(t,e,o)=>{let{signal:n}=e,r=o?.input??e.input,a=o?.history?[...o.history]:e.history?[...e.history]:void 0,g=e.onEvent??(()=>{}),d=o?{...o.usage}:{inputTokens:0,outputTokens:0,totalTokens:0},l=F.getStore()?.startedAt??Date.now(),c=F.getStore()?.runId??"<unknown>",i={...t,emit:s(u=>{u.type==="usage"&&(d.inputTokens+=u.usage.inputTokens,d.outputTokens+=u.usage.outputTokens,d.totalTokens+=u.usage.totalTokens);let A={...u,runId:F.getStore()?.runId};try{g(A);}catch{}try{t.emit(A);}catch{}},"emit")},w=t.config.persistence,T=s(async(u,A)=>{let C=w?.[u];if(C)try{await C(A);}catch(P){i.emit({type:"log",level:"warn",message:`[persistence] ${u} threw: ${P.message}`});}},"callPersistence"),I;if(o)I=o.plan,i.emit({type:"log",level:"info",message:`[resume] continuing run ${c} from step ${o.stepIndex}/${I.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),i.emit({type:"plan.created",plan:I});else {try{I=await _e(r,a,i,n);}catch(u){if(i.emit({type:"error",error:Y(u),phase:"plan"}),te(u)||n?.aborted)throw await T("onRunComplete",{runId:c,startedAt:l,status:"cancelled",input:r,history:a,trace:[],usage:d,stepIndex:0,iterations:0,revisions:0,error:u.message,completedAt:Date.now()}),u;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."}]};}i.emit({type:"plan.created",plan:I});}let v=o?[...o.trace]:[],p=I,h=o?.stepIndex??0,R=o?.iterations??0,f=o?.revisions??0,b=t.config.maxRevisions??2,E=t.config.maxTotalTokens,m=s((u,A={})=>({runId:c,startedAt:l,status:u,input:r,history:a,plan:p,trace:v,usage:d,stepIndex:h,iterations:R,revisions:f,...A}),"buildSnapshot");o||await T("onRunStart",m("executing"));let y=s(async()=>{await T("onStepComplete",m("executing"));},"persistCheckpoint");for(;R<t.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(h>=p.steps.length)break;if(E&&d.totalTokens>=E){i.emit({type:"budget.exceeded",tokens:d.totalTokens,cap:E});break}R++;let u=p.steps[h];i.emit({type:"step.start",step:u,index:h});let A=new AbortController;if(e.onStepStart)try{e.onStepStart({step:u,index:h,abort:s(()=>A.abort(),"abort")});}catch(x){i.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${x.message}`});}let C=me([n,A.signal]),P;try{P=await Me(r,p,u,v,a,i,C);}catch(x){if(n?.aborted)throw i.emit({type:"error",error:Y(x),phase:"execute"}),await T("onRunComplete",m("cancelled",{error:x.message,completedAt:Date.now()})),x;if(A.signal.aborted&&te(x))i.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),P={step:u,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw i.emit({type:"error",error:Y(x),phase:"execute"}),await T("onRunComplete",m("failed",{error:x.message,completedAt:Date.now()})),x}v.push(P),i.emit({type:"step.complete",step:u,result:P});let $=p.steps[h+1]??null;if($===null){i.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await so(t.config.replanAfter,P,{signal:n,timeoutMs:t.config.llmTimeoutMs??0,onError:s(x=>i.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${x.message}`}),"onError")})){i.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),h++,await y();continue}let M;try{M=await Ne(r,p,v,$,i,n);}catch(x){throw i.emit({type:"error",error:Y(x),phase:"replan"}),await T("onRunComplete",m(te(x)||n?.aborted?"cancelled":"failed",{error:x.message,completedAt:Date.now()})),x}if(i.emit({type:"replan.decision",mode:M.mode,reason:M.reason,cause:"llm-decision"}),M.mode==="finish")break;if(M.mode==="revise"){if(f>=b){i.emit({type:"revisions.exceeded",cap:b});break}f++,p=M.newPlan,i.emit({type:"plan.revised",plan:p,reason:M.reason}),h=0,await y();continue}h++,await y();}let S;try{S=await De(r,p,v,a,i,n);}catch(u){throw i.emit({type:"error",error:Y(u),phase:"synthesize"}),await T("onRunComplete",m(te(u)||n?.aborted?"cancelled":"failed",{error:u.message,completedAt:Date.now()})),u}return i.emit({type:"final",text:S}),await T("onRunComplete",m("complete",{text:S,completedAt:Date.now()})),{text:S,plan:p,trace:v,iterations:R,usage:d}},"runAgentLoopInner"),Y=s(t=>t instanceof Error?t:new Error(typeof t=="string"?t:JSON.stringify(t)),"asError");var oe={none:0,error:1,warn:2,info:3,debug:4},Dn=s(async(t,e)=>{let o=oe[t.logLevel]>=oe.debug,n=s(m=>{if(e)try{e(m);}catch(y){o&&console.error("[agent] event handler threw:",y);}},"emit"),r=s((m,y)=>{oe[t.logLevel]>=oe[m]&&n({type:"log",level:m,message:y});},"log"),a,g=s((m,y)=>{if(!t.tools)return m;let S=[];for(let[u,A]of Object.entries(t.tools)){if(m.tools[u]&&y(u),t.availableTools?.length&&!t.availableTools.includes(u)||!t.availableTools?.length&&t.excludedTools?.length&&t.excludedTools.includes(u))continue;m.tools[u]=A;let C=typeof A=="object"&&A&&"description"in A?A.description:"";S.push({name:u,description:typeof C=="string"?C:"",server:"<native>"});}return {tools:m.tools,catalog:[...m.catalog,...S]}},"mergeNativeTools"),d=s(async()=>{let m=await Se(t.mcpServers,r,t.clientName,t.outputSanitizer,u=>a?.(u),t.inputSanitizer),y=le(m.tools,m.catalog,t.availableTools,t.excludedTools,r),S=g(y,u=>{throw m.close().catch(()=>{}),new Error(`Native tool "${u}" collides with an MCP-registered tool of the same name`)});return {connection:m,tools:S.tools,catalog:S.catalog}},"connect"),l;try{l=await d();}catch(m){throw n({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let c=Object.keys(t.mcpServers).length;if(t.failOnNoTools&&c>0&&!l.connection.results.some(y=>y.connected)){let y=l.connection.results.filter(u=>!u.connected).map(u=>`${u.name}: ${u.error??"unknown"}`).join("; ");await l.connection.close().catch(()=>{});let S=new Error(`All ${c} configured MCP server(s) failed to connect [${y}]`);throw n({type:"error",error:S,phase:"init"}),S}let i,w,T;try{let m=Q(t,void 0,void 0,"executor"),y=Q(t,t.planner,t.plannerModel,"planner"),S=Q(t,t.synthesizer,t.synthesizerModel,"synthesizer");[i,w,T]=await Promise.all([ee(t.clientName,m),ee(t.clientName,y),ee(t.clientName,S)]);}catch(m){throw await l.connection.close().catch(()=>{}),n({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let I={config:t,executorModel:i,plannerModel:w,synthesizerModel:T,tools:l.tools,toolCatalog:l.catalog.map(m=>({name:m.name,description:m.description})),emit:n},v=0,p=false,h=false,R=false,f=new Set,b=s(async m=>{await l.connection.refreshServer(m);let y=le(l.connection.tools,l.connection.catalog,t.availableTools,t.excludedTools),S=g(y,u=>{throw new Error(`Native tool "${u}" collides with an MCP-registered tool of the same name`)});for(let u of Object.keys(I.tools))delete I.tools[u];Object.assign(I.tools,S.tools),I.toolCatalog=S.catalog.map(u=>({name:u.name,description:u.description})),r("info",`[mcp] ${m}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),E=s(async()=>{if(!(R||p||h)&&!(v>0||f.size===0)){R=true;try{for(;f.size>0&&v===0&&!p&&!h;){let m=f.values().next().value;f.delete(m);try{await b(m);}catch(y){r("warn",`[mcp] ${m}: refresh failed - ${y.message}`);}}}finally{R=false;}}},"drainPendingRefreshes");return a=s(m=>{f.add(m),E();},"onToolsChanged"),{run:s(async m=>{if(p)throw new Error("Agent is closed");if(h)throw new Error("Agent is reconnecting; retry shortly");if(R)throw new Error("Agent is refreshing tools; retry shortly");let y=t.maxConcurrentRuns;if(typeof y=="number"&&y>0&&v>=y)throw new Error(`maxConcurrentRuns reached (${v}/${y}); rate-limit on the caller side or raise the cap`);v++;try{return await Fe(I,m)}finally{v--,E();}},"run"),listTools:s(()=>I.toolCatalog.slice(),"listTools"),reconnect:s(async()=>{if(p)throw new Error("Agent is closed");if(h)throw new Error("Already reconnecting");if(R)throw new Error("Agent is refreshing tools; retry shortly");if(v>0)throw new Error(`Cannot reconnect with ${v} active run(s)`);h=true;try{let m=l.connection;f.clear();let y=await d();for(let S of Object.keys(I.tools))delete I.tools[S];Object.assign(I.tools,y.tools),I.toolCatalog=y.catalog.map(S=>({name:S.name,description:S.description})),l=y,await m.close().catch(()=>{});}finally{h=false;}},"reconnect"),close:s(async m=>{p=true;let y=m?.waitForRuns??false,S=m?.timeoutMs??3e4,u=Date.now()+S;if(y&&v>0)for(;v>0&&Date.now()<u;)await new Promise($=>setTimeout($,50));v>0&&n({type:"log",level:"warn",message:`[agent] close called with ${v} active run(s); they will fail mid-flight`});let A=Math.max(u-Date.now(),0),C=false,P;await Promise.race([l.connection.close().catch(()=>{}),new Promise($=>{P=setTimeout(()=>{C=true,$();},A),P.unref?.();})]),P&&clearTimeout(P),C&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${A}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>v,"activeRuns")}},"createAgent");export{V as FileOAuthStore,re as MemoryOAuthStore,X as NodeOAuthProvider,st as beginMcpOAuth,Dn as createAgent,rt as createNodeOAuthProvider,it as finishMcpOAuth,Ye as getCurrentRunId,ne as getCurrentRunSandbox,Ft as redactHeaders};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudko.dev/agent",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.23",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Tool-using planning agent over MCP servers, built on the Vercel AI SDK.",
|
|
6
6
|
"keywords": [
|
|
@@ -91,20 +91,20 @@
|
|
|
91
91
|
"dependencies": {
|
|
92
92
|
"@modelcontextprotocol/sdk": "^1.30.0",
|
|
93
93
|
"@opentelemetry/api": "^1.9.1",
|
|
94
|
-
"ai": "^7.0.
|
|
94
|
+
"ai": "^7.0.66",
|
|
95
95
|
"zod": "^4.4.3"
|
|
96
96
|
},
|
|
97
97
|
"peerDependencies": {
|
|
98
|
-
"@ai-sdk/amazon-bedrock": "^
|
|
99
|
-
"@ai-sdk/anthropic": "^
|
|
100
|
-
"@ai-sdk/azure": "^
|
|
101
|
-
"@ai-sdk/deepseek": "^
|
|
102
|
-
"@ai-sdk/google": "^
|
|
103
|
-
"@ai-sdk/google-vertex": "^
|
|
104
|
-
"@ai-sdk/openai": "^
|
|
105
|
-
"@ai-sdk/openai-compatible": "^
|
|
106
|
-
"@ai-sdk/xai": "^
|
|
107
|
-
"workers-ai-provider": "^
|
|
98
|
+
"@ai-sdk/amazon-bedrock": "^5.0.0",
|
|
99
|
+
"@ai-sdk/anthropic": "^4.0.0",
|
|
100
|
+
"@ai-sdk/azure": "^4.0.0",
|
|
101
|
+
"@ai-sdk/deepseek": "^3.0.0",
|
|
102
|
+
"@ai-sdk/google": "^4.0.0",
|
|
103
|
+
"@ai-sdk/google-vertex": "^5.0.0",
|
|
104
|
+
"@ai-sdk/openai": "^4.0.0",
|
|
105
|
+
"@ai-sdk/openai-compatible": "^3.0.0",
|
|
106
|
+
"@ai-sdk/xai": "^4.0.0",
|
|
107
|
+
"workers-ai-provider": "^4.0.0"
|
|
108
108
|
},
|
|
109
109
|
"peerDependenciesMeta": {
|
|
110
110
|
"@ai-sdk/amazon-bedrock": {
|
|
@@ -139,15 +139,15 @@
|
|
|
139
139
|
}
|
|
140
140
|
},
|
|
141
141
|
"devDependencies": {
|
|
142
|
-
"@ai-sdk/amazon-bedrock": "^5.0.
|
|
143
|
-
"@ai-sdk/anthropic": "^4.0.
|
|
144
|
-
"@ai-sdk/azure": "^4.0.
|
|
145
|
-
"@ai-sdk/deepseek": "^3.0.
|
|
146
|
-
"@ai-sdk/google": "^4.0.
|
|
147
|
-
"@ai-sdk/google-vertex": "^5.0.
|
|
148
|
-
"@ai-sdk/openai": "^4.0.
|
|
149
|
-
"@ai-sdk/openai-compatible": "^3.0.
|
|
150
|
-
"@ai-sdk/xai": "^4.0.
|
|
142
|
+
"@ai-sdk/amazon-bedrock": "^5.0.57",
|
|
143
|
+
"@ai-sdk/anthropic": "^4.0.39",
|
|
144
|
+
"@ai-sdk/azure": "^4.0.43",
|
|
145
|
+
"@ai-sdk/deepseek": "^3.0.28",
|
|
146
|
+
"@ai-sdk/google": "^4.0.44",
|
|
147
|
+
"@ai-sdk/google-vertex": "^5.0.54",
|
|
148
|
+
"@ai-sdk/openai": "^4.0.42",
|
|
149
|
+
"@ai-sdk/openai-compatible": "^3.0.30",
|
|
150
|
+
"@ai-sdk/xai": "^4.0.39",
|
|
151
151
|
"@types/node": "^22.9.0",
|
|
152
152
|
"prettier": "^3.9.6",
|
|
153
153
|
"tsup": "^8.5.1",
|