@dudko.dev/agent 0.0.30 → 0.0.31
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 +274 -9
- package/dist/cli.js +126 -56
- package/dist/index.cjs +94 -41
- package/dist/index.d.cts +421 -16
- package/dist/index.d.ts +421 -16
- package/dist/index.js +94 -41
- package/dist/subagent-worker.js +120 -0
- package/package.json +12 -12
package/dist/index.cjs
CHANGED
|
@@ -1,72 +1,125 @@
|
|
|
1
|
-
'use strict';var auth_js=require('@modelcontextprotocol/sdk/client/auth.js'),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'),we=require('path'),url=require('url'),async_hooks=require('async_hooks'),Qe=require('os'),api=require('@opentelemetry/api'),zod=require('zod');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var we__default=/*#__PURE__*/_interopDefault(we);var Qe__default=/*#__PURE__*/_interopDefault(Qe);var qe=Object.defineProperty;var s=(t,e)=>qe(t,"name",{value:e,configurable:true});var W={version:"0.0.30"};var F=new async_hooks.AsyncLocalStorage,Ye=s(()=>F.getStore()?.runId,"getCurrentRunId"),ne=s(()=>F.getStore()?.sandboxDir,"getCurrentRunSandbox");var et=we__default.default.join(Qe__default.default.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 promises.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 promises.writeFile(o,JSON.stringify(e,null,2),{mode:384}),await promises.chmod(o,384).catch(()=>{}),await promises.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 promises.mkdir(we__default.default.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=crypto.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_js.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_js.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=api.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:api.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_js.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]=ai.dynamicTool({description:A,inputSchema:ai.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?{...stdio_js.getDefaultEnvironment(),...h.env}:void 0;f=new stdio_js.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 streamableHttp_js.StreamableHTTPClientTransport(new url.URL(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 index_js.Client({name:o,version:xt}),await R.connect(f),r&&R.setNotificationHandler(types_js.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 auth_js.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=crypto.randomUUID().slice(0,8),c=we__default.default.join(r,`${o}-${d}-${l}${g}`),i=Buffer.from(t,"base64");return await promises.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
|
-
`)
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
1
|
+
'use strict';var crypto=require('crypto'),async_hooks=require('async_hooks'),ai=require('ai'),auth_js=require('@modelcontextprotocol/sdk/client/auth.js'),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'),promises=require('fs/promises'),ie=require('path'),url=require('url'),sn=require('os'),api=require('@opentelemetry/api'),zod=require('zod'),worker_threads=require('worker_threads');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ie__default=/*#__PURE__*/_interopDefault(ie);var sn__default=/*#__PURE__*/_interopDefault(sn);var Uo=Object.defineProperty;var s=(e,t)=>Uo(e,"name",{value:t,configurable:true});var _o=s(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),M=_o();var F=new async_hooks.AsyncLocalStorage,Do=s(()=>F.getStore()?.runId,"getCurrentRunId"),qe=s(()=>F.getStore()?.sandboxDir,"getCurrentRunSandbox");var Be=new Set(["autopilot","ask-writes","ask-all","read-only"]),xt=s(e=>typeof e=="string"&&Be.has(e),"isToolApprovalMode"),fe=class extends Error{static{s(this,"ToolDeniedError");}reason;constructor(t){super(`Tool call denied by the user${t?`: ${t}`:""}. Do not retry it; continue without it, or report what is blocked.`),this.name="ToolDeniedError",this.reason=t;}toJSON(){return this.message}},V=s((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),ae=s(e=>!!e&&typeof e=="object"&&e.readOnly===true,"isReadOnlyTool"),Ct=new Map,jo=s(e=>{let t=Ct.get(e);if(!t){let o=e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t=new RegExp(`^${o}$`),Ct.set(e,t);}return t},"globToRegExp"),Ot=s((e,t)=>{if(!e)return;if(Object.hasOwn(e,t)&&!t.includes("*"))return {pattern:t,permission:e[t]};let o;for(let[n,r]of Object.entries(e))n.includes("*")&&jo(n).test(t)&&(!o||n.length>o.pattern.length)&&(o={pattern:n,permission:r});return o},"matchToolRule"),Rt=s(e=>{if(e.builtIn)return {permission:"allow",source:"builtin"};if(e.remembered?.has(e.name))return {permission:"allow",source:"remembered"};let t=Ot(e.rules,e.name);if(t)return {permission:t.permission,source:"rule",rule:t.pattern};switch(e.mode){case "autopilot":return {permission:"allow",source:"mode"};case "read-only":return {permission:e.readOnly?"allow":"deny",source:"mode"};case "ask-writes":return {permission:e.readOnly?"allow":"ask",source:"mode"};case "ask-all":return {permission:"ask",source:"mode"}}},"decideToolPermission"),Fo=s(e=>typeof e=="boolean"?{approved:e}:e&&typeof e=="object"?{approved:e.approved===true,reason:e.reason,remember:e.remember}:{approved:false,reason:"invalid approval decision"},"normalizeDecision"),xe=class extends Error{static{s(this,"ApprovalTimeout");}},Ko=s((e,t,o)=>new Promise((n,r)=>{let i,l=s(()=>{i&&clearTimeout(i),o?.removeEventListener("abort",c);},"done");function c(){l(),r(o?.reason??new DOMException("Aborted","AbortError"));}if(s(c,"onAbort"),o?.aborted){c();return}o?.addEventListener("abort",c,{once:true}),typeof t=="number"&&t>0&&(i=setTimeout(()=>{l(),r(new xe);},t)),e.then(a=>{l(),n(a);},a=>{l(),r(a);});}),"awaitDecision"),Et=s((e,t={})=>{let o=e?.mode??"autopilot";if(!xt(o))throw new Error(`toolApproval.mode must be ${[...Be].join(" | ")}, got: ${JSON.stringify(o)}`);let n=new Set;return {getMode:s(()=>o,"getMode"),setMode:s(i=>{if(!xt(i))throw new Error(`tool approval mode must be ${[...Be].join(" | ")}, got: ${JSON.stringify(i)}`);o=i;},"setMode"),remembered:n,gate:s(async(i,l,c)=>{let a=Rt({name:i,readOnly:c.readOnly,mode:o,rules:e?.rules,remembered:n,builtIn:c.builtIn});if(a.permission==="allow")return;let p=F.getStore(),d=p?.emit??t.fallbackEmit??(()=>{}),f=crypto.randomUUID(),u=s((b,O)=>{throw d({type:"tool.approval-resolved",id:f,name:i,approved:false,reason:b,automatic:O}),new fe(b)},"deny");a.permission==="deny"&&u(a.source==="rule"?`denied by rule "${a.rule}"`:`"${o}" mode allows read-only tools only`,true);let h=e?.onRequest;if(!h){u("no approval handler configured",true);return}let T=t.sanitize?await t.sanitize(i,l):l,x=p?.currentStep;d({type:"tool.approval-requested",id:f,name:i,input:T,readOnly:c.readOnly,...x?{step:x}:{}});let K={id:f,toolName:i,input:T,readOnly:c.readOnly,...x?{step:x}:{},...p?.runId?{runId:p.runId}:{}},L;try{L=await Ko(Promise.resolve().then(()=>h(K)),e?.timeoutMs,c.signal);}catch(b){if(b instanceof xe&&u(`no decision within ${e?.timeoutMs}ms`,true),c.signal?.aborted)throw d({type:"tool.approval-resolved",id:f,name:i,approved:false,reason:"aborted",automatic:true}),b;u(`approval handler failed: ${b?.message??String(b)}`,true);return}let g=Fo(L);if(g.approved&&g.remember&&n.add(i),d({type:"tool.approval-resolved",id:f,name:i,approved:g.approved,...g.reason?{reason:g.reason}:{},automatic:false}),!g.approved)throw new fe(g.reason)},"gate")}},"createApprovalController");var he=s(e=>e===false?{enabled:false}:e===void 0||e===true?{enabled:true}:{enabled:true,...e.ttl?{ttl:e.ttl}:{},...e.key?{key:e.key}:{}},"resolvePromptCaching"),Je=s((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),Pt=s((e,t,o)=>e.enabled?{openai:{promptCacheKey:e.key??`${t}:${o}`}}:void 0,"cacheProviderOptions"),Ho=s(e=>{let t=e.providerOptions;if(!t?.anthropic||!("cacheControl"in t.anthropic))return e;let{cacheControl:o,...n}=t.anthropic,{anthropic:r,...i}=t,l=Object.keys(n).length?{...i,anthropic:n}:i,{providerOptions:c,...a}=e;return Object.keys(l).length?{...a,providerOptions:l}:a},"withoutBreakpoint"),Ge=s((e,t)=>{if(!t.enabled||e.length===0)return e;let o=e.map((i,l)=>l<e.length-1?Ho(i):i),n=o[o.length-1],r=n.providerOptions??{};return o[o.length-1]={...n,providerOptions:{...r,anthropic:{...r.anthropic,cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}},o},"withRollingBreakpoint");var Mt=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"?Mt(o.cause,t):false},"isRetriable"),te=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(i){if(n=i,r===t.maxRetries||!Mt(i))throw i;t.onRetry?.(r+1,i);let l=o*2**r+Math.random()*250;await Wo(l,t.signal);}}throw n},"withRetry"),Wo=s((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let r=setTimeout(()=>{t?.removeEventListener("abort",i),o();},e),i=s(()=>{clearTimeout(r),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),Ye=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),G=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Ye([e,AbortSignal.timeout(t)]),"withTimeout"),qo=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),Bo=s(e=>{if(!e)return e;let t={};for(let[o,n]of Object.entries(e))t[o]=qo.has(o.toLowerCase())?"***redacted***":n;return t},"redactHeaders"),le=s(()=>({inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0,cacheWriteTokens:0}),"emptyUsage"),ye=s(e=>typeof e=="number"&&Number.isFinite(e)?e:0,"n"),z=s(e=>{if(!e)return le();let t=ye(e.inputTokens),o=ye(e.outputTokens);return {inputTokens:t,outputTokens:o,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:t+o,reasoningTokens:ye(e.outputTokenDetails?.reasoningTokens??e.reasoningTokens),cachedInputTokens:ye(e.inputTokenDetails?.cacheReadTokens??e.cachedInputTokens),cacheWriteTokens:ye(e.inputTokenDetails?.cacheWriteTokens)}},"normalizeUsage"),Te=s((e,t)=>({inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,totalTokens:e.totalTokens+t.totalTokens,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0),cachedInputTokens:(e.cachedInputTokens??0)+(t.cachedInputTokens??0),cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)}),"addUsage"),Lt=s((e,t)=>{Object.assign(e,Te(e,t));},"accumulateUsage"),ce=s((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText"),Ve=s(e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e),"errorMessage");var oe=s(e=>{let t=e.limits?.maxTotalTokens??e.maxTotalTokens;return {...e.limits,...t!==void 0?{maxTotalTokens:t}:{}}},"resolveLimits"),ke=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isCap"),$t=s(e=>!!(e&&(ke(e.maxInputTokens)||ke(e.maxOutputTokens)||ke(e.maxReasoningTokens)||ke(e.maxTotalTokens))),"hasTokenLimits"),Ce=s((e,t)=>{if(!t)return;let o=[["input",e.inputTokens,t.maxInputTokens],["output",e.outputTokens,t.maxOutputTokens],["reasoning",e.reasoningTokens??0,t.maxReasoningTokens],["total",e.totalTokens,t.maxTotalTokens]];for(let[n,r,i]of o)if(ke(i)&&r>=i)return {kind:n,tokens:r,cap:i}},"checkLimits"),Jo=s(e=>e.reduce((t,o)=>Te(t,z(o.usage)),le()),"sumStepUsage"),Ut=s((e,t,o)=>({steps:n})=>{let r=Ce(Te(e(),Jo(n)),t);return r?(o?.(r),true):false},"limitsStopCondition");var _t=s(e=>{if(!(e===void 0||e===false))return e===true?{level:"medium"}:typeof e=="string"?{level:e}:{...e,level:e.level??"medium"}},"normalizeThinking"),Ze=s(e=>{let t=_t(e);if(!t)return {};let o=t.level??"medium";if(o==="none")return {reasoning:"none"};let n=t.includeThoughts!==false,r=t.budgetTokens;if(typeof r=="number"&&Number.isFinite(r)&&r>0){let i=Math.floor(r);return {reasoning:o,providerOptions:{anthropic:{thinking:{type:"enabled",budgetTokens:i}},google:{thinkingConfig:{thinkingBudget:i,includeThoughts:n}}}}}return n?{reasoning:o,providerOptions:{google:{thinkingConfig:{includeThoughts:true}},openai:{reasoningSummary:"auto"}}}:{reasoning:o}},"resolveThinking"),Qe=s((e,t)=>{let o=e.stageThinking?.[t];return o!==void 0?o:e.thinking},"stageThinkingSetting"),Oe=s((e,t)=>_t(Qe(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),Xe=s(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),Nt=s((e,t)=>{let o={...e};for(let[n,r]of Object.entries(t))o[n]=Xe(o[n])&&Xe(r)?Nt(o[n],r):r;return o},"deepMerge"),et=s((...e)=>{let t;for(let o of e)if(o)for(let[n,r]of Object.entries(o))Xe(r)&&(t??={},t[n]=Nt(t[n]??{},r));return t},"mergeProviderOptions");var Dt=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),ne=s((e,t,o)=>{let n=he(e.promptCaching),r=Ze(Qe(e,t)),i=et(r.providerOptions,Pt(n,e.clientName,t)),l=Dt(oe(e).perCall?.[t]);return {instructions:Je(o,n),...r.reasoning?{reasoning:r.reasoning}:{},...i?{providerOptions:i}:{},...l?{maxOutputTokens:l}:{}}},"stageCallOptions"),we=s((e,t)=>{let o=Dt(oe(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var jt=128e3,Go=2e4,re=s((e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t,"nonNeg"),ue=s(e=>{let t=re(e?.contextWindowTokens,0)||jt;return {auto:e?.auto!==false,contextWindowTokens:t,thresholdTokens:re(e?.thresholdTokens,0)||Math.floor(t/2),keepRecentTurns:re(e?.keepRecentTurns,4),keepRecentSteps:re(e?.keepRecentSteps,3),summaryMaxTokens:re(e?.summaryMaxTokens,0)||1024,maxToolOutputChars:re(e?.maxToolOutputChars,Go),clearToolResultsAfterTokens:re(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:re(e?.keepToolResults,3)}},"resolveCompaction"),se=s(e=>Math.ceil(e.length/4),"estimateTokens"),ot="[Summary of earlier conversation]",nt=s(e=>e.role==="assistant"&&e.content.startsWith(ot),"isSummaryTurn"),tt=s(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
|
|
2
|
+
`),"renderTurns"),Yo=`You compress conversation history for an AI agent.
|
|
3
|
+
|
|
4
|
+
Summarize the conversation below into a compact, factual record that lets the agent continue the conversation without the original turns. Keep: what the user asked for and decided, facts and results the assistant reported (names, identifiers, numbers, URLs, file paths, dates), open questions and commitments. Drop greetings, filler and repetition. Write plain text in the conversation's language, no preamble.`,Vo=`You compress the execution trace of an AI agent.
|
|
5
|
+
|
|
6
|
+
Summarize the executed steps below into a compact, factual record the agent can rely on for the remaining steps. Keep every concrete result: identifiers, names, numbers, URLs, file paths, errors and what failed, and conclusions. Drop narration. Write plain text, no preamble.`,be=s(async(e,t,o={})=>{let n=se(tt(e)),r={history:e,beforeTokens:n,afterTokens:n,compacted:false},i=o.thresholdTokens??jt/2;if(!o.force&&n<=i)return r;let l=Math.max(0,o.keepRecentTurns??4),c=e.length-l;if(c<=0)return r;let a=e.slice(0,c);if(a.length===1&&nt(a[0]))return r;try{let p=await ai.generateText({model:t,instructions:Yo,prompt:`Conversation to summarize:
|
|
7
|
+
${tt(a)}`,maxOutputTokens:o.summaryMaxTokens??1024,abortSignal:G(o.signal,o.timeoutMs??0),maxRetries:0}),d=z(p.usage);o.onUsage?.(d);let f=p.text.trim();if(!f)return {...r,usage:d};let u=[{role:"assistant",content:`${ot}
|
|
8
|
+
${f}`},...e.slice(c)];return {history:u,summary:f,beforeTokens:n,afterTokens:se(tt(u)),compacted:!0,usage:d}}catch{return r}},"compactHistory"),Ft=s(async(e,t,o,n)=>{try{let r=await ai.generateText({model:o,instructions:Vo,prompt:[t?`Summary of the steps before these:
|
|
9
|
+
${t}
|
|
10
|
+
`:"",`Steps to summarize:
|
|
11
|
+
${n.render(e,n.offset)}`].filter(Boolean).join(`
|
|
12
|
+
`),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:G(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:z(r.usage)}:void 0}catch{return}},"summarizeTrace"),Kt=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:ce(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:ce(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:ce(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Xo=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),rt=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Kt(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Re={version:"0.0.31"};var an=ie__default.default.join(sn__default.default.homedir(),".agent","mcp-oauth.json"),Ee=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await promises.readFile(this.filePath,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}async writeAll(t){let o=`${this.filePath}.${process.pid}.tmp`;await promises.writeFile(o,JSON.stringify(t,null,2),{mode:384}),await promises.chmod(o,384).catch(()=>{}),await promises.rename(o,this.filePath);}enqueue(t){let o=this.queue.then(t,t);return this.queue=o.catch(()=>{}),o}async get(t){return this.enqueue(async()=>(await this.readAll())[t])}async set(t,o){await this.enqueue(async()=>{let n=await this.readAll();n[t]=o,await promises.mkdir(ie__default.default.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(t){await this.enqueue(async()=>{let o=await this.readAll();t in o&&(delete o[t],await this.writeAll(o));});}},st=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(t){return this.map.get(t)}async set(t,o){this.map.set(t,o);}async delete(t){this.map.delete(t);}},ln=30,cn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),pn=new Set(["localhost","127.0.0.1","[::1]","::1"]),it=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||pn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Pe=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Ee,this.ns=cn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??ln)*1e3,this.onAuthorizationUrl=t.onAuthorizationUrl,this._clientMetadata={client_name:t.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...t.scope?{scope:t.scope}:{},...t.clientMetadata},it(t.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(t){return `${this.ns}:${t}`}async readJSON(t){let o=await this.store.get(this.key(t));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(t));return}}async state(){let t=crypto.randomBytes(32).toString("hex");return await this.store.set(this.key("state"),t),t}async verifyState(t){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&t!==void 0&&o===t}async clientInformation(){return this.readJSON("client")}async saveClientInformation(t){await this.store.set(this.key("client"),JSON.stringify(t));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(t){let o={tokens:t,expiresAt:typeof t.expires_in=="number"?Date.now()+t.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(t){await this.store.set(this.key("verifier"),t);}async codeVerifier(){let t=await this.store.get(this.key("verifier"));if(!t)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return t}async redirectToAuthorization(t){this.authorizationUrl=t,await this.onAuthorizationUrl?.(t);}async invalidateCredentials(t){let o=t==="all"?["tokens","client","verifier","state"]:[t];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let t=await this.readJSON("tokens");return t?.tokens?.access_token?t.expiresAt===void 0?false:Date.now()+this.skewMs>=t.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},un=s(e=>new Pe(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth_js.auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),mn=s(async(e,t,o={})=>{if(!await e.verifyState(t.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth_js.auth(e,{serverUrl:e.serverUrl,authorizationCode:t.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var hn="@dudko.dev/agent",yn=Re.version,at,Tn=s(()=>(at||(at=api.trace.getTracer(hn,yn)),at),"tracer"),E={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"},J=s(async(e,t,o)=>Tn().startActiveSpan(e,async n=>{for(let[r,i]of Object.entries(t))i!==void 0&&n.setAttribute(r,i);try{let r=await o(n);return n.end(),r}catch(r){let i=r instanceof Error?r:new Error(String(r));throw n.recordException(i),n.setStatus({code:api.SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Ln=s(e=>"command"in e&&!!e.command,"isStdioConfig"),$n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Un=Re.version,lt=64,ve=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),_n=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,lt-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Me=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Jt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Jt;i++){let l=await e.listTools(n?{cursor:n}:void 0);o.push(...l.tools);let c=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!c||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),de=class extends Error{static{s(this,"RefreshOnlyAbort");}},zn=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new de},"state"),saveCodeVerifier:s(()=>{throw new de},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new de},"redirectToAuthorization")}),"refreshOnly"),jn=s(async(e,t,o,n,r)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth_js.auth(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof de?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Gt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,O)=>{let H=`${ve(g)}__`;for(let I of f.get(g)??[])delete a[I];for(let I=p.length-1;I>=0;I--)p[I].server===g&&p.splice(I,1);let $=[],_=0,R=0;for(let I of O){let v=H+ve(I.name);if(v.length>lt){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${lt}-char limit enforced by major LLM providers; skipping`),R++;continue}let C=_n(v,a);if(!C){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}C!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${C}"`);let U=I.description??"",W=I.annotations?.readOnlyHint===true;a[C]=ai.dynamicTool({description:U,inputSchema:ai.jsonSchema(I.inputSchema),execute:s(async(q,k)=>J("agent.tool_call",{[E.TOOL_NAME]:C},async P=>{let D=q??{};if(i)try{let S=await i(C,D);D=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${C}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),D={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:D},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let m=w.isError===true,y=w.content;if(n)try{y=await n(C,y);}catch(S){if(t("warn",`[mcp] ${C}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Me("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:C,sandboxDir:m?void 0:qe()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Me(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&V(a[C]),p.push({name:C,description:U,server:g,readOnly:W}),$.push(C),_++;}f.set(g,$),R>0?t("info",`[mcp] ${g}: ${_} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${_} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Jt} pages; the rest is ignored`)),"listServerTools"),T=s(async(g,b)=>{u(g,b,await h(g,b));},"registerServerTools"),x=s(async(g,b)=>{let O=b.connectTimeoutMs??l.connectTimeoutMs,H=typeof O=="number"&&Number.isFinite(O)&&O>=0?O:Nn,$,_=false,R=K(g,b,I=>{$=I;},()=>_);try{return await(H>0?Fn(R,H,()=>{_=!0;}):R)}catch(I){$&&await $.close().catch(()=>{});let v=_?`connect timed out after ${H}ms`:I.message,C=!_&&I instanceof auth_js.UnauthorizedError;return t("error",C?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:C}}},"openConnection"),K=s(async(g,b,O,H)=>{let $,_=s(async()=>{if(H())throw await $?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(b)){let v=b.env?{...stdio_js.getDefaultEnvironment(),...b.env}:void 0;R=new stdio_js.StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if($n(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),it(b.url,`MCP server "${g}"`),await jn(b.authProvider,b.url,b.fetch,t,g)),R=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await _(),$=new index_js.Client({name:o,version:Un}),O($),await $.connect(R),await _(),r&&$.setNotificationHandler(types_js.ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,$);return await _(),{name:g,client:$,listed:I}}catch(R){throw $&&await $.close().catch(()=>{}),R}},"connectOnce"),L=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of L){if(!g.client||!g.listed){d.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),u(g.name,g.client,g.listed),d.push({name:g.name,connected:true});}return {tools:a,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:s(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await T(g,b);},"refreshServer")}},"connectMcpServers"),Fn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),n(l);},l=>{clearTimeout(i),r(l);});}),"withConnectTimeout"),qt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return qt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?qt[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"),Hn=/[^a-zA-Z0-9_-]/g,Bt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=crypto.randomUUID().slice(0,8),p=ie__default.default.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await promises.writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Wn=s(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(`
|
|
13
|
+
`);let r=t?.sandboxDir,i=t?.toolName??"tool",l,c=s(()=>r?(l||(l=promises.mkdir(r,{recursive:true}).then(()=>{})),l):Promise.resolve(),"ensureDir"),a=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){a.push(p.text);continue}if(r&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let d=await Bt(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,i,r,c);a.push(d);continue}if(r&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let d=p.resource;if(typeof d.blob=="string"){let f=await Bt(d.blob,typeof d.mimeType=="string"?d.mimeType:void 0,"resource",i,r,c);typeof d.uri=="string"&&(f.uri=d.uri),a.push(f);continue}if(typeof d.text=="string"){a.push(d.text);continue}}a.push(p);}return a},"flattenContent"),ct=s((e,t,o,n,r)=>{let i=o?.length?new Set(o.map(ve)):null,l=n?.length?new Set(n.map(ve)):null,c=new Set,a={},p=[];for(let d of t){if((i?.has(d.name)||l?.has(d.name))&&c.add(d.name),i&&!i.has(d.name)||!i&&l?.has(d.name))continue;let f=e[d.name];f&&(a[d.name]=f,p.push(d));}if(r)for(let[d,f]of [["availableTools",o],["excludedTools",n]])for(let u of f??[])c.has(ve(u))||r("warn",`[mcp] ${d}: "${u}" matches no discovered tool`);return {tools:a,catalog:p}},"filterTools");var Le=s((e,t,o,n)=>{let r=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,l=t?.baseURL??e.baseURL,c=t?.model??o??e.model,a=t?.providerOptions??e.providerOptions??{};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(qn.has(r)&&!l)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:l,apiKey:i,model:c,providerOptions:a}},"resolveStage"),qn=new Set(["openai-compatible","azure"]),X={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"},Z=s(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),$e=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await Z(X.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await Z(X.anthropic);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await Z(X["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await Z(X.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await Z(X.xai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await Z(X.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await Z(X["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await Z(X["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await Z(X.deepseek);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let r=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...l}=o;if(!r&&!("binding"in l))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await Z(X.cloudflare),a="binding"in l?l:{accountId:r,apiKey:t.apiKey,...l};return c(a)(t.model)}}},"buildModelFromStage");var Bn=s(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,r)=>n.type==="tool-result"?[`${o}:${r}`]:[]):[]),"positionsOf"),Jn=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Yt=s(e=>{try{return se(JSON.stringify(e))}catch{return 0}},"estimate"),pt=s((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,r=s(i=>n.size===0?i:i.map((l,c)=>l.role==="tool"&&Array.isArray(l.content)?{...l,content:l.content.map((a,p)=>a.type==="tool-result"&&n.has(`${c}:${p}`)?{...a,output:{type:"text",value:Jn(a.toolName)}}:a)}:l),"apply");return i=>{let l=r(i),c=Yt(l);if(c<=e.triggerTokens)return l;let a=Bn(i),p=0;for(let f of a.slice(0,Math.max(0,a.length-o)))n.has(f)||(n.add(f),p+=1);if(p===0)return l;let d=r(i);return t?.({cleared:p,beforeTokens:c,afterTokens:Yt(d)}),d}},"createToolResultClearer");var Xt=/^[a-z0-9-]{1,64}$/,Yn="load_skill",Vn="read_skill_file",Xn=24e3,eo=s(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=ie__default.default.posix.normalize(t);if(!o||o==="."||o.startsWith("/")||o===".."||o.startsWith("../"))throw new Error(`skill file path must be relative and stay inside the skill: "${e}"`);return o},"normalizeSkillPath"),ut=s(e=>{if(!e||typeof e!="object")throw new Error("skill must be an object { name, description, content, files? }");let{name:t,description:o,content:n,files:r}=e;if(typeof t!="string"||!Xt.test(t))throw new Error(`skill name must match ${Xt} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof n!="string")throw new Error(`skill "${t}": content must be a string`);if(r!==void 0&&!Array.isArray(r))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,l=(r??[]).map(c=>{if(!c||typeof c.path!="string"||typeof c.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let a;try{a=eo(c.path);}catch(p){throw new Error(`skill "${t}": ${p.message}`)}if(i.has(a))throw new Error(`skill "${t}": duplicate file "${a}"`);return i.add(a),{path:a,content:c.content}});return {name:t,description:o.trim(),content:n,...l.length?{files:l}:{}}},"defineSkill"),Zn=s(e=>{let t=e.trim();if(t.length>=2&&t.startsWith('"')&&t.endsWith('"'))try{return JSON.parse(t)}catch{return t.slice(1,-1)}return t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/''/g,"'"):t.replace(/\s+#.*$/,"")},"unquote"),Qn=s(e=>{let t={},o=e.split(`
|
|
14
|
+
`);for(let n=0;n<o.length;n++){let r=o[n],i=/^([A-Za-z0-9_-]+)\s*:(.*)$/.exec(r);if(!i)continue;let l=i[1],c=i[2].trim(),a=/^([>|])([+-]?)\s*(#.*)?$/.exec(c);if(a){let p=[];for(;n+1<o.length&&(/^\s/.test(o[n+1])||o[n+1].trim()==="");)p.push(o[++n]);for(;p.length&&p[p.length-1].trim()==="";)p.pop();let d=Math.min(...p.filter(u=>u.trim()).map(u=>/^\s*/.exec(u)[0].length)),f=p.map(u=>u.slice(Number.isFinite(d)?d:0));t[l]=a[1]==="|"?f.join(`
|
|
15
|
+
`):f.join(`
|
|
16
|
+
`).split(/\n\s*\n/).map(u=>u.replace(/\n/g," ").trim()).join(`
|
|
17
|
+
`);continue}t[l]=Zn(c);}return t},"parseFrontmatter"),to=s((e,t)=>{let o=e.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
18
|
+
`),n=/^\s*---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n|$)/.exec(o);if(!n)throw new Error('SKILL.md must start with a frontmatter block between "---" lines');let r=Qn(n[1]);if(!r.name)throw new Error('SKILL.md frontmatter is missing "name"');if(!r.description)throw new Error(`SKILL.md "${r.name}": frontmatter is missing "description"`);return ut({name:r.name,description:r.description,content:o.slice(n[0].length).trim(),...t?.length?{files:t}:{}})},"parseSkillMarkdown"),er=new Set([".md",".txt",".json",".yaml",".yml",".csv",".ts",".js",".py",".sh",".html",".css",".xml",".toml"]),tr=256*1024,oo=s(async(e,t,o)=>{let n=await promises.readdir(t,{withFileTypes:true});n.sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){if(r.name.startsWith(".")||r.name==="node_modules")continue;let i=ie__default.default.join(t,r.name);if(r.isDirectory()){await oo(e,i,o);continue}if(!r.isFile())continue;let l=ie__default.default.relative(e,i).split(ie__default.default.sep).join("/");l==="SKILL.md"||!er.has(ie__default.default.extname(r.name).toLowerCase())||(await promises.stat(i)).size>tr||o.push({path:l,content:await promises.readFile(i,"utf8")});}},"collectFiles"),or=s(async e=>{let t=await promises.readdir(e,{withFileTypes:true});t.sort((r,i)=>r.name.localeCompare(i.name));let o=[],n=new Set;for(let r of t){if(!r.isDirectory()||r.name.startsWith(".")||r.name==="node_modules")continue;let i=ie__default.default.join(e,r.name),l;try{l=await promises.readFile(ie__default.default.join(i,"SKILL.md"),"utf8");}catch{continue}let c=[];await oo(i,i,c);let a;try{a=to(l,c);}catch(p){throw new Error(`${ie__default.default.join(i,"SKILL.md")}: ${p.message}`)}if(n.has(a.name))throw new Error(`duplicate skill name "${a.name}" in ${e}`);n.add(a.name),o.push(a);}return o},"loadSkillsFromDir"),no=s(e=>{let t=[],o=new Set;for(let n of e??[]){let r=ut(n);if(o.has(r.name))throw new Error(`duplicate skill name "${r.name}"`);o.add(r.name),t.push(r);}return t},"validateSkills"),nr=s((e,t)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}\u2026`:o},"oneLine"),dt=s(e=>e.map(t=>`- ${t.name}: ${nr(t.description,300)}`).join(`
|
|
19
|
+
`),"renderSkillsIndex"),ro=s((e,t,o=Xn)=>{let n=new Map(e.map(l=>[l.name,l])),r=[],i=0;for(let l of t){let c=n.get(l);if(!c)continue;let a=`### Skill: ${c.name}
|
|
20
|
+
${c.content.trim()}`,p=o-i;if(p<=0){r.push(`### Skill: ${c.name}
|
|
21
|
+
\u2026 [skill instructions clipped: budget exhausted]`);continue}if(a.length>p){r.push(`${a.slice(0,p)}
|
|
22
|
+
\u2026 [skill instructions clipped]`),i=o;continue}r.push(a),i+=a.length;}return r.join(`
|
|
23
|
+
|
|
24
|
+
`)},"renderActiveSkills"),mt=s((e,t,o,n,r)=>e.some(i=>i.name===t)?(n&&!n.activeSkills.includes(t)&&(n.activeSkills.push(t),r?.({type:"skill.activated",name:t,by:o})),true):false,"activateSkill"),so=s(e=>{if(!e.length)return {};let t=e.map(n=>n.name),o=s(n=>{let r=e.find(i=>i.name===n);if(!r)throw new Error(`Unknown skill "${n}". Available skills: ${t.join(", ")}`);return r},"find");return {[Yn]:V(ai.tool({description:"Load the full instructions of a skill from the SKILLS list and activate it for the rest of the task. Call it before doing work a skill covers.",inputSchema:zod.z.object({name:zod.z.string().describe(`Skill name, one of: ${t.join(", ")}`)}),execute:s(async({name:n})=>{let r=o(n),i=F.getStore();return mt(e,r.name,"tool",i?.state,i?.emit),{name:r.name,content:r.content,files:(r.files??[]).map(l=>l.path)}},"execute")})),[Vn]:V(ai.tool({description:"Read a file bundled with a skill (paths are listed by load_skill). Returns the file content.",inputSchema:zod.z.object({name:zod.z.string().describe("Skill name"),path:zod.z.string().describe("Skill-relative file path, as listed by load_skill")}),execute:s(async({name:n,path:r})=>{let i=o(n),l;try{l=eo(r);}catch(a){throw new Error(a.message)}let c=(i.files??[]).find(a=>a.path===l);if(!c){let a=(i.files??[]).map(p=>p.path);throw new Error(`Skill "${i.name}" has no file "${r}". Files: ${a.length?a.join(", "):"(none)"}`)}return c.content},"execute")}))}},"createSkillTools");var ee="find_tools",sr=40,ir=8,ar=20,Ne=s((e,t)=>{let o=e.toolSelectionStrategy??"auto";if(o==="auto"){let n=e.toolSearchThreshold??sr;return t>n?"search":"all"}return o},"resolveToolStrategy"),_e=s(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean),"tokenizeForSearch"),gt=s((e,t)=>e.some(o=>o===t||t.length>=3&&o.startsWith(t)),"hit"),ao=s((e,t,o={})=>{let n=[...new Set(_e(t))];if(n.length===0)return [];let r=Math.floor(o.limit??ir),i=Math.min(ar,Math.max(1,Number.isFinite(r)?r:8)),l=o.server?.trim().toLowerCase(),c=[];return e.forEach((a,p)=>{if(l&&(a.server??"").toLowerCase()!==l)return;let d=_e(a.name),f=_e(a.server??""),u=_e(a.description??""),h=0;for(let T of n)h+=(gt(d,T)?3:0)+(gt(f,T)?2:0)+(gt(u,T)?1:0);h>0&&c.push({entry:a,score:h,index:p});}),c.sort((a,p)=>p.score-a.score||a.index-p.index),c.slice(0,i).map(a=>a.entry)},"searchTools"),lr=12e3,cr=60,lo=s((e,t=lr)=>{if(e.length===0)return "(no tools available)";let o=new Map;for(let c of e){let a=c.server??"<native>",p=o.get(a)??[];p.push(c),o.set(a,p);}let n=[],r=0,i=0;e:for(let[c,a]of o){let p=`[${c}]`;if(r+p.length+1>t)break;n.push(p),r+=p.length+1;for(let d of a){let f=(d.description||"").replace(/\s+/g," ").trim().slice(0,cr),u=`- ${d.name}: ${f}`;if(r+u.length+1>t)break e;n.push(u),r+=u.length+1,i++;}}let l=e.length-i;return l>0&&n.push(`\u2026 ${l} more tools \u2014 the executor can find them with ${ee}`),n.join(`
|
|
25
|
+
`)},"renderSearchCatalog"),co=s(e=>({[ee]:V(ai.tool({description:"Search the full tool catalogue by keywords and ACTIVATE the matching tools: they become callable from your next step on. Use it whenever the tools you need are not loaded yet.",inputSchema:zod.z.object({query:zod.z.string().describe('Keywords describing the capability you need, e.g. "list github issues"'),server:zod.z.string().optional().describe("Restrict the search to one MCP server"),limit:zod.z.number().optional().describe("Max results (default 8, max 20)")}),execute:s(async({query:t,server:o,limit:n})=>{let r=ao(e(),t,{server:o,limit:n}),i=r.map(a=>a.name),l=F.getStore(),c=l?.state;if(c)for(let a of i){let p=c.discovered.indexOf(a);p>=0&&c.discovered.splice(p,1),c.discovered.push(a),c.stepActive?.add(a);}return l?.emit&&l.currentStep&&l.emit({type:"tools.discovered",step:l.currentStep,query:t,names:i}),{tools:r.map(a=>({name:a.name,description:a.description,server:a.server??"<native>",readOnly:a.readOnly===true}))}},"execute")}))}),"createFindToolsTool");var po=1500,uo=6e3,ht=s(e=>{if(!e?.length)return "(no prior conversation)";let t=nt(e[0])?e[0]:void 0,o=t?e.slice(1):e,n=o.slice(-8),r=o.length-n.length,i=[];if(t){let l=t.content.length>uo?`${t.content.slice(0,uo)}... [truncated]`:t.content;i.push(`${t.role}: ${l}`);}r>0&&i.push(`(${r} earlier turns omitted)`);for(let l of n){let c=l.content.length>po?`${l.content.slice(0,po)}... [truncated]`:l.content;i.push(`${l.role}: ${c}`);}return i.join(`
|
|
26
|
+
`)},"renderHistory"),ur={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},dr=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=ur[t],r=e.slice(0,o),i=e.length-r.length,l=r.map(c=>{let a=(c.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${c.name}: ${a}`});return i>0&&l.push(`... and ${i} more tools`),l.join(`
|
|
27
|
+
`)},"renderToolCatalog"),mo=s((e,t)=>t==="search"?lo(e):dr(e,t),"renderCatalogFor"),ft=1500,mr=s(e=>{let t;try{t=typeof e=="string"?e:JSON.stringify(e);}catch{t=String(e);}return t===void 0&&(t=String(e)),t.length>ft?`${t.slice(0,ft)}... [truncated, ${t.length-ft} chars]`:t},"truncateOutput"),gr=s((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${mr(n.output)}`).join(`
|
|
28
|
+
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
|
|
29
|
+
`)},"renderTraceEntry"),De=s((e,t=0)=>e.map((o,n)=>gr(o,t+n)).join(`
|
|
30
|
+
`),"renderTraceSteps"),me=s((e,t)=>{if(e.length===0)return "(no steps executed yet)";let o=t?.summary?Math.min(Math.max(t.upTo,0),e.length):0;if(o===0)return De(e);let n=[`Summary of earlier steps (1-${o}): ${t.summary}`];return o<e.length&&n.push(De(e.slice(o),o)),n.join(`
|
|
31
|
+
`)},"renderTrace"),yt=s(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
|
|
32
|
+
expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
|
|
33
|
+
suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
|
|
34
|
+
`),"renderPlan"),ze=s((e,t)=>t?`${e}
|
|
11
35
|
|
|
12
36
|
Domain context:
|
|
13
|
-
${
|
|
37
|
+
${t}`:e,"withDomainContext"),je=8,go=s(e=>`You are the Planner of a multi-step agent system.
|
|
14
38
|
|
|
15
39
|
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
40
|
|
|
17
41
|
Rules:
|
|
18
|
-
1. Produce 1-5 steps for typical requests (hard cap is
|
|
42
|
+
1. Produce 1-5 steps for typical requests (hard cap is ${e}). Prefer FEWER, larger steps over many micro-steps. If the task is trivial and needs no tools, output a single step "Answer the user directly".
|
|
19
43
|
2. Each step must be self-contained, action-oriented, and verifiable. State what should be done and what the expected outcome is.
|
|
20
44
|
3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
|
|
21
45
|
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
46
|
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.
|
|
47
|
+
6. The agent works autonomously: never plan a step that asks the user for clarification, confirmation or permission (the host handles tool consent). If the request is ambiguous, pick the most reasonable interpretation and state the assumption in the step description.
|
|
48
|
+
7. Output strict JSON matching the requested schema. No prose outside JSON.`,"plannerBase");go(je);var fr=`
|
|
24
49
|
|
|
25
50
|
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
|
-
|
|
51
|
+
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.`,hr=`
|
|
52
|
+
|
|
53
|
+
ADDITIONAL RULE (tool-search mode):
|
|
54
|
+
The tool catalogue is large; the list below may be abridged. suggestedTools are optional hints: name tools you are sure fit the step, the executor loads them up front and can discover any other tool itself with ${ee}. Never invent names.`,yr=`
|
|
55
|
+
|
|
56
|
+
SKILL SELECTION:
|
|
57
|
+
Skills are packaged instructions for specific kinds of work. Set "skills" to the names of the skills from the SKILLS list below that apply to this request (leave it empty when none does). Their instructions are given to the executor.`,Tr=s((e,t=je)=>go(t)+(e==="compact"?fr:e==="search"?hr:""),"buildPlannerSystem"),kr=s(e=>e?.length?`
|
|
58
|
+
|
|
59
|
+
SKILLS:
|
|
60
|
+
${dt(e)}`:"","skillsIndexSection"),Tt=s((e,t)=>{if(!e?.length||!t?.length)return "";let o=ro(e,t);return o?`
|
|
61
|
+
|
|
62
|
+
ACTIVE SKILLS (follow these instructions where they apply):
|
|
63
|
+
|
|
64
|
+
${o}`:""},"activeSkillsSection"),fo=s(e=>ze(Tr(e.mode,e.maxSteps)+(e.skills?.length?yr:""),e.domain)+kr(e.skills)+`
|
|
65
|
+
|
|
66
|
+
Available tools:
|
|
67
|
+
${mo(e.catalog,e.mode)}`,"composePlannerSystem"),ho=s((e,t)=>[t?.length?`Conversation history:
|
|
68
|
+
${ht(t)}
|
|
28
69
|
`:"",`User request:
|
|
29
|
-
${
|
|
30
|
-
|
|
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.
|
|
70
|
+
${e}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
71
|
+
`),"buildPlannerUserPrompt"),wr=`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
72
|
|
|
33
73
|
Rules:
|
|
34
74
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
35
75
|
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
76
|
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
77
|
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
|
-
|
|
78
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,br=`
|
|
79
|
+
|
|
80
|
+
TOOLS:
|
|
81
|
+
Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${ee} with a few keywords; the matching tools become callable from your next step on.`,vr=`
|
|
82
|
+
|
|
83
|
+
SKILLS:
|
|
84
|
+
Packaged instructions for specific kinds of work. When one of these applies to the current step and is not active yet, call load_skill with its name before doing the work; read_skill_file reads files it bundles.`,yo=s(e=>ze(wr,e.domain)+(e.skills?.length?`${vr}
|
|
85
|
+
${dt(e.skills)}`:"")+(e.searchMode?`${br}${e.toolCount?` The catalogue has ${e.toolCount} tools.`:""}`:"")+Tt(e.skills,e.activeSkills),"composeExecutorSystem"),To=s((e,t,o,n,r,i)=>[r?.length?`Conversation history:
|
|
86
|
+
${ht(r)}
|
|
40
87
|
`:"",`Original user request:
|
|
41
|
-
${
|
|
42
|
-
${
|
|
43
|
-
${
|
|
44
|
-
`),"buildExecutorUserPrompt"),
|
|
88
|
+
${e}`,"",`Overall plan:
|
|
89
|
+
${yt(t)}`,"",`Trace so far:
|
|
90
|
+
${me(n,i)}`,"",`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(`
|
|
91
|
+
`),"buildExecutorUserPrompt"),Sr=`You are the Replanner of an autonomous multi-step agent system. After an Executor step you decide what should happen next.
|
|
45
92
|
|
|
46
93
|
You have three options:
|
|
47
94
|
- "continue": the next planned step is still appropriate.
|
|
48
95
|
- "revise": the plan is wrong or incomplete given what we now know - produce a NEW plan covering only the REMAINING work (do not include already-completed steps). The new plan must follow the same rules as the original Planner.
|
|
49
|
-
- "finish": we already have enough information to answer the user. The system will then synthesize the final answer from the trace.
|
|
96
|
+
- "finish": we already have enough information to answer the user, or nothing more can be done. The system will then synthesize the final answer from the trace.
|
|
50
97
|
|
|
51
98
|
Rules:
|
|
52
99
|
1. Prefer "continue" when the original plan still applies. Revise only when needed.
|
|
53
100
|
2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
|
|
54
|
-
3. When
|
|
55
|
-
4.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
101
|
+
3. When a step failed or was blocked, prefer revising around the failure (another tool, other arguments, another source, a reasonable assumption) over finishing with nothing. Finish only when no workable alternative remains.
|
|
102
|
+
4. Never revise into a step that asks the user for input, clarification or permission - the agent runs autonomously.
|
|
103
|
+
5. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
|
|
104
|
+
6. Output strict JSON matching the schema. No prose outside JSON.`,ko=s(e=>ze(Sr,e.domain)+`
|
|
105
|
+
|
|
106
|
+
Available tools (for the revise option):
|
|
107
|
+
${mo(e.catalog,e.mode)}`+Tt(e.skills,e.activeSkills),"composeReplannerSystem"),wo=s((e,t,o,n,r)=>[`Original user request:
|
|
108
|
+
${e}`,"",`Current plan:
|
|
109
|
+
${yt(t)}`,"",`Completed steps:
|
|
110
|
+
${me(o,r)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","","Decide now: continue, revise, or finish."].join(`
|
|
111
|
+
`),"buildReplannerUserPrompt"),Ir=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
61
112
|
|
|
62
113
|
Rules:
|
|
63
|
-
1. Answer the user directly and concisely. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
64
|
-
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes).
|
|
65
|
-
3.
|
|
66
|
-
4.
|
|
67
|
-
|
|
114
|
+
1. Answer the user directly and concisely: report what was done and what was found. Do NOT mention "steps", "plans", or internal mechanics unless the user explicitly asked for them.
|
|
115
|
+
2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes). Never invent results the trace does not contain.
|
|
116
|
+
3. Mention the assumptions the agent made, briefly.
|
|
117
|
+
4. If the trace shows the request (or part of it) could not be completed, say so plainly and explain what blocked it.
|
|
118
|
+
5. Do not end with questions or offers unless the request genuinely cannot be completed without input from the user.
|
|
119
|
+
6. Use the user's language.`,bo=s(e=>ze(Ir,e.domain)+Tt(e.skills,e.activeSkills),"composeSynthesizerSystem"),vo=s((e,t,o,n,r)=>[n?.length?`Conversation history:
|
|
120
|
+
${ht(n)}
|
|
68
121
|
`:"",`User request:
|
|
69
|
-
${
|
|
70
|
-
${
|
|
71
|
-
${
|
|
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=ai.streamText({model:a.executorModel,tools:c,...i?{activeTools:Object.keys(c)}:{},stopWhen:ai.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=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")}),Le=8,he=zod.z.object({thought:zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:zod.z.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=ai.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=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: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 ai.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=ai.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__default.default.join(Qe.tmpdir(),"agent-sandbox");return we__default.default.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??crypto.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 promises.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");exports.FileOAuthStore=V;exports.MemoryOAuthStore=re;exports.NodeOAuthProvider=X;exports.beginMcpOAuth=st;exports.createAgent=Dn;exports.createNodeOAuthProvider=rt;exports.finishMcpOAuth=it;exports.getCurrentRunId=Ye;exports.getCurrentRunSandbox=ne;exports.redactHeaders=Ft;
|
|
122
|
+
${e}`,"",`Plan that was executed:
|
|
123
|
+
${yt(t)}`,"",`Execution trace:
|
|
124
|
+
${me(o,r)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
125
|
+
`),"buildSynthesizerUserPrompt");var xr=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")}),Cr=je,kt=zod.z.object({thought:zod.z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:zod.z.array(xr).min(1),skills:zod.z.array(zod.z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),Fe=s(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):Cr},"planStepCap"),ge=s(e=>{if(e.run)return e.run.strategy;let t=Ne(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"effectiveToolStrategy"),wt=s(e=>e==="plan-narrowed"?"compact":e==="search"?"search":"full","catalogModeFor"),bt=s((e,t)=>{if(!t?.length)return;let o=new Set((e.skills??[]).map(i=>i.name)),n=[...new Set(t.filter(i=>o.has(i)))],r=t.filter(i=>!o.has(i));return r.length&&e.emit({type:"log",level:"warn",message:`[plan] dropped unknown skills: ${r.join(", ")}`}),n.length?n:void 0},"filterPlanSkills"),So=s(async(e,t,o,n)=>J("agent.plan",{[E.PHASE]:"plan"},async r=>{let i=new Set(o.toolCatalog.map(u=>u.name)),l=wt(ge(o)),c=Fe(o),{object:a,usage:p}=await te(()=>Or(e,t,l,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((u,h)=>o.emit({type:"retry",phase:"plan",attempt:u,error:h.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:p}),r.setAttribute(E.USAGE_TOTAL_TOKENS,p.totalTokens);let d=a.steps.slice(0,c);d.length<a.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${a.steps.length} steps; truncated to hard cap ${c}`});let f=bt(o,a.skills);return {thought:a.thought,...f?{skills:f}:{},steps:d.map(u=>{if(!u.suggestedTools?.length)return u;let h=u.suggestedTools.filter(x=>i.has(x)),T=u.suggestedTools.length-h.length;return T>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${u.id}" had ${T} unknown suggestedTools, stripped`}),h.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${u.id}" had no valid suggestedTools left; falling back to full toolset`}),{...u,suggestedTools:void 0,requiresTools:true}):{...u,suggestedTools:h}})}}),"createInitialPlan"),Or=s(async(e,t,o,n,r)=>{let i=ne(n.config,"planner",fo({mode:o,catalog:n.toolCatalog,maxSteps:Fe(n),domain:n.config.systemPrompt,skills:n.skills})),l=ai.streamObject({model:n.plannerModel,schema:kt,...i,prompt:ho(e,t),abortSignal:G(r,n.config.llmTimeoutMs??0)}),c="",a=false,p=0;for await(let u of l.partialObjectStream){let h=u?.thought;typeof h=="string"&&h!==c&&(h.startsWith(c)?n.emit({type:"plan.thought-delta",delta:h.slice(c.length)}):a||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),a=true),c=h);let T=u?.steps;if(Array.isArray(T)&&T.length>p)for(;p<T.length;){let x=T[p];if(!x||typeof x.description!="string"||!x.description.length)break;let K={id:typeof x.id=="string"&&x.id?x.id:`s${p+1}`,description:x.description,expectedOutcome:typeof x.expectedOutcome=="string"?x.expectedOutcome:"",suggestedTools:Array.isArray(x.suggestedTools)?x.suggestedTools.filter(L=>typeof L=="string"):void 0};n.emit({type:"plan.step-added",step:K,index:p}),p++;}}let[d,f]=await Promise.all([l.object,l.usage]);return {object:d,usage:z(f)}},"streamPlanOnce");var Pr=s((e,t)=>{if(ge(e)!=="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 i=e.tools[r];i&&(n[r]=i);}return n},"buildActiveToolSet"),Io="[BLOCKER]",Mr=s(e=>e.includes(Io)?{summary:e.split(Io).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),vt=4e3,Lr=s(e=>e.length>vt?`${e.slice(0,vt)}... [truncated, ${e.length-vt} chars]`:e,"truncateForTrace"),Ao=s(async(e,t,o,n,r,i,l)=>J("agent.execute_step",{[E.PHASE]:"execute",[E.STEP_ID]:o.id},async c=>{let a=Date.now(),p=await te(()=>Ur(e,t,o,n,r,i,l),{maxRetries:i.config.llmMaxRetries??2,signal:l,onRetry:s((d,f)=>i.emit({type:"retry",phase:"execute",attempt:d,error:f.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:p.usage}),c.setAttribute(E.USAGE_TOTAL_TOKENS,p.usage.totalTokens),c.setAttribute(E.STEP_BLOCKED,p.blocked),c.setAttribute(E.TOOL_COUNT,p.toolCalls.length),{step:o,summary:p.summary,toolCalls:p.toolCalls,durationMs:Date.now()-a,blocked:p.blocked}}),"executeStep"),$r=s((e,t)=>{let o=ge(e),n=e.builtinTools??{};if(o==="search"){let l={...e.tools,...n,...e.findTools??{}},c=new Set([...Object.keys(n),...Object.keys(e.findTools??{})]);for(let a of t.suggestedTools??[])e.tools[a]&&c.add(a);for(let a of (e.run?.discovered??[]).slice(-16))e.tools[a]&&c.add(a);return {tools:l,active:c}}let r=Pr(e,t),i=Object.keys(n).length?{...r,...n}:r;return o==="plan-narrowed"?{tools:i,activeTools:Object.keys(i)}:{tools:i}},"buildExecutorTools"),Ur=s(async(e,t,o,n,r,i,l)=>{let c=[],a=new Map,{tools:p,activeTools:d,active:f}=$r(i,o),u=i.run;u&&(u.stepActive=f);let h=s(async(k,P)=>{let D=i.config.inputSanitizer;if(!D)return P;try{return await D(k,P)}catch(w){return i.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${k} - ${w.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),T,x=[ai.stepCountIs(i.config.maxStepsPerTask)],K=oe(i.config);u&&$t(K)&&x.push(Ut(()=>u.usage,K,()=>{T="tokens";}));let L=i.config.maxToolCalls;u&&typeof L=="number"&&L>0&&x.push(()=>u.toolCalls>=L?(T??="tool-calls",true):false);let g=ne(i.config,"executor",yo({domain:i.config.systemPrompt,skills:i.skills,activeSkills:u?.activeSkills,searchMode:!!f,toolCount:i.toolCatalog.length})),b=Oe(i.config,"executor"),O=u?{summary:u.traceSummary,upTo:u.traceSummaryUpTo}:void 0,H=he(i.config.promptCaching),$=ue(i.config.compaction),_=$.clearToolResultsAfterTokens>0?pt({triggerTokens:$.clearToolResultsAfterTokens,keep:$.keepToolResults},k=>{i.emit({type:"log",level:"info",message:`[executor] cleared ${k.cleared} stale tool result(s) from the step's context`}),i.emit({type:"context.compacted",scope:"tool-results",beforeTokens:k.beforeTokens,afterTokens:k.afterTokens});}):void 0,R=H.enabled||!!_,I=ai.streamText({model:i.executorModel,tools:p,...d?{activeTools:d}:{},...f||R?{prepareStep:s(({messages:k})=>{let P=Ge(_?_(k):k,H);return {...f?{activeTools:[...f].filter(D=>D in p)}:{},...R?{messages:P}:{}}},"prepareStep")}:{},stopWhen:x,...g,prompt:To(e,t,o,n,r,O),abortSignal:G(l,i.config.llmTimeoutMs??0)});for await(let k of I.fullStream)switch(k.type){case "text-delta":k.text&&i.emit({type:"step.text-delta",step:o,delta:k.text});break;case "reasoning-delta":k.text&&b&&i.emit({type:"step.reasoning-delta",step:o,delta:k.text});break;case "tool-call":{let P=await h(k.toolName,k.input);a.set(k.toolCallId,{name:k.toolName,input:P}),i.emit({type:"step.tool-call",step:o,name:k.toolName,input:P});break}case "tool-result":{if(k.preliminary)break;let D=a.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:D,output:k.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:k.toolName,output:k.output,ok:true}),a.delete(k.toolCallId);break}case "tool-error":{let D=a.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:D,output:k.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:k.toolName,output:k.error,ok:false}),a.delete(k.toolCallId);break}case "error":{let P=k.error;throw P instanceof Error?P:new Error(String(P))}}let[v,C]=await Promise.all([I.text,I.usage]),{summary:U,blocked:W}=Mr(v.trim());return {summary:U.length>0?Lr(U):T?`Stopped early: the run's ${T==="tokens"?"token":"tool-call"} budget was reached after ${c.length} tool call(s).`:c.length>0?`Executed ${c.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:c,blocked:W,usage:C?z(C):le()}},"runOnce");var Nr=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:kt.describe("Plan covering ONLY the remaining work")})]),xo=s(async(e,t,o,n,r,i)=>J("agent.replan",{[E.PHASE]:"replan"},async l=>{let c=wt(ge(r)),a=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,{object:p,usage:d}=await te(async()=>{let f=ne(r.config,"replanner",ko({mode:c,catalog:r.toolCatalog,domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),u=await ai.generateObject({model:r.plannerModel,schema:Nr,...f,prompt:wo(e,t,o,n,a),abortSignal:G(i,r.config.llmTimeoutMs??0)}),h=z(u.usage);return {object:u.object,usage:h}},{maxRetries:r.config.llmMaxRetries??2,signal:i,onRetry:s((f,u)=>r.emit({type:"retry",phase:"replan",attempt:f,error:u.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:d}),l.setAttribute(E.REPLAN_MODE,p.mode),l.setAttribute(E.USAGE_TOTAL_TOKENS,d.totalTokens),p}),"decideNextAction");var Co=s(async(e,t,o,n,r,i)=>J("agent.synthesize",{[E.PHASE]:"synthesize"},async l=>{let{text:c,usage:a}=await te(()=>zr(e,t,o,n,r,i),{maxRetries:r.config.llmMaxRetries??2,signal:i,onRetry:s((p,d)=>r.emit({type:"retry",phase:"synthesize",attempt:p,error:d.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:a}),l.setAttribute(E.USAGE_TOTAL_TOKENS,a.totalTokens),c}),"synthesizeAnswer"),zr=s(async(e,t,o,n,r,i)=>{let l=ne(r.config,"synthesizer",bo({domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),c=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,a=Oe(r.config,"synthesizer"),p=ai.streamText({model:r.synthesizerModel,...l,prompt:vo(e,t,o,n,c),abortSignal:G(i,r.config.llmTimeoutMs??0)});for await(let u of p.fullStream)if(u.type==="text-delta")u.text&&r.emit({type:"final.text-delta",delta:u.text});else if(u.type==="reasoning-delta")u.text&&a&&r.emit({type:"final.reasoning-delta",delta:u.text});else if(u.type==="error"){let h=u.error;throw h instanceof Error?h:new Error(String(h))}let[d,f]=await Promise.all([p.text,p.usage]);return {text:d,usage:z(f)}},"streamOnce");var Ro=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"),Hr=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return Ro(t);let n=s(()=>Ro(t),"fallback"),{signal:r}=o,i=o.timeoutMs??0;if(r?.aborted)return n();let l=(async()=>{try{return !!await e(t)}catch(a){return o.onError?.(a),n()}})(),c=Number.isFinite(i)&&i>0;return !c&&!r?l:new Promise(a=>{let p=false,d,f=s(h=>{p||(p=true,d!==void 0&&clearTimeout(d),r?.removeEventListener("abort",u),a(h));},"finish");function u(){f(n());}s(u,"onAbort"),c&&(d=setTimeout(()=>f(n()),i)),r?.addEventListener("abort",u,{once:true}),l.then(f,()=>f(n()));})},"replanTriggered"),Ke=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Wr=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||ie__default.default.join(sn.tmpdir(),"agent-sandbox");return ie__default.default.join(o,t)},"resolveSandboxDir"),Eo=/^[a-zA-Z0-9_-]{1,128}$/,St=s((e,t)=>{if(!Eo.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Eo}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),qr=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(St(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(St(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"),Po=s(async(e,t)=>{let o=await qr(e,t),n=o?.runId??crypto.randomUUID();St(n,"runId");let r=o?.startedAt??Date.now(),i=Wr(e,n);return F.run({runId:n,startedAt:r,sandboxDir:i},async()=>J("agent.run",{[E.RUN_ID]:n,[E.PROVIDER]:e.config.providerType,[E.MODEL]:e.config.model},async l=>{try{let c=await Jr(e,t,o);return l.setAttribute(E.ITERATIONS,c.iterations),l.setAttribute(E.USAGE_TOTAL_TOKENS,c.usage.totalTokens),l.setAttribute(E.USAGE_INPUT_TOKENS,c.usage.inputTokens),l.setAttribute(E.USAGE_OUTPUT_TOKENS,c.usage.outputTokens),c}finally{e.config.keepSandbox||await promises.rm(i,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Br=s(e=>{let t=Ne(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"runToolStrategy"),Jr=s(async(e,t,o)=>{let{signal:n}=t,r=o?.input??t.input,i=o?.history?[...o.history]:t.history?[...t.history]:void 0,l=t.onEvent??(()=>{}),c=ue(e.config.compaction),a=oe(e.config),p=e.config.maxToolCalls,d=z(o?.usage),f=F.getStore()?.startedAt??Date.now(),u=F.getStore()?.runId??"<unknown>",h={usage:d,toolCalls:o?.toolCallCount??0,strategy:Br(e),discovered:[],activeSkills:[...o?.activeSkills??[]],traceSummary:o?.traceSummary,traceSummaryUpTo:o?.traceSummaryUpTo??0},T={...e,run:h,emit:s(w=>{w.type==="usage"&&Lt(d,w.usage);let m={...w,runId:F.getStore()?.runId};try{l(m);}catch{}try{e.emit(m);}catch{}},"emit")},x=F.getStore();x&&(x.emit=T.emit,x.state=h);let K=s((w,m)=>{mt(e.skills??[],w,m,h,T.emit);},"activate"),L=e.config.persistence,g=s(async(w,m)=>{let y=L?.[w];if(y)try{await y(m);}catch(A){T.emit({type:"log",level:"warn",message:`[persistence] ${w} threw: ${A.message}`});}},"callPersistence"),b;if(!o&&i?.length&&c.auto){let w=await be(i,e.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:we(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,onUsage:s(m=>T.emit({type:"usage",phase:"compact",usage:m}),"onUsage")});w.compacted&&(i=w.history,b=w.history,T.emit({type:"context.compacted",scope:"history",beforeTokens:w.beforeTokens,afterTokens:w.afterTokens}));}let O=s(async w=>{if(!c.auto||n?.aborted)return;let m=s(()=>({summary:h.traceSummary,upTo:h.traceSummaryUpTo}),"view"),y=se(me(w,m()));if(y<=c.thresholdTokens)return;let A=w.length-c.keepRecentSteps,S=h.traceSummary?h.traceSummaryUpTo:0;if(A<=S)return;let j=await Ft(w.slice(S,A),h.traceSummary,e.synthesizerModel,{summaryMaxTokens:we(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,render:De,offset:S});j&&(T.emit({type:"usage",phase:"compact",usage:j.usage}),h.traceSummary=j.summary,h.traceSummaryUpTo=A,T.emit({type:"context.compacted",scope:"trace",beforeTokens:y,afterTokens:se(me(w,m()))}));},"maybeCompactTrace"),H=false,$=s(()=>{let w=Ce(d,a);if(w)return w;if(typeof p=="number"&&p>0&&h.toolCalls>=p)return {kind:"tool-calls",tokens:h.toolCalls,cap:p}},"budgetBreach"),_=s(()=>{let w=$();return w?(H||(H=true,T.emit({type:"budget.exceeded",...w})),true):false},"reportBudget"),R;if(o)R=o.plan,T.emit({type:"log",level:"info",message:`[resume] continuing run ${u} from step ${o.stepIndex}/${R.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),T.emit({type:"plan.created",plan:R});else {try{R=await So(r,i,T,n);}catch(w){if(T.emit({type:"error",error:Ie(w),phase:"plan"}),Ke(w)||n?.aborted)throw await g("onRunComplete",{runId:u,startedAt:f,status:"cancelled",input:r,history:i,trace:[],usage:d,stepIndex:0,iterations:0,revisions:0,error:w.message,completedAt:Date.now()}),w;R={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."}]};}T.emit({type:"plan.created",plan:R});for(let w of R.skills??[])K(w,"plan");}let I=o?[...o.trace]:[],v=R,C=o?.stepIndex??0,U=o?.iterations??0,W=o?.revisions??0,q=e.config.maxRevisions??2,k=s((w,m={})=>({runId:u,startedAt:f,status:w,input:r,history:i,plan:v,trace:I,usage:d,stepIndex:C,iterations:U,revisions:W,...h.traceSummary?{traceSummary:h.traceSummary,traceSummaryUpTo:h.traceSummaryUpTo}:{},...h.activeSkills.length?{activeSkills:[...h.activeSkills]}:{},...h.toolCalls?{toolCallCount:h.toolCalls}:{},...m}),"buildSnapshot");o||await g("onRunStart",k("executing"));let P=s(async()=>{await g("onStepComplete",k("executing"));},"persistCheckpoint");for(;U<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(C>=v.steps.length||_())break;U++;let w=v.steps[C];x&&(x.currentStep=w),T.emit({type:"step.start",step:w,index:C});let m=new AbortController;if(t.onStepStart)try{t.onStepStart({step:w,index:C,abort:s(()=>m.abort(),"abort")});}catch(N){T.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${N.message}`});}let y=Ye([n,m.signal]),A;try{await O(I),A=await Ao(r,v,w,I,i,T,y);}catch(N){if(n?.aborted)throw T.emit({type:"error",error:Ie(N),phase:"execute"}),await g("onRunComplete",k("cancelled",{error:N.message,completedAt:Date.now()})),N;if(m.signal.aborted&&Ke(N))T.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),A={step:w,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw T.emit({type:"error",error:Ie(N),phase:"execute"}),await g("onRunComplete",k("failed",{error:N.message,completedAt:Date.now()})),N}if(I.push(A),T.emit({type:"step.complete",step:w,result:A}),_()){C++;break}let S=v.steps[C+1]??null;if(S===null){T.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await Hr(e.config.replanAfter,A,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:s(N=>T.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${N.message}`}),"onError")})){T.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),C++,await P();continue}let B;try{await O(I),B=await xo(r,v,I,S,T,n);}catch(N){throw T.emit({type:"error",error:Ie(N),phase:"replan"}),await g("onRunComplete",k(Ke(N)||n?.aborted?"cancelled":"failed",{error:N.message,completedAt:Date.now()})),N}if(T.emit({type:"replan.decision",mode:B.mode,reason:B.reason,cause:"llm-decision"}),B.mode==="finish")break;if(B.mode==="revise"){if(W>=q){T.emit({type:"revisions.exceeded",cap:q});break}W++,v=Gr(T,B.newPlan),T.emit({type:"plan.revised",plan:v,reason:B.reason});for(let N of v.skills??[])K(N,"plan");C=0,await P();continue}C++,await P();}let D;try{await O(I),D=await Co(r,v,I,i,T,n);}catch(w){throw T.emit({type:"error",error:Ie(w),phase:"synthesize"}),await g("onRunComplete",k(Ke(w)||n?.aborted?"cancelled":"failed",{error:w.message,completedAt:Date.now()})),w}return T.emit({type:"final",text:D}),await g("onRunComplete",k("complete",{text:D,completedAt:Date.now()})),{text:D,plan:v,trace:I,iterations:U,usage:d,...b?{compactedHistory:b}:{}}},"runAgentLoopInner"),Gr=s((e,t)=>{let o=Fe(e);t.steps.length>o&&e.emit({type:"log",level:"warn",message:`[replan] revised plan has ${t.steps.length} steps; truncated to hard cap ${o}`});let n=bt(e,t.skills),{skills:r,...i}=t;return {...i,steps:t.steps.slice(0,o),...n?{skills:n}:{}}},"reviseInto"),Ie=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var Mo=Symbol.for("@dudko.dev/agent:wrapped-tool"),He=class extends Error{static{s(this,"ToolBudgetError");}constructor(t){super(`tool-call budget exhausted (maxToolCalls=${t}). Do not call more tools; finish the step with what you have.`),this.name="ToolBudgetError";}toJSON(){return this.message}},Yr=s(e=>{let t=F.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new He(e);return t.toolCalls++,()=>{t.toolCalls--;}},"reserveToolCall"),Vr=s(e=>Object.prototype.toString.call(e)==="[object AsyncGeneratorFunction]","isAsyncGeneratorFunction"),Xr=s((e,t,o,n={})=>{if(t[Mo])return t;let r=ae(t),i=n.builtIn===true,l=t.execute,c=s(async(d,f)=>{let u=i?()=>{}:Yr(o.maxToolCalls);try{await o.approval.gate(e,d,{readOnly:r,builtIn:i,signal:f?.abortSignal});}catch(h){throw u(),h}},"before"),a;l&&(a=Vr(l)?async function*(d,f){await c(d,f),yield*l(d,f);}:async(d,f)=>(await c(d,f),l(d,f)));let p=rt({...t,...a?{execute:a}:{}},o.maxToolOutputChars);return Object.defineProperty(p,Mo,{value:true,enumerable:false}),p},"wrapTool"),Ae=s((e,t,o={})=>{let n={};for(let[r,i]of Object.entries(e))n[r]=Xr(r,i,t,o);return n},"wrapToolSet");var We={none:0,error:1,warn:2,info:3,debug:4},It=s(async(e,t)=>{let o=We[e.logLevel]>=We.debug,n=s(m=>{if(t)try{t(m);}catch(y){o&&console.error("[agent] event handler threw:",y);}},"emit"),r=s((m,y)=>{We[e.logLevel]>=We[m]&&n({type:"log",level:m,message:y});},"log"),i=no(e.skills),l=s(async(m,y)=>{if(!e.inputSanitizer)return y;try{return await e.inputSanitizer(m,y)}catch{return "[input redacted: sanitizer failed]"}},"sanitizeForApproval"),c=Et(e.toolApproval,{sanitize:l,fallbackEmit:n}),a=ue(e.compaction),p={approval:c,maxToolCalls:e.maxToolCalls,maxToolOutputChars:a.maxToolOutputChars},d=Ae(so(i),p,{builtIn:true}),f=e.toolSelectionStrategy??"auto",u=f==="search"||f==="auto",h=false,T=s(()=>[],"catalogRef"),x=u?Ae(co(()=>T()),p,{builtIn:true}):void 0,K=s(m=>{for(let y of Object.keys(d))if(m[y])throw new Error(`Tool "${y}" collides with a built-in skill tool of the same name`);if(x&&m[ee]){if(f==="search")throw new Error(`Tool "${ee}" collides with the built-in tool-search tool of the same name`);h||(h=true,r("warn",`[tools] a tool named "${ee}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),L,g=s((m,y)=>{if(!e.tools)return m;let A=[];for(let[S,j]of Object.entries(e.tools)){if(m.tools[S]&&y(S),e.availableTools?.length&&!e.availableTools.includes(S)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(S))continue;m.tools[S]=j;let pe=typeof j=="object"&&j&&"description"in j?j.description:"";A.push({name:S,description:typeof pe=="string"?pe:"",server:"<native>",readOnly:ae(j)});}return {tools:m.tools,catalog:[...m.catalog,...A]}},"mergeNativeTools"),b=s(async()=>{let m=await Gt(e.mcpServers,r,e.clientName,e.outputSanitizer,S=>L?.(S),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),y=ct(m.tools,m.catalog,e.availableTools,e.excludedTools,r),A;try{A=g(y,S=>{throw new Error(`Native tool "${S}" collides with an MCP-registered tool of the same name`)}),K(A.tools);}catch(S){throw m.close().catch(()=>{}),S}return {connection:m,tools:Ae(A.tools,p),catalog:A.catalog}},"connect"),O;try{O=await b();}catch(m){throw n({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let H=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&H>0&&!O.connection.results.some(y=>y.connected)){let y=O.connection.results.filter(S=>!S.connected).map(S=>`${S.name}: ${S.error??"unknown"}`).join("; ");await O.connection.close().catch(()=>{});let A=new Error(`All ${H} configured MCP server(s) failed to connect [${y}]`);throw n({type:"error",error:A,phase:"init"}),A}let $,_,R;try{let m=Le(e,void 0,void 0,"executor"),y=Le(e,e.planner,e.plannerModel,"planner"),A=Le(e,e.synthesizer,e.synthesizerModel,"synthesizer");[$,_,R]=await Promise.all([$e(e.clientName,m),$e(e.clientName,y),$e(e.clientName,A)]);}catch(m){throw await O.connection.close().catch(()=>{}),n({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let I=s(m=>m.map(y=>({name:y.name,description:y.description,server:y.server,readOnly:y.readOnly===true})),"toEntries"),v={config:e,executorModel:$,plannerModel:_,synthesizerModel:R,tools:O.tools,toolCatalog:I(O.catalog),emit:n,...Object.keys(d).length?{builtinTools:d}:{},...i.length?{skills:i}:{},approval:c};T=s(()=>v.toolCatalog,"catalogRef");let C=s(()=>{x&&!h?v.findTools=x:delete v.findTools;},"syncFindTools");C();let U=0,W=false,q=false,k=false,P=new Set,D=s(async m=>{await O.connection.refreshServer(m);let y=ct(O.connection.tools,O.connection.catalog,e.availableTools,e.excludedTools),A=g(y,j=>{throw new Error(`Native tool "${j}" collides with an MCP-registered tool of the same name`)});K(A.tools);let S=Ae(A.tools,p);for(let j of Object.keys(v.tools))delete v.tools[j];Object.assign(v.tools,S),v.toolCatalog=I(A.catalog),C(),r("info",`[mcp] ${m}: tool list refreshed (${A.catalog.length} tools total after filter)`);},"applyRefresh"),w=s(async()=>{if(!(k||W||q)&&!(U>0||P.size===0)){k=true;try{for(;P.size>0&&U===0&&!W&&!q;){let m=P.values().next().value;P.delete(m);try{await D(m);}catch(y){r("warn",`[mcp] ${m}: refresh failed - ${y.message}`);}}}finally{k=false;}}},"drainPendingRefreshes");return L=s(m=>{P.add(m),w();},"onToolsChanged"),{run:s(async m=>{if(W)throw new Error("Agent is closed");if(q)throw new Error("Agent is reconnecting; retry shortly");if(k)throw new Error("Agent is refreshing tools; retry shortly");let y=e.maxConcurrentRuns;if(typeof y=="number"&&y>0&&U>=y)throw new Error(`maxConcurrentRuns reached (${U}/${y}); rate-limit on the caller side or raise the cap`);U++;try{return await Po(v,m)}finally{U--,w();}},"run"),listTools:s(()=>v.toolCatalog.map(m=>({...m})),"listTools"),listSkills:s(()=>i.map(m=>({name:m.name,description:m.description})),"listSkills"),compact:s(async m=>{let y=await be(m.history,v.synthesizerModel,{thresholdTokens:a.thresholdTokens,keepRecentTurns:a.keepRecentTurns,summaryMaxTokens:we(e,a.summaryMaxTokens),force:m.force,signal:m.signal,timeoutMs:e.llmTimeoutMs,onUsage:s(A=>n({type:"usage",phase:"compact",usage:A}),"onUsage")});return y.compacted&&n({type:"context.compacted",scope:"history",beforeTokens:y.beforeTokens,afterTokens:y.afterTokens}),{history:y.history,...y.summary?{summary:y.summary}:{},beforeTokens:y.beforeTokens,afterTokens:y.afterTokens,compacted:y.compacted}},"compact"),setToolApprovalMode:s(m=>c.setMode(m),"setToolApprovalMode"),getToolApprovalMode:s(()=>c.getMode(),"getToolApprovalMode"),reconnect:s(async()=>{if(W)throw new Error("Agent is closed");if(q)throw new Error("Already reconnecting");if(k)throw new Error("Agent is refreshing tools; retry shortly");if(U>0)throw new Error(`Cannot reconnect with ${U} active run(s)`);q=true;try{let m=O.connection;P.clear();let y=await b();for(let A of Object.keys(v.tools))delete v.tools[A];Object.assign(v.tools,y.tools),v.toolCatalog=I(y.catalog),C(),O=y,await m.close().catch(()=>{});}finally{q=false;}},"reconnect"),close:s(async m=>{W=true;let y=m?.waitForRuns??false,A=m?.timeoutMs??3e4,S=Date.now()+A;if(y&&U>0)for(;U>0&&Date.now()<S;)await new Promise(N=>setTimeout(N,50));U>0&&n({type:"log",level:"warn",message:`[agent] close called with ${U} active run(s); they will fail mid-flight`});let j=Math.max(S-Date.now(),0),pe=false,B;await Promise.race([O.connection.close().catch(()=>{}),new Promise(N=>{B=setTimeout(()=>{pe=true,N();},j),B.unref?.();})]),B&&clearTimeout(B),pe&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${j}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>U,"activeRuns")}},"createAgent");var ns=8e3,rs=4,ss=4e3,$o=s(e=>{try{let t=JSON.stringify(e,(o,n)=>n instanceof Error?n.message:typeof n=="bigint"?n.toString():n);return t===void 0?void 0:JSON.parse(t)}catch{return String(e)}},"jsonSafe"),is=s(e=>{try{return structuredClone(e)}catch{return $o(e)}},"toCloneable"),At=s((e,t=0)=>{if(typeof e=="string")return ce(e,ss);if(e instanceof Error||!e||typeof e!="object"||t>8)return e;if(Array.isArray(e))return e.map(n=>At(n,t+1));let o={};for(let[n,r]of Object.entries(e))o[n]=At(r,t+1);return o},"clipStrings"),as=s(e=>At(e),"slimEvent"),ls=s((e,t="config")=>{if(e.tools&&Object.keys(e.tools).length)throw new Error(`${t}.tools cannot cross into a worker thread; use the \`tools\` option of createSubagentTool to proxy host tools (or isolation: 'in-process')`);let o=new Set,n=s((r,i)=>{if(typeof r=="function")throw new Error(`${i} is a function and cannot cross into a worker thread; use the \`tools\` option to proxy host tools, or isolation: 'in-process'`);if(!(!r||typeof r!="object"||o.has(r))){o.add(r);for(let[l,c]of Object.entries(r))n(c,`${i}.${l}`);}},"walk");n(e,t);},"assertWorkerSafeConfig"),cs=s(()=>{let e=M;return new URL(e.endsWith(".ts")?"./subagent-worker.ts":"./subagent-worker.js",e)},"subagentWorkerUrl"),ps=s((e=process.execArgv)=>{if(!e.some(n=>["-e","--eval","-p","--print","--input-type"].includes(n)||/^--(input-type|eval|print)=/.test(n)))return;let o=[];for(let n=0;n<e.length;n++){let r=e[n];if(["-e","--eval","-p","--print","--input-type"].includes(r)){n++;continue}/^--(input-type|eval|print)=/.test(r)||o.push(r);}return o},"workerExecArgv"),us=s(e=>{let t=0,o=[];return {acquire:s(n=>new Promise((r,i)=>{if(n?.aborted){i(n.reason??new DOMException("Aborted","AbortError"));return}let l=s(()=>{n?.removeEventListener("abort",c),t++,r();},"grant");function c(){let a=o.indexOf(l);a>=0&&o.splice(a,1),i(n?.reason??new DOMException("Aborted","AbortError"));}if(s(c,"onAbort"),t<e){l();return}n?.addEventListener("abort",c,{once:true}),o.push(l);}),"acquire"),release:s(()=>{t--,o.shift()?.();},"release")}},"createSemaphore"),ds=s(async(e,t,o,n,r)=>{if(!e?.execute)return {ok:false,output:`Unknown proxied tool "${t}"`};try{let i={toolCallId:n,messages:[],abortSignal:r,context:{}},l=e.execute(o,i);if(l&&typeof l[Symbol.asyncIterator]=="function"){let c;for await(let a of l)c=a;l=c;}return {ok:!0,output:$o(await l)}}catch(i){return {ok:false,output:Ve(i)}}},"runHostTool"),ms=s(e=>Object.entries(e).map(([t,o])=>({name:t,description:typeof o.description=="string"?o.description:"",inputSchema:ai.asSchema(o.inputSchema).jsonSchema,...ae(o)?{readOnly:true}:{}})),"describeTools"),gs=s(async(e,t,o,n)=>{let r={...e.config.tools??{},...e.tools??{}},i=await It({...e.config,...Object.keys(r).length?{tools:r}:{}},n);try{let l=await i.run({input:t,signal:o});return {text:l.text,usage:l.usage}}finally{await i.close({timeoutMs:5e3}).catch(()=>{});}},"runInProcess"),fs=s((e,t,o,n)=>new Promise((r,i)=>{let l=e.tools??{},c=false,a;try{let u=ps();a=new worker_threads.Worker(cs(),{workerData:{subagent:e.name},...u?{execArgv:u}:{}});}catch(u){i(u);return}let p=s(u=>{c||(c=true,o.removeEventListener("abort",d),u(),a.terminate().catch(()=>{}));},"finish");function d(){a.postMessage({type:"abort"}),setTimeout(()=>p(()=>i(o.reason??new DOMException("Aborted","AbortError"))),1e3).unref?.();}s(d,"onAbort");let f=async_hooks.AsyncResource.bind(u=>{switch(u.type){case "event":n(u.event);break;case "tool-call":ds(l[u.name],u.name,u.input,u.callId,o).then(h=>{c||a.postMessage({type:"tool-result",callId:u.callId,ok:h.ok,output:h.output});});break;case "done":p(()=>r({text:u.text,usage:u.usage}));break;case "error":p(()=>i(o.aborted?o.reason??new DOMException("Aborted","AbortError"):new Error(u.error)));break}});if(a.on("message",f),a.on("error",u=>p(()=>i(u))),a.on("exit",u=>p(()=>i(new Error(`subagent worker exited with code ${u} before finishing`)))),o.aborted){d();return}o.addEventListener("abort",d,{once:true}),a.postMessage({type:"run",task:t,config:is(e.config),proxied:ms(l)});}),"runInWorker"),hs=s(e=>{let t=e.isolation??"worker";if(!e.name||typeof e.name!="string")throw new Error("createSubagentTool: name is required");t==="worker"&&ls(e.config,`subagent "${e.name}": config`);let o=e.outputMaxChars??ns,n=us(Math.max(1,e.maxConcurrent??rs)),r=ai.tool({description:e.description,inputSchema:zod.z.object({task:zod.z.string().describe("A complete, self-contained task for the subagent, with all context it needs")}),execute:s(async({task:i},{abortSignal:l})=>{let a=F.getStore()?.emit??(()=>{}),p=crypto.randomUUID(),d=e.name;await n.acquire(l);let f=new AbortController,u=s(()=>f.abort(l?.reason),"onParentAbort");l?.addEventListener("abort",u,{once:true}),l?.aborted&&u();let h=false,T=typeof e.timeoutMs=="number"&&e.timeoutMs>0?setTimeout(()=>{h=true,f.abort(new Error(`subagent "${d}" timed out after ${e.timeoutMs}ms`));},e.timeoutMs):void 0,x=le(),K=s(L=>{if(L.type==="usage"){let g=z(L.usage);a({type:"usage",phase:"subagent",usage:g});}a({type:"subagent.event",id:p,name:d,event:as(L)});},"onChildEvent");try{a({type:"subagent.start",id:p,name:d,task:i});let L=t==="worker"?await fs(e,i,f.signal,K):await gs(e,i,f.signal,K);x=z(L.usage);let g=ce(L.text,o);return a({type:"subagent.complete",id:p,name:d,text:g,usage:x}),g}catch(L){let g=h?`subagent "${d}" timed out after ${e.timeoutMs}ms`:Ve(L);throw a({type:"subagent.error",id:p,name:d,error:g}),h?new Error(g):L}finally{T&&clearTimeout(T),l?.removeEventListener("abort",u),n.release();}},"execute")});return V(r,e.readOnly===true)},"createSubagentTool");exports.FileOAuthStore=Ee;exports.MemoryOAuthStore=st;exports.NodeOAuthProvider=Pe;exports.SUMMARY_PREFIX=ot;exports.ToolBudgetError=He;exports.ToolDeniedError=fe;exports.addUsage=Te;exports.beginMcpOAuth=dn;exports.buildInstructions=Je;exports.checkLimits=Ce;exports.compactHistory=be;exports.createAgent=It;exports.createNodeOAuthProvider=un;exports.createSubagentTool=hs;exports.createToolResultClearer=pt;exports.decideToolPermission=Rt;exports.defineSkill=ut;exports.estimateTokens=se;exports.finishMcpOAuth=mn;exports.getCurrentRunId=Do;exports.getCurrentRunSandbox=qe;exports.isReadOnlyTool=ae;exports.loadSkillsFromDir=or;exports.markReadOnly=V;exports.matchToolRule=Ot;exports.mergeProviderOptions=et;exports.normalizeUsage=z;exports.parseSkillMarkdown=to;exports.redactHeaders=Bo;exports.resolveLimits=oe;exports.resolvePromptCaching=he;exports.resolveThinking=Ze;exports.searchTools=ao;exports.truncateToolModelOutput=Kt;exports.withRollingBreakpoint=Ge;exports.withToolOutputLimit=rt;
|