@dudko.dev/agent 0.0.30 → 0.0.32

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.
@@ -0,0 +1,120 @@
1
+ import {dynamicTool,jsonSchema,tool,generateText,generateObject,streamObject,stepCountIs,streamText}from'ai';import {randomUUID}from'crypto';import {isMainThread,parentPort}from'worker_threads';import {AsyncLocalStorage}from'async_hooks';import {UnauthorizedError,auth}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {rm,mkdir,writeFile}from'fs/promises';import po from'path';import {URL as URL$1}from'url';import Uo,{tmpdir}from'os';import {SpanStatusCode,trace}from'@opentelemetry/api';import {z}from'zod';var To=Object.defineProperty;var r=(e,t)=>To(e,"name",{value:t,configurable:true});var F=new AsyncLocalStorage;var pt=r(()=>F.getStore()?.sandboxDir,"getCurrentRunSandbox");var je=new Set(["autopilot","ask-writes","ask-all","read-only"]),dt=r(e=>typeof e=="string"&&je.has(e),"isToolApprovalMode"),be=class extends Error{static{r(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}},Y=r((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),pe=r(e=>!!e&&typeof e=="object"&&e.readOnly===true,"isReadOnlyTool"),mt=new Map,bo=r(e=>{let t=mt.get(e);if(!t){let o=e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t=new RegExp(`^${o}$`),mt.set(e,t);}return t},"globToRegExp"),vo=r((e,t)=>{if(!e)return;if(Object.hasOwn(e,t)&&!t.includes("*"))return {pattern:t,permission:e[t]};let o;for(let[n,s]of Object.entries(e))n.includes("*")&&bo(n).test(t)&&(!o||n.length>o.pattern.length)&&(o={pattern:n,permission:s});return o},"matchToolRule"),So=r(e=>{if(e.builtIn)return {permission:"allow",source:"builtin"};if(e.remembered?.has(e.name))return {permission:"allow",source:"remembered"};let t=vo(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"),Io=r(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"),ve=class extends Error{static{r(this,"ApprovalTimeout");}},Ao=r((e,t,o)=>new Promise((n,s)=>{let i,a=r(()=>{i&&clearTimeout(i),o?.removeEventListener("abort",c);},"done");function c(){a(),s(o?.reason??new DOMException("Aborted","AbortError"));}if(r(c,"onAbort"),o?.aborted){c();return}o?.addEventListener("abort",c,{once:true}),typeof t=="number"&&t>0&&(i=setTimeout(()=>{a(),s(new ve);},t)),e.then(l=>{a(),n(l);},l=>{a(),s(l);});}),"awaitDecision"),gt=r((e,t={})=>{let o=e?.mode??"autopilot";if(!dt(o))throw new Error(`toolApproval.mode must be ${[...je].join(" | ")}, got: ${JSON.stringify(o)}`);let n=new Set;return {getMode:r(()=>o,"getMode"),setMode:r(i=>{if(!dt(i))throw new Error(`tool approval mode must be ${[...je].join(" | ")}, got: ${JSON.stringify(i)}`);o=i;},"setMode"),remembered:n,gate:r(async(i,a,c)=>{let l=So({name:i,readOnly:c.readOnly,mode:o,rules:e?.rules,remembered:n,builtIn:c.builtIn});if(l.permission==="allow")return;let u=F.getStore(),p=u?.emit??t.fallbackEmit??(()=>{}),f=randomUUID(),m=r((b,C)=>{throw p({type:"tool.approval-resolved",id:f,name:i,approved:false,reason:b,automatic:C}),new be(b)},"deny");l.permission==="deny"&&m(l.source==="rule"?`denied by rule "${l.rule}"`:`"${o}" mode allows read-only tools only`,true);let h=e?.onRequest;if(!h){m("no approval handler configured",true);return}let y=t.sanitize?await t.sanitize(i,a):a,x=u?.currentStep;p({type:"tool.approval-requested",id:f,name:i,input:y,readOnly:c.readOnly,...x?{step:x}:{}});let D={id:f,toolName:i,input:y,readOnly:c.readOnly,...x?{step:x}:{},...u?.runId?{runId:u.runId}:{}},_;try{_=await Ao(Promise.resolve().then(()=>h(D)),e?.timeoutMs,c.signal);}catch(b){if(b instanceof ve&&m(`no decision within ${e?.timeoutMs}ms`,true),c.signal?.aborted)throw p({type:"tool.approval-resolved",id:f,name:i,approved:false,reason:"aborted",automatic:true}),b;m(`approval handler failed: ${b?.message??String(b)}`,true);return}let g=Io(_);if(g.approved&&g.remember&&n.add(i),p({type:"tool.approval-resolved",id:f,name:i,approved:g.approved,...g.reason?{reason:g.reason}:{},automatic:false}),!g.approved)throw new be(g.reason)},"gate")}},"createApprovalController");var Se=r(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"),ft=r((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),ht=r((e,t,o)=>e.enabled?{openai:{promptCacheKey:e.key??`${t}:${o}`}}:void 0,"cacheProviderOptions"),xo=r(e=>{let t=e.providerOptions;if(!t?.anthropic||!("cacheControl"in t.anthropic))return e;let{cacheControl:o,...n}=t.anthropic,{anthropic:s,...i}=t,a=Object.keys(n).length?{...i,anthropic:n}:i,{providerOptions:c,...l}=e;return Object.keys(a).length?{...l,providerOptions:a}:l},"withoutBreakpoint"),yt=r((e,t)=>{if(!t.enabled||e.length===0)return e;let o=e.map((i,a)=>a<e.length-1?xo(i):i),n=o[o.length-1],s=n.providerOptions??{};return o[o.length-1]={...n,providerOptions:{...s,anthropic:{...s.anthropic,cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}},o},"withRollingBreakpoint");var Tt=r((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"?Tt(o.cause,t):false},"isRetriable"),ee=r(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let s=0;s<=t.maxRetries;s++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(n=i,s===t.maxRetries||!Tt(i))throw i;t.onRetry?.(s+1,i);let a=o*2**s+Math.random()*250;await Oo(a,t.signal);}}throw n},"withRetry"),Oo=r((e,t)=>new Promise((o,n)=>{if(t?.aborted){n(new DOMException("Aborted","AbortError"));return}let s=setTimeout(()=>{t?.removeEventListener("abort",i),o();},e),i=r(()=>{clearTimeout(s),n(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),Fe=r(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),J=r((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Fe([e,AbortSignal.timeout(t)]),"withTimeout");var ie=r(()=>({inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0,cacheWriteTokens:0}),"emptyUsage"),de=r(e=>typeof e=="number"&&Number.isFinite(e)?e:0,"n"),K=r(e=>{if(!e)return ie();let t=de(e.inputTokens),o=de(e.outputTokens);return {inputTokens:t,outputTokens:o,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:t+o,reasoningTokens:de(e.outputTokenDetails?.reasoningTokens??e.reasoningTokens),cachedInputTokens:de(e.inputTokenDetails?.cacheReadTokens??e.cachedInputTokens),cacheWriteTokens:de(e.inputTokenDetails?.cacheWriteTokens)}},"normalizeUsage"),Ie=r((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"),kt=r((e,t)=>{Object.assign(e,Ie(e,t));},"accumulateUsage"),me=r((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText"),Ke=r(e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e),"errorMessage");var ne=r(e=>{let t=e.limits?.maxTotalTokens??e.maxTotalTokens;return {...e.limits,...t!==void 0?{maxTotalTokens:t}:{}}},"resolveLimits"),ge=r(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isCap"),wt=r(e=>!!(e&&(ge(e.maxInputTokens)||ge(e.maxOutputTokens)||ge(e.maxReasoningTokens)||ge(e.maxTotalTokens))),"hasTokenLimits"),We=r((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,s,i]of o)if(ge(i)&&s>=i)return {kind:n,tokens:s,cap:i}},"checkLimits"),Co=r(e=>e.reduce((t,o)=>Ie(t,K(o.usage)),ie()),"sumStepUsage"),bt=r((e,t,o)=>({steps:n})=>{let s=We(Ie(e(),Co(n)),t);return s?(o?.(s),true):false},"limitsStopCondition");var vt=r(e=>{if(!(e===void 0||e===false))return e===true?{level:"medium"}:typeof e=="string"?{level:e}:{...e,level:e.level??"medium"}},"normalizeThinking"),St=r(e=>{let t=vt(e);if(!t)return {};let o=t.level??"medium";if(o==="none")return {reasoning:"none"};let n=t.includeThoughts!==false,s=t.budgetTokens;if(typeof s=="number"&&Number.isFinite(s)&&s>0){let i=Math.floor(s);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=r((e,t)=>{let o=e.stageThinking?.[t];return o!==void 0?o:e.thinking},"stageThinkingSetting"),Ae=r((e,t)=>vt(qe(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),He=r(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),It=r((e,t)=>{let o={...e};for(let[n,s]of Object.entries(t))o[n]=He(o[n])&&He(s)?It(o[n],s):s;return o},"deepMerge"),At=r((...e)=>{let t;for(let o of e)if(o)for(let[n,s]of Object.entries(o))He(s)&&(t??={},t[n]=It(t[n]??{},s));return t},"mergeProviderOptions");var xt=r(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),te=r((e,t,o)=>{let n=Se(e.promptCaching),s=St(qe(e,t)),i=At(s.providerOptions,ht(n,e.clientName,t)),a=xt(ne(e).perCall?.[t]);return {instructions:ft(o,n),...s.reasoning?{reasoning:s.reasoning}:{},...i?{providerOptions:i}:{},...a?{maxOutputTokens:a}:{}}},"stageCallOptions"),fe=r((e,t)=>{let o=xt(ne(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var Ct=128e3,Ro=2e4,oe=r((e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t,"nonNeg"),ae=r(e=>{let t=oe(e?.contextWindowTokens,0)||Ct;return {auto:e?.auto!==false,contextWindowTokens:t,thresholdTokens:oe(e?.thresholdTokens,0)||Math.floor(t/2),keepRecentTurns:oe(e?.keepRecentTurns,4),keepRecentSteps:oe(e?.keepRecentSteps,3),summaryMaxTokens:oe(e?.summaryMaxTokens,0)||1024,maxToolOutputChars:oe(e?.maxToolOutputChars,Ro),clearToolResultsAfterTokens:oe(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:oe(e?.keepToolResults,3)}},"resolveCompaction"),re=r(e=>Math.ceil(e.length/4),"estimateTokens"),Rt="[Summary of earlier conversation]",Je=r(e=>e.role==="assistant"&&e.content.startsWith(Rt),"isSummaryTurn"),Be=r(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
2
+ `),"renderTurns"),Eo=`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.`,Po=`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.`,xe=r(async(e,t,o={})=>{let n=re(Be(e)),s={history:e,beforeTokens:n,afterTokens:n,compacted:false},i=o.thresholdTokens??Ct/2;if(!o.force&&n<=i)return s;let a=Math.max(0,o.keepRecentTurns??4),c=e.length-a;if(c<=0)return s;let l=e.slice(0,c);if(l.length===1&&Je(l[0]))return s;try{let u=await generateText({model:t,instructions:Eo,prompt:`Conversation to summarize:
7
+ ${Be(l)}`,maxOutputTokens:o.summaryMaxTokens??1024,abortSignal:J(o.signal,o.timeoutMs??0),maxRetries:0}),p=K(u.usage);o.onUsage?.(p);let f=u.text.trim();if(!f)return {...s,usage:p};let m=[{role:"assistant",content:`${Rt}
8
+ ${f}`},...e.slice(c)];return {history:m,summary:f,beforeTokens:n,afterTokens:re(Be(m)),compacted:!0,usage:p}}catch{return s}},"compactHistory"),Et=r(async(e,t,o,n)=>{try{let s=await generateText({model:o,instructions:Po,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:J(n.signal,n.timeoutMs??0),maxRetries:0}),i=s.text.trim();return i?{summary:i,usage:K(s.usage)}:void 0}catch{return}},"summarizeTrace"),Mo=r((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:me(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:me(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:me(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Lo=r(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"),Pt=r((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:r(async s=>Mo(o?await o(s):Lo(s.output),t),"toModelOutput")}},"withToolOutputLimit");var Oe={version:"0.0.32"};po.join(Uo.homedir(),".agent","mcp-oauth.json");var No=new Set(["localhost","127.0.0.1","[::1]","::1"]),Mt=r((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:"||No.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var jo="@dudko.dev/agent",Fo=Oe.version,Ge,Ko=r(()=>(Ge||(Ge=trace.getTracer(jo,Fo)),Ge),"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"},B=r(async(e,t,o)=>Ko().startActiveSpan(e,async n=>{for(let[s,i]of Object.entries(t))i!==void 0&&n.setAttribute(s,i);try{let s=await o(n);return n.end(),s}catch(s){let i=s instanceof Error?s:new Error(String(s));throw n.recordException(i),n.setStatus({code:SpanStatusCode.ERROR,message:i.message}),n.end(),s}}),"withSpan");var nn=r(e=>"command"in e&&!!e.command,"isStdioConfig"),rn=r(e=>"url"in e&&!!e.url,"isHttpConfig"),sn=Oe.version,Ye=64,he=r(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),an=r((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,s=e.slice(0,Ye-n.length)+n;if(!t[s])return s}return ""},"uniqueKey"),Ce=class extends Error{static{r(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},ln=3e4,Ut=100,cn=r(async(e,t)=>{let o=[],n,s=new Set;for(let i=0;i<Ut;i++){let a=await e.listTools(n?{cursor:n}:void 0);o.push(...a.tools);let c=typeof a.nextCursor=="string"&&a.nextCursor?a.nextCursor:void 0;if(!c||s.has(c))return o;s.add(c),n=c;}return t?.(),o},"listAllTools"),le=class extends Error{static{r(this,"RefreshOnlyAbort");}},un=r(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:r(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:r(()=>e.tokens(),"tokens"),saveTokens:r(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:r(()=>e.codeVerifier(),"codeVerifier"),state:r(()=>{throw new le},"state"),saveCodeVerifier:r(()=>{throw new le},"saveCodeVerifier"),redirectToAuthorization:r(()=>{throw new le},"redirectToAuthorization")}),"refreshOnly"),pn=r(async(e,t,o,n,s)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(un(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof le?`[mcp] ${s}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${s}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),_t=r(async(e,t,o,n,s,i,a={})=>{let c=new Map,l={},u=[],p=[],f=new Map,m=r((g,b,C)=>{let j=`${he(g)}__`;for(let I of f.get(g)??[])delete l[I];for(let I=u.length-1;I>=0;I--)u[I].server===g&&u.splice(I,1);let M=[],$=0,R=0;for(let I of C){let v=j+he(I.name);if(v.length>Ye){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${Ye}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=an(v,l);if(!O){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}O!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${O}"`);let L=I.description??"",W=I.annotations?.readOnlyHint===true;l[O]=dynamicTool({description:L,inputSchema:jsonSchema(I.inputSchema),execute:r(async(H,k)=>B("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let N=H??{};if(i)try{let S=await i(O,N);N=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),N={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:N},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let d=w.isError===true,T=w.content;if(n)try{T=await n(O,T);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),d)throw new Ce("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await fn(T,{toolName:O,sandboxDir:d?void 0:pt()});if(d){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Ce(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&Y(l[O]),u.push({name:O,description:L,server:g,readOnly:W}),M.push(O),$++;}f.set(g,M),R>0?t("info",`[mcp] ${g}: ${$} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${$} tools mounted`);},"mountServerTools"),h=r((g,b)=>cn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Ut} pages; the rest is ignored`)),"listServerTools"),y=r(async(g,b)=>{m(g,b,await h(g,b));},"registerServerTools"),x=r(async(g,b)=>{let C=b.connectTimeoutMs??a.connectTimeoutMs,j=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:ln,M,$=false,R=D(g,b,I=>{M=I;},()=>$);try{return await(j>0?dn(R,j,()=>{$=!0;}):R)}catch(I){M&&await M.close().catch(()=>{});let v=$?`connect timed out after ${j}ms`:I.message,O=!$&&I instanceof UnauthorizedError;return t("error",O?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:O}}},"openConnection"),D=r(async(g,b,C,j)=>{let M,$=r(async()=>{if(j())throw await M?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(nn(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;R=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if(rn(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`),Mt(b.url,`MCP server "${g}"`),await pn(b.authProvider,b.url,b.fetch,t,g)),R=new StreamableHTTPClientTransport(new URL$1(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 $(),M=new Client({name:o,version:sn}),C(M),await M.connect(R),await $(),s&&M.setNotificationHandler(ToolListChangedNotificationSchema,()=>{s(g);});let I=await h(g,M);return await $(),{name:g,client:M,listed:I}}catch(R){throw M&&await M.close().catch(()=>{}),R}},"connectOnce"),_=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of _){if(!g.client||!g.listed){p.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),m(g.name,g.client,g.listed),p.push({name:g.name,connected:true});}return {tools:l,catalog:u,results:p,close:r(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:r(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await y(g,b);},"refreshServer")}},"connectMcpServers"),dn=r((e,t,o)=>new Promise((n,s)=>{let i=setTimeout(()=>{o(),s(new Error(`connect timed out after ${t}ms`));},t);e.then(a=>{clearTimeout(i),n(a);},a=>{clearTimeout(i),s(a);});}),"withConnectTimeout"),Lt={image:".bin",audio:".bin",resource:".bin"},mn=r((e,t)=>{if(!e)return Lt[t];let o=e.indexOf("/"),s=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !s||/[^a-z0-9.+-]/.test(s)?Lt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[s]??`.${s.replace(/\+/g,"-")}`},"extFromMime"),gn=/[^a-zA-Z0-9_-]/g,$t=r(async(e,t,o,n,s,i)=>{await i();let a=mn(t,o),c=n.replace(gn,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),u=po.join(s,`${o}-${c}-${l}${a}`),p=Buffer.from(e,"base64");return await writeFile(u,p),{type:"file",kind:o,path:u,mimeType:t,bytes:p.byteLength}},"spillBase64"),fn=r(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(u=>u?.type==="text"&&typeof u.text=="string"))return o.map(u=>u.text).join(`
13
+ `);let s=t?.sandboxDir,i=t?.toolName??"tool",a,c=r(()=>s?(a||(a=mkdir(s,{recursive:true}).then(()=>{})),a):Promise.resolve(),"ensureDir"),l=[];for(let u of o){if(u?.type==="text"&&typeof u.text=="string"){l.push(u.text);continue}if(s&&(u?.type==="image"||u?.type==="audio")&&typeof u.data=="string"){let p=await $t(u.data,typeof u.mimeType=="string"?u.mimeType:void 0,u.type,i,s,c);l.push(p);continue}if(s&&u?.type==="resource"&&u.resource&&typeof u.resource=="object"){let p=u.resource;if(typeof p.blob=="string"){let f=await $t(p.blob,typeof p.mimeType=="string"?p.mimeType:void 0,"resource",i,s,c);typeof p.uri=="string"&&(f.uri=p.uri),l.push(f);continue}if(typeof p.text=="string"){l.push(p.text);continue}}l.push(u);}return l},"flattenContent"),Ve=r((e,t,o,n,s)=>{let i=o?.length?new Set(o.map(he)):null,a=n?.length?new Set(n.map(he)):null,c=new Set,l={},u=[];for(let p of t){if((i?.has(p.name)||a?.has(p.name))&&c.add(p.name),i&&!i.has(p.name)||!i&&a?.has(p.name))continue;let f=e[p.name];f&&(l[p.name]=f,u.push(p));}if(s)for(let[p,f]of [["availableTools",o],["excludedTools",n]])for(let m of f??[])c.has(he(m))||s("warn",`[mcp] ${p}: "${m}" matches no discovered tool`);return {tools:l,catalog:u}},"filterTools");var Re=r((e,t,o,n)=>{let s=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,a=t?.baseURL??e.baseURL,c=t?.model??o??e.model,l=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(hn.has(s)&&!a)throw new Error(`${n}: provider "${s}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:s,baseURL:a,apiKey:i,model:c,providerOptions:l}},"resolveStage"),hn=new Set(["openai-compatible","azure"]),V={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"},X=r(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"),Ee=r(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await X(V.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await X(V.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 X(V["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await X(V.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await X(V.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 X(V.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await X(V["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await X(V["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await X(V.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 s=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...a}=o;if(!s&&!("binding"in a))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await X(V.cloudflare),l="binding"in a?a:{accountId:s,apiKey:t.apiKey,...a};return c(l)(t.model)}}},"buildModelFromStage");var yn=r(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,s)=>n.type==="tool-result"?[`${o}:${s}`]:[]):[]),"positionsOf"),Tn=r(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Nt=r(e=>{try{return re(JSON.stringify(e))}catch{return 0}},"estimate"),Dt=r((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,s=r(i=>n.size===0?i:i.map((a,c)=>a.role==="tool"&&Array.isArray(a.content)?{...a,content:a.content.map((l,u)=>l.type==="tool-result"&&n.has(`${c}:${u}`)?{...l,output:{type:"text",value:Tn(l.toolName)}}:l)}:a),"apply");return i=>{let a=s(i),c=Nt(a);if(c<=e.triggerTokens)return a;let l=yn(i),u=0;for(let f of l.slice(0,Math.max(0,l.length-o)))n.has(f)||(n.add(f),u+=1);if(u===0)return a;let p=s(i);return t?.({cleared:u,beforeTokens:c,afterTokens:Nt(p)}),p}},"createToolResultClearer");var jt=/^[a-z0-9-]{1,64}$/,wn="load_skill",bn="read_skill_file",vn=24e3,Ft=r(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=po.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"),Sn=r(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:s}=e;if(typeof t!="string"||!jt.test(t))throw new Error(`skill name must match ${jt} (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(s!==void 0&&!Array.isArray(s))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,a=(s??[]).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 l;try{l=Ft(c.path);}catch(u){throw new Error(`skill "${t}": ${u.message}`)}if(i.has(l))throw new Error(`skill "${t}": duplicate file "${l}"`);return i.add(l),{path:l,content:c.content}});return {name:t,description:o.trim(),content:n,...a.length?{files:a}:{}}},"defineSkill");var Kt=r(e=>{let t=[],o=new Set;for(let n of e??[]){let s=Sn(n);if(o.has(s.name))throw new Error(`duplicate skill name "${s.name}"`);o.add(s.name),t.push(s);}return t},"validateSkills"),In=r((e,t)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}\u2026`:o},"oneLine"),Xe=r(e=>e.map(t=>`- ${t.name}: ${In(t.description,300)}`).join(`
14
+ `),"renderSkillsIndex"),Wt=r((e,t,o=vn)=>{let n=new Map(e.map(a=>[a.name,a])),s=[],i=0;for(let a of t){let c=n.get(a);if(!c)continue;let l=`### Skill: ${c.name}
15
+ ${c.content.trim()}`,u=o-i;if(u<=0){s.push(`### Skill: ${c.name}
16
+ \u2026 [skill instructions clipped: budget exhausted]`);continue}if(l.length>u){s.push(`${l.slice(0,u)}
17
+ \u2026 [skill instructions clipped]`),i=o;continue}s.push(l),i+=l.length;}return s.join(`
18
+
19
+ `)},"renderActiveSkills"),Ze=r((e,t,o,n,s)=>e.some(i=>i.name===t)?(n&&!n.activeSkills.includes(t)&&(n.activeSkills.push(t),s?.({type:"skill.activated",name:t,by:o})),true):false,"activateSkill"),Ht=r(e=>{if(!e.length)return {};let t=e.map(n=>n.name),o=r(n=>{let s=e.find(i=>i.name===n);if(!s)throw new Error(`Unknown skill "${n}". Available skills: ${t.join(", ")}`);return s},"find");return {[wn]:Y(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:z.object({name:z.string().describe(`Skill name, one of: ${t.join(", ")}`)}),execute:r(async({name:n})=>{let s=o(n),i=F.getStore();return Ze(e,s.name,"tool",i?.state,i?.emit),{name:s.name,content:s.content,files:(s.files??[]).map(a=>a.path)}},"execute")})),[bn]:Y(tool({description:"Read a file bundled with a skill (paths are listed by load_skill). Returns the file content.",inputSchema:z.object({name:z.string().describe("Skill name"),path:z.string().describe("Skill-relative file path, as listed by load_skill")}),execute:r(async({name:n,path:s})=>{let i=o(n),a;try{a=Ft(s);}catch(l){throw new Error(l.message)}let c=(i.files??[]).find(l=>l.path===a);if(!c){let l=(i.files??[]).map(u=>u.path);throw new Error(`Skill "${i.name}" has no file "${s}". Files: ${l.length?l.join(", "):"(none)"}`)}return c.content},"execute")}))}},"createSkillTools");var Q="find_tools",xn=40,On=8,Cn=20,Le=r((e,t)=>{let o=e.toolSelectionStrategy??"auto";if(o==="auto"){let n=e.toolSearchThreshold??xn;return t>n?"search":"all"}return o},"resolveToolStrategy"),Me=r(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"),Qe=r((e,t)=>e.some(o=>o===t||t.length>=3&&o.startsWith(t)),"hit"),Rn=r((e,t,o={})=>{let n=[...new Set(Me(t))];if(n.length===0)return [];let s=Math.floor(o.limit??On),i=Math.min(Cn,Math.max(1,Number.isFinite(s)?s:8)),a=o.server?.trim().toLowerCase(),c=[];return e.forEach((l,u)=>{if(a&&(l.server??"").toLowerCase()!==a)return;let p=Me(l.name),f=Me(l.server??""),m=Me(l.description??""),h=0;for(let y of n)h+=(Qe(p,y)?3:0)+(Qe(f,y)?2:0)+(Qe(m,y)?1:0);h>0&&c.push({entry:l,score:h,index:u});}),c.sort((l,u)=>u.score-l.score||l.index-u.index),c.slice(0,i).map(l=>l.entry)},"searchTools"),En=12e3,Pn=60,Bt=r((e,t=En)=>{if(e.length===0)return "(no tools available)";let o=new Map;for(let c of e){let l=c.server??"<native>",u=o.get(l)??[];u.push(c),o.set(l,u);}let n=[],s=0,i=0;e:for(let[c,l]of o){let u=`[${c}]`;if(s+u.length+1>t)break;n.push(u),s+=u.length+1;for(let p of l){let f=(p.description||"").replace(/\s+/g," ").trim().slice(0,Pn),m=`- ${p.name}: ${f}`;if(s+m.length+1>t)break e;n.push(m),s+=m.length+1,i++;}}let a=e.length-i;return a>0&&n.push(`\u2026 ${a} more tools \u2014 the executor can find them with ${Q}`),n.join(`
20
+ `)},"renderSearchCatalog"),Jt=r(e=>({[Q]:Y(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:z.object({query:z.string().describe('Keywords describing the capability you need, e.g. "list github issues"'),server:z.string().optional().describe("Restrict the search to one MCP server"),limit:z.number().optional().describe("Max results (default 8, max 20)")}),execute:r(async({query:t,server:o,limit:n})=>{let s=Rn(e(),t,{server:o,limit:n}),i=s.map(l=>l.name),a=F.getStore(),c=a?.state;if(c)for(let l of i){let u=c.discovered.indexOf(l);u>=0&&c.discovered.splice(u,1),c.discovered.push(l),c.stepActive?.add(l);}return a?.emit&&a.currentStep&&a.emit({type:"tools.discovered",step:a.currentStep,query:t,names:i}),{tools:s.map(l=>({name:l.name,description:l.description,server:l.server??"<native>",readOnly:l.readOnly===true}))}},"execute")}))}),"createFindToolsTool");var Gt=1500,Yt=6e3,tt=r(e=>{if(!e?.length)return "(no prior conversation)";let t=Je(e[0])?e[0]:void 0,o=t?e.slice(1):e,n=o.slice(-8),s=o.length-n.length,i=[];if(t){let a=t.content.length>Yt?`${t.content.slice(0,Yt)}... [truncated]`:t.content;i.push(`${t.role}: ${a}`);}s>0&&i.push(`(${s} earlier turns omitted)`);for(let a of n){let c=a.content.length>Gt?`${a.content.slice(0,Gt)}... [truncated]`:a.content;i.push(`${a.role}: ${c}`);}return i.join(`
21
+ `)},"renderHistory"),Ln={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},$n=r((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=Ln[t],s=e.slice(0,o),i=e.length-s.length,a=s.map(c=>{let l=(c.description||"").replace(/\s+/g," ").trim().slice(0,n);return `- ${c.name}: ${l}`});return i>0&&a.push(`... and ${i} more tools`),a.join(`
22
+ `)},"renderToolCatalog"),Vt=r((e,t)=>t==="search"?Bt(e):$n(e,t),"renderCatalogFor"),et=1500,Un=r(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>et?`${t.slice(0,et)}... [truncated, ${t.length-et} chars]`:t},"truncateOutput"),_n=r((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${Un(n.output)}`).join(`
23
+ `):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
24
+ `)},"renderTraceEntry"),$e=r((e,t=0)=>e.map((o,n)=>_n(o,t+n)).join(`
25
+ `),"renderTraceSteps"),ce=r((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 $e(e);let n=[`Summary of earlier steps (1-${o}): ${t.summary}`];return o<e.length&&n.push($e(e.slice(o),o)),n.join(`
26
+ `)},"renderTrace"),ot=r(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
27
+ expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
28
+ suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
29
+ `),"renderPlan"),Ue=r((e,t)=>t?`${e}
30
+
31
+ Domain context:
32
+ ${t}`:e,"withDomainContext"),_e=8,Xt=r(e=>`You are the Planner of a multi-step agent system.
33
+
34
+ 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.
35
+
36
+ Rules:
37
+ 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".
38
+ 2. Each step must be self-contained, action-oriented, and verifiable. State what should be done and what the expected outcome is.
39
+ 3. If a step needs a tool, suggest tool name(s) ONLY from the provided available-tools list. NEVER fabricate tool names.
40
+ 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.
41
+ 5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
42
+ 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.
43
+ 7. Output strict JSON matching the requested schema. No prose outside JSON.`,"plannerBase");Xt(_e);var Nn=`
44
+
45
+ ADDITIONAL RULE (tool-narrowed mode):
46
+ 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.`,Dn=`
47
+
48
+ ADDITIONAL RULE (tool-search mode):
49
+ 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 ${Q}. Never invent names.`,zn=`
50
+
51
+ SKILL SELECTION:
52
+ 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.`,jn=r((e,t=_e)=>Xt(t)+(e==="compact"?Nn:e==="search"?Dn:""),"buildPlannerSystem"),Fn=r(e=>e?.length?`
53
+
54
+ SKILLS:
55
+ ${Xe(e)}`:"","skillsIndexSection"),nt=r((e,t)=>{if(!e?.length||!t?.length)return "";let o=Wt(e,t);return o?`
56
+
57
+ ACTIVE SKILLS (follow these instructions where they apply):
58
+
59
+ ${o}`:""},"activeSkillsSection"),Zt=r(e=>Ue(jn(e.mode,e.maxSteps)+(e.skills?.length?zn:""),e.domain)+Fn(e.skills)+`
60
+
61
+ Available tools:
62
+ ${Vt(e.catalog,e.mode)}`,"composePlannerSystem"),Qt=r((e,t)=>[t?.length?`Conversation history:
63
+ ${tt(t)}
64
+ `:"",`User request:
65
+ ${e}`,"","Produce the plan now."].filter(Boolean).join(`
66
+ `),"buildPlannerUserPrompt"),Kn=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
67
+
68
+ Rules:
69
+ 1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
70
+ 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.
71
+ 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.
72
+ 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.
73
+ 5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,Wn=`
74
+
75
+ TOOLS:
76
+ Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${Q} with a few keywords; the matching tools become callable from your next step on.`,Hn=`
77
+
78
+ SKILLS:
79
+ 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.`,eo=r(e=>Ue(Kn,e.domain)+(e.skills?.length?`${Hn}
80
+ ${Xe(e.skills)}`:"")+(e.searchMode?`${Wn}${e.toolCount?` The catalogue has ${e.toolCount} tools.`:""}`:"")+nt(e.skills,e.activeSkills),"composeExecutorSystem"),to=r((e,t,o,n,s,i)=>[s?.length?`Conversation history:
81
+ ${tt(s)}
82
+ `:"",`Original user request:
83
+ ${e}`,"",`Overall plan:
84
+ ${ot(t)}`,"",`Trace so far:
85
+ ${ce(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(`
86
+ `),"buildExecutorUserPrompt"),qn=`You are the Replanner of an autonomous multi-step agent system. After an Executor step you decide what should happen next.
87
+
88
+ You have three options:
89
+ - "continue": the next planned step is still appropriate.
90
+ - "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.
91
+ - "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.
92
+
93
+ Rules:
94
+ 1. Prefer "continue" when the original plan still applies. Revise only when needed.
95
+ 2. Prefer "finish" as soon as the user's request is satisfied - do not run unnecessary extra steps.
96
+ 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.
97
+ 4. Never revise into a step that asks the user for input, clarification or permission - the agent runs autonomously.
98
+ 5. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
99
+ 6. Output strict JSON matching the schema. No prose outside JSON.`,oo=r(e=>Ue(qn,e.domain)+`
100
+
101
+ Available tools (for the revise option):
102
+ ${Vt(e.catalog,e.mode)}`+nt(e.skills,e.activeSkills),"composeReplannerSystem"),no=r((e,t,o,n,s)=>[`Original user request:
103
+ ${e}`,"",`Current plan:
104
+ ${ot(t)}`,"",`Completed steps:
105
+ ${ce(o,s)}`,"",n?`Next planned step: [${n.id}] ${n.description}`:"There is no next step in the current plan.","","Decide now: continue, revise, or finish."].join(`
106
+ `),"buildReplannerUserPrompt"),Bn=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
107
+
108
+ Rules:
109
+ 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.
110
+ 2. Use facts from the trace verbatim when accuracy matters (names, IDs, numbers, quotes). Never invent results the trace does not contain.
111
+ 3. Mention the assumptions the agent made, briefly.
112
+ 4. If the trace shows the request (or part of it) could not be completed, say so plainly and explain what blocked it.
113
+ 5. Do not end with questions or offers unless the request genuinely cannot be completed without input from the user.
114
+ 6. Use the user's language.`,ro=r(e=>Ue(Bn,e.domain)+nt(e.skills,e.activeSkills),"composeSynthesizerSystem"),so=r((e,t,o,n,s)=>[n?.length?`Conversation history:
115
+ ${tt(n)}
116
+ `:"",`User request:
117
+ ${e}`,"",`Plan that was executed:
118
+ ${ot(t)}`,"",`Execution trace:
119
+ ${ce(o,s)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
120
+ `),"buildSynthesizerUserPrompt");var Gn=z.object({id:z.string().min(1).describe('Short stable id, e.g. "s1", "fetch-companies"'),description:z.string().min(1).describe("Concrete action to perform"),expectedOutcome:z.string().min(1).describe("What state/data should exist after this step"),suggestedTools:z.array(z.string()).optional().describe("Tool names from the available list, if any")}),Yn=_e,rt=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(Gn).min(1),skills:z.array(z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),Ne=r(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):Yn},"planStepCap"),ue=r(e=>{if(e.run)return e.run.strategy;let t=Le(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"effectiveToolStrategy"),st=r(e=>e==="plan-narrowed"?"compact":e==="search"?"search":"full","catalogModeFor"),it=r((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)))],s=t.filter(i=>!o.has(i));return s.length&&e.emit({type:"log",level:"warn",message:`[plan] dropped unknown skills: ${s.join(", ")}`}),n.length?n:void 0},"filterPlanSkills"),io=r(async(e,t,o,n)=>B("agent.plan",{[E.PHASE]:"plan"},async s=>{let i=new Set(o.toolCatalog.map(m=>m.name)),a=st(ue(o)),c=Ne(o),{object:l,usage:u}=await ee(()=>Vn(e,t,a,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:r((m,h)=>o.emit({type:"retry",phase:"plan",attempt:m,error:h.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:u}),s.setAttribute(E.USAGE_TOTAL_TOKENS,u.totalTokens);let p=l.steps.slice(0,c);p.length<l.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${l.steps.length} steps; truncated to hard cap ${c}`});let f=it(o,l.skills);return {thought:l.thought,...f?{skills:f}:{},steps:p.map(m=>{if(!m.suggestedTools?.length)return m;let h=m.suggestedTools.filter(x=>i.has(x)),y=m.suggestedTools.length-h.length;return y>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${m.id}" had ${y} unknown suggestedTools, stripped`}),h.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${m.id}" had no valid suggestedTools left; falling back to full toolset`}),{...m,suggestedTools:void 0,requiresTools:true}):{...m,suggestedTools:h}})}}),"createInitialPlan"),Vn=r(async(e,t,o,n,s)=>{let i=te(n.config,"planner",Zt({mode:o,catalog:n.toolCatalog,maxSteps:Ne(n),domain:n.config.systemPrompt,skills:n.skills})),a=streamObject({model:n.plannerModel,schema:rt,...i,prompt:Qt(e,t),abortSignal:J(s,n.config.llmTimeoutMs??0)}),c="",l=false,u=0;for await(let m of a.partialObjectStream){let h=m?.thought;typeof h=="string"&&h!==c&&(h.startsWith(c)?n.emit({type:"plan.thought-delta",delta:h.slice(c.length)}):l||(n.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),l=true),c=h);let y=m?.steps;if(Array.isArray(y)&&y.length>u)for(;u<y.length;){let x=y[u];if(!x||typeof x.description!="string"||!x.description.length)break;let D={id:typeof x.id=="string"&&x.id?x.id:`s${u+1}`,description:x.description,expectedOutcome:typeof x.expectedOutcome=="string"?x.expectedOutcome:"",suggestedTools:Array.isArray(x.suggestedTools)?x.suggestedTools.filter(_=>typeof _=="string"):void 0};n.emit({type:"plan.step-added",step:D,index:u}),u++;}}let[p,f]=await Promise.all([a.object,a.usage]);return {object:p,usage:K(f)}},"streamPlanOnce");var Qn=r((e,t)=>{if(ue(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 s of o){let i=e.tools[s];i&&(n[s]=i);}return n},"buildActiveToolSet"),ao="[BLOCKER]",er=r(e=>e.includes(ao)?{summary:e.split(ao).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),at=4e3,tr=r(e=>e.length>at?`${e.slice(0,at)}... [truncated, ${e.length-at} chars]`:e,"truncateForTrace"),lo=r(async(e,t,o,n,s,i,a)=>B("agent.execute_step",{[E.PHASE]:"execute",[E.STEP_ID]:o.id},async c=>{let l=Date.now(),u=await ee(()=>nr(e,t,o,n,s,i,a),{maxRetries:i.config.llmMaxRetries??2,signal:a,onRetry:r((p,f)=>i.emit({type:"retry",phase:"execute",attempt:p,error:f.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:u.usage}),c.setAttribute(E.USAGE_TOTAL_TOKENS,u.usage.totalTokens),c.setAttribute(E.STEP_BLOCKED,u.blocked),c.setAttribute(E.TOOL_COUNT,u.toolCalls.length),{step:o,summary:u.summary,toolCalls:u.toolCalls,durationMs:Date.now()-l,blocked:u.blocked}}),"executeStep"),or=r((e,t)=>{let o=ue(e),n=e.builtinTools??{};if(o==="search"){let a={...e.tools,...n,...e.findTools??{}},c=new Set([...Object.keys(n),...Object.keys(e.findTools??{})]);for(let l of t.suggestedTools??[])e.tools[l]&&c.add(l);for(let l of (e.run?.discovered??[]).slice(-16))e.tools[l]&&c.add(l);return {tools:a,active:c}}let s=Qn(e,t),i=Object.keys(n).length?{...s,...n}:s;return o==="plan-narrowed"?{tools:i,activeTools:Object.keys(i)}:{tools:i}},"buildExecutorTools"),nr=r(async(e,t,o,n,s,i,a)=>{let c=[],l=new Map,{tools:u,activeTools:p,active:f}=or(i,o),m=i.run;m&&(m.stepActive=f);let h=r(async(k,P)=>{let N=i.config.inputSanitizer;if(!N)return P;try{return await N(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"),y,x=[stepCountIs(i.config.maxStepsPerTask)],D=ne(i.config);m&&wt(D)&&x.push(bt(()=>m.usage,D,()=>{y="tokens";}));let _=i.config.maxToolCalls;m&&typeof _=="number"&&_>0&&x.push(()=>m.toolCalls>=_?(y??="tool-calls",true):false);let g=te(i.config,"executor",eo({domain:i.config.systemPrompt,skills:i.skills,activeSkills:m?.activeSkills,searchMode:!!f,toolCount:i.toolCatalog.length})),b=Ae(i.config,"executor"),C=m?{summary:m.traceSummary,upTo:m.traceSummaryUpTo}:void 0,j=Se(i.config.promptCaching),M=ae(i.config.compaction),$=M.clearToolResultsAfterTokens>0?Dt({triggerTokens:M.clearToolResultsAfterTokens,keep:M.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=j.enabled||!!$,I=streamText({model:i.executorModel,tools:u,...p?{activeTools:p}:{},...f||R?{prepareStep:r(({messages:k})=>{let P=yt($?$(k):k,j);return {...f?{activeTools:[...f].filter(N=>N in u)}:{},...R?{messages:P}:{}}},"prepareStep")}:{},stopWhen:x,...g,prompt:to(e,t,o,n,s,C),abortSignal:J(a,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);l.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 N=l.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:N,output:k.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:k.toolName,output:k.output,ok:true}),l.delete(k.toolCallId);break}case "tool-error":{let N=l.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:N,output:k.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:k.toolName,output:k.error,ok:false}),l.delete(k.toolCallId);break}case "error":{let P=k.error;throw P instanceof Error?P:new Error(String(P))}}let[v,O]=await Promise.all([I.text,I.usage]),{summary:L,blocked:W}=er(v.trim());return {summary:L.length>0?tr(L):y?`Stopped early: the run's ${y==="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:O?K(O):ie()}},"runOnce");var sr=z.discriminatedUnion("mode",[z.object({mode:z.literal("continue"),reason:z.string().min(1).describe("Why the next step is still appropriate")}),z.object({mode:z.literal("finish"),reason:z.string().min(1).describe("Why no more steps are needed")}),z.object({mode:z.literal("revise"),reason:z.string().min(1).describe("Why the plan must change"),newPlan:rt.describe("Plan covering ONLY the remaining work")})]),co=r(async(e,t,o,n,s,i)=>B("agent.replan",{[E.PHASE]:"replan"},async a=>{let c=st(ue(s)),l=s.run?{summary:s.run.traceSummary,upTo:s.run.traceSummaryUpTo}:void 0,{object:u,usage:p}=await ee(async()=>{let f=te(s.config,"replanner",oo({mode:c,catalog:s.toolCatalog,domain:s.config.systemPrompt,skills:s.skills,activeSkills:s.run?.activeSkills})),m=await generateObject({model:s.plannerModel,schema:sr,...f,prompt:no(e,t,o,n,l),abortSignal:J(i,s.config.llmTimeoutMs??0)}),h=K(m.usage);return {object:m.object,usage:h}},{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((f,m)=>s.emit({type:"retry",phase:"replan",attempt:f,error:m.message}),"onRetry")});return s.emit({type:"usage",phase:"replan",usage:p}),a.setAttribute(E.REPLAN_MODE,u.mode),a.setAttribute(E.USAGE_TOTAL_TOKENS,p.totalTokens),u}),"decideNextAction");var uo=r(async(e,t,o,n,s,i)=>B("agent.synthesize",{[E.PHASE]:"synthesize"},async a=>{let{text:c,usage:l}=await ee(()=>ar(e,t,o,n,s,i),{maxRetries:s.config.llmMaxRetries??2,signal:i,onRetry:r((u,p)=>s.emit({type:"retry",phase:"synthesize",attempt:u,error:p.message}),"onRetry")});return s.emit({type:"usage",phase:"synthesize",usage:l}),a.setAttribute(E.USAGE_TOTAL_TOKENS,l.totalTokens),c}),"synthesizeAnswer"),ar=r(async(e,t,o,n,s,i)=>{let a=te(s.config,"synthesizer",ro({domain:s.config.systemPrompt,skills:s.skills,activeSkills:s.run?.activeSkills})),c=s.run?{summary:s.run.traceSummary,upTo:s.run.traceSummaryUpTo}:void 0,l=Ae(s.config,"synthesizer"),u=streamText({model:s.synthesizerModel,...a,prompt:so(e,t,o,n,c),abortSignal:J(i,s.config.llmTimeoutMs??0)});for await(let m of u.fullStream)if(m.type==="text-delta")m.text&&s.emit({type:"final.text-delta",delta:m.text});else if(m.type==="reasoning-delta")m.text&&l&&s.emit({type:"final.reasoning-delta",delta:m.text});else if(m.type==="error"){let h=m.error;throw h instanceof Error?h:new Error(String(h))}let[p,f]=await Promise.all([u.text,u.usage]);return {text:p,usage:K(f)}},"streamOnce");var mo=r(e=>{if(e.blocked)return true;let{toolCalls:t}=e;return t.some((o,n)=>!o.ok&&!t.slice(n+1).some(s=>s.ok&&s.name===o.name))},"shouldCallReplanner"),pr=r(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return mo(t);let n=r(()=>mo(t),"fallback"),{signal:s}=o,i=o.timeoutMs??0;if(s?.aborted)return n();let a=(async()=>{try{return !!await e(t)}catch(l){return o.onError?.(l),n()}})(),c=Number.isFinite(i)&&i>0;return !c&&!s?a:new Promise(l=>{let u=false,p,f=r(h=>{u||(u=true,p!==void 0&&clearTimeout(p),s?.removeEventListener("abort",m),l(h));},"finish");function m(){f(n());}r(m,"onAbort"),c&&(p=setTimeout(()=>f(n()),i)),s?.addEventListener("abort",m,{once:true}),a.then(f,()=>f(n()));})},"replanTriggered"),De=r(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),dr=r((e,t)=>{let o=e.config.sandboxRoot?.trim()||po.join(tmpdir(),"agent-sandbox");return po.join(o,t)},"resolveSandboxDir"),go=/^[a-zA-Z0-9_-]{1,128}$/,lt=r((e,t)=>{if(!go.test(e))throw new Error(`Unsafe runId from ${t}: must match ${go}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),mr=r(async(e,t)=>{if(!t.resumeFromRunId)return;if(lt(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(lt(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"),fo=r(async(e,t)=>{let o=await mr(e,t),n=o?.runId??randomUUID();lt(n,"runId");let s=o?.startedAt??Date.now(),i=dr(e,n);return F.run({runId:n,startedAt:s,sandboxDir:i},async()=>B("agent.run",{[E.RUN_ID]:n,[E.PROVIDER]:e.config.providerType,[E.MODEL]:e.config.model},async a=>{try{let c=await fr(e,t,o);return a.setAttribute(E.ITERATIONS,c.iterations),a.setAttribute(E.USAGE_TOTAL_TOKENS,c.usage.totalTokens),a.setAttribute(E.USAGE_INPUT_TOKENS,c.usage.inputTokens),a.setAttribute(E.USAGE_OUTPUT_TOKENS,c.usage.outputTokens),c}finally{e.config.keepSandbox||await rm(i,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),gr=r(e=>{let t=Le(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"runToolStrategy"),fr=r(async(e,t,o)=>{let{signal:n}=t,s=o?.input??t.input,i=o?.history?[...o.history]:t.history?[...t.history]:void 0,a=t.onEvent??(()=>{}),c=ae(e.config.compaction),l=ne(e.config),u=e.config.maxToolCalls,p=K(o?.usage),f=F.getStore()?.startedAt??Date.now(),m=F.getStore()?.runId??"<unknown>",h={usage:p,toolCalls:o?.toolCallCount??0,strategy:gr(e),discovered:[],activeSkills:[...o?.activeSkills??[]],traceSummary:o?.traceSummary,traceSummaryUpTo:o?.traceSummaryUpTo??0},y={...e,run:h,emit:r(w=>{w.type==="usage"&&kt(p,w.usage);let d={...w,runId:F.getStore()?.runId};try{a(d);}catch{}try{e.emit(d);}catch{}},"emit")},x=F.getStore();x&&(x.emit=y.emit,x.state=h);let D=r((w,d)=>{Ze(e.skills??[],w,d,h,y.emit);},"activate"),_=e.config.persistence,g=r(async(w,d)=>{let T=_?.[w];if(T)try{await T(d);}catch(A){y.emit({type:"log",level:"warn",message:`[persistence] ${w} threw: ${A.message}`});}},"callPersistence"),b;if(!o&&i?.length&&c.auto){let w=await xe(i,e.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:fe(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,onUsage:r(d=>y.emit({type:"usage",phase:"compact",usage:d}),"onUsage")});w.compacted&&(i=w.history,b=w.history,y.emit({type:"context.compacted",scope:"history",beforeTokens:w.beforeTokens,afterTokens:w.afterTokens}));}let C=r(async w=>{if(!c.auto||n?.aborted)return;let d=r(()=>({summary:h.traceSummary,upTo:h.traceSummaryUpTo}),"view"),T=re(ce(w,d()));if(T<=c.thresholdTokens)return;let A=w.length-c.keepRecentSteps,S=h.traceSummary?h.traceSummaryUpTo:0;if(A<=S)return;let z=await Et(w.slice(S,A),h.traceSummary,e.synthesizerModel,{summaryMaxTokens:fe(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,render:$e,offset:S});z&&(y.emit({type:"usage",phase:"compact",usage:z.usage}),h.traceSummary=z.summary,h.traceSummaryUpTo=A,y.emit({type:"context.compacted",scope:"trace",beforeTokens:T,afterTokens:re(ce(w,d()))}));},"maybeCompactTrace"),j=false,M=r(()=>{let w=We(p,l);if(w)return w;if(typeof u=="number"&&u>0&&h.toolCalls>=u)return {kind:"tool-calls",tokens:h.toolCalls,cap:u}},"budgetBreach"),$=r(()=>{let w=M();return w?(j||(j=true,y.emit({type:"budget.exceeded",...w})),true):false},"reportBudget"),R;if(o)R=o.plan,y.emit({type:"log",level:"info",message:`[resume] continuing run ${m} from step ${o.stepIndex}/${R.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),y.emit({type:"plan.created",plan:R});else {try{R=await io(s,i,y,n);}catch(w){if(y.emit({type:"error",error:Te(w),phase:"plan"}),De(w)||n?.aborted)throw await g("onRunComplete",{runId:m,startedAt:f,status:"cancelled",input:s,history:i,trace:[],usage:p,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."}]};}y.emit({type:"plan.created",plan:R});for(let w of R.skills??[])D(w,"plan");}let I=o?[...o.trace]:[],v=R,O=o?.stepIndex??0,L=o?.iterations??0,W=o?.revisions??0,H=e.config.maxRevisions??2,k=r((w,d={})=>({runId:m,startedAt:f,status:w,input:s,history:i,plan:v,trace:I,usage:p,stepIndex:O,iterations:L,revisions:W,...h.traceSummary?{traceSummary:h.traceSummary,traceSummaryUpTo:h.traceSummaryUpTo}:{},...h.activeSkills.length?{activeSkills:[...h.activeSkills]}:{},...h.toolCalls?{toolCallCount:h.toolCalls}:{},...d}),"buildSnapshot");o||await g("onRunStart",k("executing"));let P=r(async()=>{await g("onStepComplete",k("executing"));},"persistCheckpoint");for(;L<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(O>=v.steps.length||$())break;L++;let w=v.steps[O];x&&(x.currentStep=w),y.emit({type:"step.start",step:w,index:O});let d=new AbortController;if(t.onStepStart)try{t.onStepStart({step:w,index:O,abort:r(()=>d.abort(),"abort")});}catch(U){y.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${U.message}`});}let T=Fe([n,d.signal]),A;try{await C(I),A=await lo(s,v,w,I,i,y,T);}catch(U){if(n?.aborted)throw y.emit({type:"error",error:Te(U),phase:"execute"}),await g("onRunComplete",k("cancelled",{error:U.message,completedAt:Date.now()})),U;if(d.signal.aborted&&De(U))y.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 y.emit({type:"error",error:Te(U),phase:"execute"}),await g("onRunComplete",k("failed",{error:U.message,completedAt:Date.now()})),U}if(I.push(A),y.emit({type:"step.complete",step:w,result:A}),$()){O++;break}let S=v.steps[O+1]??null;if(S===null){y.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await pr(e.config.replanAfter,A,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:r(U=>y.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${U.message}`}),"onError")})){y.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),O++,await P();continue}let q;try{await C(I),q=await co(s,v,I,S,y,n);}catch(U){throw y.emit({type:"error",error:Te(U),phase:"replan"}),await g("onRunComplete",k(De(U)||n?.aborted?"cancelled":"failed",{error:U.message,completedAt:Date.now()})),U}if(y.emit({type:"replan.decision",mode:q.mode,reason:q.reason,cause:"llm-decision"}),q.mode==="finish")break;if(q.mode==="revise"){if(W>=H){y.emit({type:"revisions.exceeded",cap:H});break}W++,v=hr(y,q.newPlan),y.emit({type:"plan.revised",plan:v,reason:q.reason});for(let U of v.skills??[])D(U,"plan");O=0,await P();continue}O++,await P();}let N;try{await C(I),N=await uo(s,v,I,i,y,n);}catch(w){throw y.emit({type:"error",error:Te(w),phase:"synthesize"}),await g("onRunComplete",k(De(w)||n?.aborted?"cancelled":"failed",{error:w.message,completedAt:Date.now()})),w}return y.emit({type:"final",text:N}),await g("onRunComplete",k("complete",{text:N,completedAt:Date.now()})),{text:N,plan:v,trace:I,iterations:L,usage:p,...b?{compactedHistory:b}:{}}},"runAgentLoopInner"),hr=r((e,t)=>{let o=Ne(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=it(e,t.skills),{skills:s,...i}=t;return {...i,steps:t.steps.slice(0,o),...n?{skills:n}:{}}},"reviseInto"),Te=r(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var ho=Symbol.for("@dudko.dev/agent:wrapped-tool"),ct=class extends Error{static{r(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=r(e=>{let t=F.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new ct(e);return t.toolCalls++,()=>{t.toolCalls--;}},"reserveToolCall"),Tr=r(e=>Object.prototype.toString.call(e)==="[object AsyncGeneratorFunction]","isAsyncGeneratorFunction"),kr=r((e,t,o,n={})=>{if(t[ho])return t;let s=pe(t),i=n.builtIn===true,a=t.execute,c=r(async(p,f)=>{let m=i?()=>{}:yr(o.maxToolCalls);try{await o.approval.gate(e,p,{readOnly:s,builtIn:i,signal:f?.abortSignal});}catch(h){throw m(),h}},"before"),l;a&&(l=Tr(a)?async function*(p,f){await c(p,f),yield*a(p,f);}:async(p,f)=>(await c(p,f),a(p,f)));let u=Pt({...t,...l?{execute:l}:{}},o.maxToolOutputChars);return Object.defineProperty(u,ho,{value:true,enumerable:false}),u},"wrapTool"),ke=r((e,t,o={})=>{let n={};for(let[s,i]of Object.entries(e))n[s]=kr(s,i,t,o);return n},"wrapToolSet");var ze={none:0,error:1,warn:2,info:3,debug:4},ut=r(async(e,t)=>{let o=ze[e.logLevel]>=ze.debug,n=r(d=>{if(t)try{t(d);}catch(T){o&&console.error("[agent] event handler threw:",T);}},"emit"),s=r((d,T)=>{ze[e.logLevel]>=ze[d]&&n({type:"log",level:d,message:T});},"log"),i=Kt(e.skills),a=r(async(d,T)=>{if(!e.inputSanitizer)return T;try{return await e.inputSanitizer(d,T)}catch{return "[input redacted: sanitizer failed]"}},"sanitizeForApproval"),c=gt(e.toolApproval,{sanitize:a,fallbackEmit:n}),l=ae(e.compaction),u={approval:c,maxToolCalls:e.maxToolCalls,maxToolOutputChars:l.maxToolOutputChars},p=ke(Ht(i),u,{builtIn:true}),f=e.toolSelectionStrategy??"auto",m=f==="search"||f==="auto",h=false,y=r(()=>[],"catalogRef"),x=m?ke(Jt(()=>y()),u,{builtIn:true}):void 0,D=r(d=>{for(let T of Object.keys(p))if(d[T])throw new Error(`Tool "${T}" collides with a built-in skill tool of the same name`);if(x&&d[Q]){if(f==="search")throw new Error(`Tool "${Q}" collides with the built-in tool-search tool of the same name`);h||(h=true,s("warn",`[tools] a tool named "${Q}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),_,g=r((d,T)=>{if(!e.tools)return d;let A=[];for(let[S,z]of Object.entries(e.tools)){if(d.tools[S]&&T(S),e.availableTools?.length&&!e.availableTools.includes(S)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(S))continue;d.tools[S]=z;let se=typeof z=="object"&&z&&"description"in z?z.description:"";A.push({name:S,description:typeof se=="string"?se:"",server:"<native>",readOnly:pe(z)});}return {tools:d.tools,catalog:[...d.catalog,...A]}},"mergeNativeTools"),b=r(async()=>{let d=await _t(e.mcpServers,s,e.clientName,e.outputSanitizer,S=>_?.(S),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),T=Ve(d.tools,d.catalog,e.availableTools,e.excludedTools,s),A;try{A=g(T,S=>{throw new Error(`Native tool "${S}" collides with an MCP-registered tool of the same name`)}),D(A.tools);}catch(S){throw d.close().catch(()=>{}),S}return {connection:d,tools:ke(A.tools,u),catalog:A.catalog}},"connect"),C;try{C=await b();}catch(d){throw n({type:"error",error:d instanceof Error?d:new Error(String(d)),phase:"init"}),d}let j=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&j>0&&!C.connection.results.some(T=>T.connected)){let T=C.connection.results.filter(S=>!S.connected).map(S=>`${S.name}: ${S.error??"unknown"}`).join("; ");await C.connection.close().catch(()=>{});let A=new Error(`All ${j} configured MCP server(s) failed to connect [${T}]`);throw n({type:"error",error:A,phase:"init"}),A}let M,$,R;try{let d=Re(e,void 0,void 0,"executor"),T=Re(e,e.planner,e.plannerModel,"planner"),A=Re(e,e.synthesizer,e.synthesizerModel,"synthesizer");[M,$,R]=await Promise.all([Ee(e.clientName,d),Ee(e.clientName,T),Ee(e.clientName,A)]);}catch(d){throw await C.connection.close().catch(()=>{}),n({type:"error",error:d instanceof Error?d:new Error(String(d)),phase:"init"}),d}let I=r(d=>d.map(T=>({name:T.name,description:T.description,server:T.server,readOnly:T.readOnly===true})),"toEntries"),v={config:e,executorModel:M,plannerModel:$,synthesizerModel:R,tools:C.tools,toolCatalog:I(C.catalog),emit:n,...Object.keys(p).length?{builtinTools:p}:{},...i.length?{skills:i}:{},approval:c};y=r(()=>v.toolCatalog,"catalogRef");let O=r(()=>{x&&!h?v.findTools=x:delete v.findTools;},"syncFindTools");O();let L=0,W=false,H=false,k=false,P=new Set,N=r(async d=>{await C.connection.refreshServer(d);let T=Ve(C.connection.tools,C.connection.catalog,e.availableTools,e.excludedTools),A=g(T,z=>{throw new Error(`Native tool "${z}" collides with an MCP-registered tool of the same name`)});D(A.tools);let S=ke(A.tools,u);for(let z of Object.keys(v.tools))delete v.tools[z];Object.assign(v.tools,S),v.toolCatalog=I(A.catalog),O(),s("info",`[mcp] ${d}: tool list refreshed (${A.catalog.length} tools total after filter)`);},"applyRefresh"),w=r(async()=>{if(!(k||W||H)&&!(L>0||P.size===0)){k=true;try{for(;P.size>0&&L===0&&!W&&!H;){let d=P.values().next().value;P.delete(d);try{await N(d);}catch(T){s("warn",`[mcp] ${d}: refresh failed - ${T.message}`);}}}finally{k=false;}}},"drainPendingRefreshes");return _=r(d=>{P.add(d),w();},"onToolsChanged"),{run:r(async d=>{if(W)throw new Error("Agent is closed");if(H)throw new Error("Agent is reconnecting; retry shortly");if(k)throw new Error("Agent is refreshing tools; retry shortly");let T=e.maxConcurrentRuns;if(typeof T=="number"&&T>0&&L>=T)throw new Error(`maxConcurrentRuns reached (${L}/${T}); rate-limit on the caller side or raise the cap`);L++;try{return await fo(v,d)}finally{L--,w();}},"run"),listTools:r(()=>v.toolCatalog.map(d=>({...d})),"listTools"),listSkills:r(()=>i.map(d=>({name:d.name,description:d.description})),"listSkills"),compact:r(async d=>{let T=await xe(d.history,v.synthesizerModel,{thresholdTokens:l.thresholdTokens,keepRecentTurns:l.keepRecentTurns,summaryMaxTokens:fe(e,l.summaryMaxTokens),force:d.force,signal:d.signal,timeoutMs:e.llmTimeoutMs,onUsage:r(A=>n({type:"usage",phase:"compact",usage:A}),"onUsage")});return T.compacted&&n({type:"context.compacted",scope:"history",beforeTokens:T.beforeTokens,afterTokens:T.afterTokens}),{history:T.history,...T.summary?{summary:T.summary}:{},beforeTokens:T.beforeTokens,afterTokens:T.afterTokens,compacted:T.compacted}},"compact"),setToolApprovalMode:r(d=>c.setMode(d),"setToolApprovalMode"),getToolApprovalMode:r(()=>c.getMode(),"getToolApprovalMode"),reconnect:r(async()=>{if(W)throw new Error("Agent is closed");if(H)throw new Error("Already reconnecting");if(k)throw new Error("Agent is refreshing tools; retry shortly");if(L>0)throw new Error(`Cannot reconnect with ${L} active run(s)`);H=true;try{let d=C.connection;P.clear();let T=await b();for(let A of Object.keys(v.tools))delete v.tools[A];Object.assign(v.tools,T.tools),v.toolCatalog=I(T.catalog),O(),C=T,await d.close().catch(()=>{});}finally{H=false;}},"reconnect"),close:r(async d=>{W=true;let T=d?.waitForRuns??false,A=d?.timeoutMs??3e4,S=Date.now()+A;if(T&&L>0)for(;L>0&&Date.now()<S;)await new Promise(U=>setTimeout(U,50));L>0&&n({type:"log",level:"warn",message:`[agent] close called with ${L} active run(s); they will fail mid-flight`});let z=Math.max(S-Date.now(),0),se=false,q;await Promise.race([C.connection.close().catch(()=>{}),new Promise(U=>{q=setTimeout(()=>{se=true,U();},z),q.unref?.();})]),q&&clearTimeout(q),se&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${z}ms; abandoning transport(s)`});},"close"),activeRuns:r(()=>L,"activeRuns")}},"createAgent");var wr=r(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"),we=r(e=>{try{return structuredClone(e)}catch{return wr(e)}},"toCloneable");var Ar=r(e=>{let t=new AbortController,o=new Map,n=false,s=r(a=>{try{e.postMessage(a);}catch{e.postMessage(we(a));}},"post"),i=r(async a=>{let c={};for(let u of a.proxied)c[u.name]=Y(dynamicTool({description:u.description,inputSchema:jsonSchema(u.inputSchema),execute:r((p,f)=>new Promise((m,h)=>{let y=randomUUID(),x=f?.abortSignal,D=r(()=>{o.delete(y),h(x?.reason??new DOMException("Aborted","AbortError"));},"onAbort");if(x?.aborted){D();return}x?.addEventListener("abort",D,{once:true}),o.set(y,_=>{o.delete(y),x?.removeEventListener("abort",D),_.ok?m(_.output):h(new Error(typeof _.output=="string"?_.output:JSON.stringify(_.output)));}),s({type:"tool-call",callId:y,name:u.name,input:we(p)});}),"execute")}),u.readOnly===true);let l;try{l=await ut({...a.config,...a.proxied.length?{tools:c}:{}},p=>s({type:"event",event:we(p)}));let u=await l.run({input:a.task,signal:t.signal});s({type:"done",text:u.text,usage:we(u.usage),iterations:u.iterations});}catch(u){s({type:"error",error:Ke(u)});}finally{await l?.close({timeoutMs:2e3}).catch(()=>{});}},"run");e.on("message",a=>{switch(a.type){case "run":n||(n=true,i(a));break;case "abort":t.abort();break;case "tool-result":o.get(a.callId)?.({ok:a.ok,output:a.output});break}});},"serveSubagentWorker");!isMainThread&&parentPort&&Ar(parentPort);export{Ar as serveSubagentWorker};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent",
3
- "version": "0.0.30",
3
+ "version": "0.0.32",
4
4
  "type": "module",
5
5
  "description": "Tool-using planning agent over MCP servers, built on the Vercel AI SDK.",
6
6
  "keywords": [
@@ -89,9 +89,9 @@
89
89
  "prepublishOnly": "npm run typecheck && npm test && npm run build"
90
90
  },
91
91
  "dependencies": {
92
- "@modelcontextprotocol/sdk": "^1.30.1",
92
+ "@modelcontextprotocol/sdk": "^1.32.1",
93
93
  "@opentelemetry/api": "^1.9.1",
94
- "ai": "^7.0.116",
94
+ "ai": "^7.0.137",
95
95
  "zod": "^4.6.5"
96
96
  },
97
97
  "peerDependencies": {
@@ -139,15 +139,15 @@
139
139
  }
140
140
  },
141
141
  "devDependencies": {
142
- "@ai-sdk/amazon-bedrock": "^5.0.96",
143
- "@ai-sdk/anthropic": "^4.0.65",
144
- "@ai-sdk/azure": "^4.0.81",
145
- "@ai-sdk/deepseek": "^3.0.54",
146
- "@ai-sdk/google": "^4.0.82",
147
- "@ai-sdk/google-vertex": "^5.0.95",
148
- "@ai-sdk/openai": "^4.0.77",
149
- "@ai-sdk/openai-compatible": "^3.0.57",
150
- "@ai-sdk/xai": "^5.0.10",
142
+ "@ai-sdk/amazon-bedrock": "^5.0.113",
143
+ "@ai-sdk/anthropic": "^4.0.78",
144
+ "@ai-sdk/azure": "^4.0.99",
145
+ "@ai-sdk/deepseek": "^3.0.63",
146
+ "@ai-sdk/google": "^4.0.93",
147
+ "@ai-sdk/google-vertex": "^5.0.109",
148
+ "@ai-sdk/openai": "^4.0.91",
149
+ "@ai-sdk/openai-compatible": "^3.0.67",
150
+ "@ai-sdk/xai": "^5.0.20",
151
151
  "@types/node": "^22.9.0",
152
152
  "prettier": "^3.9.9",
153
153
  "tsup": "^8.5.1",