@dudko.dev/agent 0.0.36 → 0.0.37
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 +91 -2
- package/dist/cli.js +90 -68
- package/dist/index.cjs +71 -57
- package/dist/index.d.cts +76 -3
- package/dist/index.d.ts +76 -3
- package/dist/index.js +71 -57
- package/dist/subagent-worker.js +63 -53
- package/package.json +11 -11
package/dist/index.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import {randomBytes,randomUUID}from'crypto';import {AsyncLocalStorage,AsyncResource}from'async_hooks';import {generateText,dynamicTool,jsonSchema,tool,streamObject,stepCountIs,streamText,generateObject,asSchema}from'ai';import {auth,UnauthorizedError}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {readFile,writeFile,chmod,rename,mkdir,readdir,stat,rm}from'fs/promises';import ae from'path';import {URL as URL$1}from'url';import sn,{tmpdir}from'os';import {trace,SpanStatusCode}from'@opentelemetry/api';import {z}from'zod';import {Worker}from'worker_threads';var _o=Object.defineProperty;var s=(e,t)=>_o(e,"name",{value:t,configurable:true});var K=new AsyncLocalStorage,Do=s(()=>K.getStore()?.runId,"getCurrentRunId"),Be=s(()=>K.getStore()?.sandboxDir,"getCurrentRunSandbox");var Je=new Set(["autopilot","ask-writes","ask-all","read-only"]),Ot=s(e=>typeof e=="string"&&Je.has(e),"isToolApprovalMode"),he=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}},X=s((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),le=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"),Rt=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"),Et=s(e=>{if(e.builtIn)return {permission:"allow",source:"builtin"};if(e.remembered?.has(e.name))return {permission:"allow",source:"remembered"};let t=Rt(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"),Oe=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 Oe);},t)),e.then(a=>{l(),n(a);},a=>{l(),r(a);});}),"awaitDecision"),Pt=s((e,t={})=>{let o=e?.mode??"autopilot";if(!Ot(o))throw new Error(`toolApproval.mode must be ${[...Je].join(" | ")}, got: ${JSON.stringify(o)}`);let n=new Set;return {getMode:s(()=>o,"getMode"),setMode:s(i=>{if(!Ot(i))throw new Error(`tool approval mode must be ${[...Je].join(" | ")}, got: ${JSON.stringify(i)}`);o=i;},"setMode"),remembered:n,gate:s(async(i,l,c)=>{let a=Et({name:i,readOnly:c.readOnly,mode:o,rules:e?.rules,remembered:n,builtIn:c.builtIn});if(a.permission==="allow")return;let p=K.getStore(),d=p?.emit??t.fallbackEmit??(()=>{}),f=randomUUID(),u=s((b,C)=>{throw d({type:"tool.approval-resolved",id:f,name:i,approved:false,reason:b,automatic:C}),new he(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 H={id:f,toolName:i,input:T,readOnly:c.readOnly,...x?{step:x}:{},...p?.runId?{runId:p.runId}:{}},M;try{M=await Ko(Promise.resolve().then(()=>h(H)),e?.timeoutMs,c.signal);}catch(b){if(b instanceof Oe&&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(M);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 he(g.reason)},"gate")}},"createApprovalController");var ye=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"),Ge=s((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),Mt=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"),Ye=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 Lt=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"?Lt(o.cause,t):false},"isRetriable"),oe=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||!Lt(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"),Ve=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),Y=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Ve([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"),ce=s(()=>({inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0,cacheWriteTokens:0}),"emptyUsage"),Te=s(e=>typeof e=="number"&&Number.isFinite(e)?e:0,"n"),j=s(e=>{if(!e)return ce();let t=Te(e.inputTokens),o=Te(e.outputTokens);return {inputTokens:t,outputTokens:o,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:t+o,reasoningTokens:Te(e.outputTokenDetails?.reasoningTokens??e.reasoningTokens),cachedInputTokens:Te(e.inputTokenDetails?.cacheReadTokens??e.cachedInputTokens),cacheWriteTokens:Te(e.inputTokenDetails?.cacheWriteTokens)}},"normalizeUsage"),ke=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"),$t=s((e,t)=>{Object.assign(e,ke(e,t));},"accumulateUsage"),pe=s((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText"),Xe=s(e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e),"errorMessage");var ne=s(e=>{let t=e.limits?.maxTotalTokens??e.maxTotalTokens;return {...e.limits,...t!==void 0?{maxTotalTokens:t}:{}}},"resolveLimits"),we=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isCap"),Ut=s(e=>!!(e&&(we(e.maxInputTokens)||we(e.maxOutputTokens)||we(e.maxReasoningTokens)||we(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(we(i)&&r>=i)return {kind:n,tokens:r,cap:i}},"checkLimits"),Jo=s(e=>e.reduce((t,o)=>ke(t,j(o.usage)),ce()),"sumStepUsage"),_t=s((e,t,o)=>({steps:n})=>{let r=Ce(ke(e(),Jo(n)),t);return r?(o?.(r),true):false},"limitsStopCondition");var Nt=s(e=>{if(!(e===void 0||e===false))return e===true?{level:"medium"}:typeof e=="string"?{level:e}:{...e,level:e.level??"medium"}},"normalizeThinking"),Qe=s(e=>{let t=Nt(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"),et=s((e,t)=>{let o=e.stageThinking?.[t];return o!==void 0?o:e.thinking},"stageThinkingSetting"),Re=s((e,t)=>Nt(et(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),Ze=s(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),Dt=s((e,t)=>{let o={...e};for(let[n,r]of Object.entries(t))o[n]=Ze(o[n])&&Ze(r)?Dt(o[n],r):r;return o},"deepMerge"),tt=s((...e)=>{let t;for(let o of e)if(o)for(let[n,r]of Object.entries(o))Ze(r)&&(t??={},t[n]=Dt(t[n]??{},r));return t},"mergeProviderOptions");var zt=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),re=s((e,t,o)=>{let n=ye(e.promptCaching),r=Qe(et(e,t)),i=tt(r.providerOptions,Mt(n,e.clientName,t)),l=zt(ne(e).perCall?.[t]);return {instructions:Ge(o,n),...r.reasoning?{reasoning:r.reasoning}:{},...i?{providerOptions:i}:{},...l?{maxOutputTokens:l}:{}}},"stageCallOptions"),be=s((e,t)=>{let o=zt(ne(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var Ft=128e3,Go=2e4,se=s((e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t,"nonNeg"),de=s(e=>{let t=se(e?.contextWindowTokens,0)||Ft;return {auto:e?.auto!==false,contextWindowTokens:t,thresholdTokens:se(e?.thresholdTokens,0)||Math.floor(t/2),keepRecentTurns:se(e?.keepRecentTurns,4),keepRecentSteps:se(e?.keepRecentSteps,3),summaryMaxTokens:se(e?.summaryMaxTokens,0)||1024,maxToolOutputChars:se(e?.maxToolOutputChars,Go),clearToolResultsAfterTokens:se(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:se(e?.keepToolResults,3)}},"resolveCompaction"),ie=s(e=>Math.ceil(e.length/4),"estimateTokens"),nt="[Summary of earlier conversation]",rt=s(e=>e.role==="assistant"&&e.content.startsWith(nt),"isSummaryTurn"),ot=s(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
|
|
2
|
-
`),"renderTurns"),
|
|
1
|
+
import {randomBytes,randomUUID}from'crypto';import {AsyncLocalStorage,AsyncResource}from'async_hooks';import {generateText,dynamicTool,jsonSchema,tool,streamObject,stepCountIs,streamText,generateObject,asSchema}from'ai';import {auth,UnauthorizedError}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {readFile,writeFile,chmod,rename,mkdir,readdir,stat,rm}from'fs/promises';import le from'path';import {URL as URL$1}from'url';import fn,{tmpdir}from'os';import {trace,SpanStatusCode}from'@opentelemetry/api';import {z}from'zod';import {Worker}from'worker_threads';var qo=Object.defineProperty;var s=(e,t)=>qo(e,"name",{value:t,configurable:true});var W=new AsyncLocalStorage,Jo=s(()=>W.getStore()?.runId,"getCurrentRunId"),Ye=s(()=>W.getStore()?.sandboxDir,"getCurrentRunSandbox");var Ve=new Set(["autopilot","ask-writes","ask-all","read-only"]),Mt=s(e=>typeof e=="string"&&Ve.has(e),"isToolApprovalMode"),Te=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}},Z=s((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),ue=s(e=>!!e&&typeof e=="object"&&e.readOnly===true,"isReadOnlyTool"),$t=new Map,Yo=s(e=>{let t=$t.get(e);if(!t){let o=e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t=new RegExp(`^${o}$`),$t.set(e,t);}return t},"globToRegExp"),Lt=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("*")&&Yo(n).test(t)&&(!o||n.length>o.pattern.length)&&(o={pattern:n,permission:r});return o},"matchToolRule"),Ut=s(e=>{if(e.builtIn)return {permission:"allow",source:"builtin"};if(e.remembered?.has(e.name))return {permission:"allow",source:"remembered"};let t=Lt(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"),Vo=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"),Re=class extends Error{static{s(this,"ApprovalTimeout");}},Xo=s((e,t,o)=>new Promise((n,r)=>{let i,a=s(()=>{i&&clearTimeout(i),o?.removeEventListener("abort",c);},"done");function c(){a(),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(()=>{a(),r(new Re);},t)),e.then(l=>{a(),n(l);},l=>{a(),r(l);});}),"awaitDecision"),_t=s((e,t={})=>{let o=e?.mode??"autopilot";if(!Mt(o))throw new Error(`toolApproval.mode must be ${[...Ve].join(" | ")}, got: ${JSON.stringify(o)}`);let n=new Set;return {getMode:s(()=>o,"getMode"),setMode:s(i=>{if(!Mt(i))throw new Error(`tool approval mode must be ${[...Ve].join(" | ")}, got: ${JSON.stringify(i)}`);o=i;},"setMode"),remembered:n,gate:s(async(i,a,c)=>{let l=Ut({name:i,readOnly:c.readOnly,mode:o,rules:e?.rules,remembered:n,builtIn:c.builtIn});if(l.permission==="allow")return;let u=W.getStore(),d=u?.emit??t.fallbackEmit??(()=>{}),m=randomUUID(),g=s((k,A)=>{throw d({type:"tool.approval-resolved",id:m,name:i,approved:false,reason:k,automatic:A}),new Te(k)},"deny");l.permission==="deny"&&g(l.source==="rule"?`denied by rule "${l.rule}"`:`"${o}" mode allows read-only tools only`,true);let h=e?.onRequest;if(!h){g("no approval handler configured",true);return}let w=t.sanitize?await t.sanitize(i,a):a,T=u?.currentStep;d({type:"tool.approval-requested",id:m,name:i,input:w,readOnly:c.readOnly,...T?{step:T}:{}});let K={id:m,toolName:i,input:w,readOnly:c.readOnly,...T?{step:T}:{},...u?.runId?{runId:u.runId}:{}},D;try{D=await Xo(Promise.resolve().then(()=>h(K)),e?.timeoutMs,c.signal);}catch(k){if(k instanceof Re&&g(`no decision within ${e?.timeoutMs}ms`,true),c.signal?.aborted)throw d({type:"tool.approval-resolved",id:m,name:i,approved:false,reason:"aborted",automatic:true}),k;g(`approval handler failed: ${k?.message??String(k)}`,true);return}let y=Vo(D);if(y.approved&&y.remember&&n.add(i),d({type:"tool.approval-resolved",id:m,name:i,approved:y.approved,...y.reason?{reason:y.reason}:{},automatic:false}),!y.approved)throw new Te(y.reason)},"gate")}},"createApprovalController");var ke=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"),Xe=s((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),Nt=s((e,t,o)=>e.enabled?{openai:{promptCacheKey:e.key??`${t}:${o}`}}:void 0,"cacheProviderOptions"),Zo=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,a=Object.keys(n).length?{...i,anthropic:n}:i,{providerOptions:c,...l}=e;return Object.keys(a).length?{...l,providerOptions:a}:l},"withoutBreakpoint"),Ze=s((e,t)=>{if(!t.enabled||e.length===0)return e;let o=e.map((i,a)=>a<e.length-1?Zo(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 Dt=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"?Dt(o.cause,t):false},"isRetriable"),ne=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||!Dt(i))throw i;t.onRetry?.(r+1,i);let a=o*2**r+Math.random()*250;await Qo(a,t.signal);}}throw n},"withRetry"),Qo=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"),Qe=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),V=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Qe([e,AbortSignal.timeout(t)]),"withTimeout"),en=new Set(["authorization","proxy-authorization","x-api-key","api-key","cookie","set-cookie"]),tn=s(e=>{if(!e)return e;let t={};for(let[o,n]of Object.entries(e))t[o]=en.has(o.toLowerCase())?"***redacted***":n;return t},"redactHeaders"),pe=s(()=>({inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0,cacheWriteTokens:0}),"emptyUsage"),we=s(e=>typeof e=="number"&&Number.isFinite(e)?e:0,"n"),H=s(e=>{if(!e)return pe();let t=we(e.inputTokens),o=we(e.outputTokens);return {inputTokens:t,outputTokens:o,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:t+o,reasoningTokens:we(e.outputTokenDetails?.reasoningTokens??e.reasoningTokens),cachedInputTokens:we(e.inputTokenDetails?.cacheReadTokens??e.cachedInputTokens),cacheWriteTokens:we(e.inputTokenDetails?.cacheWriteTokens)}},"normalizeUsage"),be=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"),zt=s((e,t)=>{Object.assign(e,be(e,t));},"accumulateUsage"),de=s((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText"),et=s(e=>e instanceof Error?e.message:typeof e=="string"?e:JSON.stringify(e),"errorMessage");var re=s(e=>{let t=e.limits?.maxTotalTokens??e.maxTotalTokens;return {...e.limits,...t!==void 0?{maxTotalTokens:t}:{}}},"resolveLimits"),ve=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isCap"),jt=s(e=>!!(e&&(ve(e.maxInputTokens)||ve(e.maxOutputTokens)||ve(e.maxReasoningTokens)||ve(e.maxTotalTokens))),"hasTokenLimits"),Ee=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(ve(i)&&r>=i)return {kind:n,tokens:r,cap:i}},"checkLimits"),on=s(e=>e.reduce((t,o)=>be(t,H(o.usage)),pe()),"sumStepUsage"),Ft=s((e,t,o)=>({steps:n})=>{let r=Ee(be(e(),on(n)),t);return r?(o?.(r),true):false},"limitsStopCondition");var Kt=s(e=>{if(!(e===void 0||e===false))return e===true?{level:"medium"}:typeof e=="string"?{level:e}:{...e,level:e.level??"medium"}},"normalizeThinking"),ot=s(e=>{let t=Kt(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"),nt=s((e,t)=>{let o=e.stageThinking?.[t];return o!==void 0?o:e.thinking},"stageThinkingSetting"),Pe=s((e,t)=>Kt(nt(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),tt=s(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),Ht=s((e,t)=>{let o={...e};for(let[n,r]of Object.entries(t))o[n]=tt(o[n])&&tt(r)?Ht(o[n],r):r;return o},"deepMerge"),rt=s((...e)=>{let t;for(let o of e)if(o)for(let[n,r]of Object.entries(o))tt(r)&&(t??={},t[n]=Ht(t[n]??{},r));return t},"mergeProviderOptions");var Wt=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),se=s((e,t,o)=>{let n=ke(e.promptCaching),r=ot(nt(e,t)),i=rt(r.providerOptions,Nt(n,e.clientName,t)),a=Wt(re(e).perCall?.[t]);return {instructions:Xe(o,n),...r.reasoning?{reasoning:r.reasoning}:{},...i?{providerOptions:i}:{},...a?{maxOutputTokens:a}:{}}},"stageCallOptions"),Se=s((e,t)=>{let o=Wt(re(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var Bt=128e3,nn=2e4,ie=s((e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t,"nonNeg"),ge=s(e=>{let t=ie(e?.contextWindowTokens,0)||Bt;return {auto:e?.auto!==false,contextWindowTokens:t,thresholdTokens:ie(e?.thresholdTokens,0)||Math.floor(t/2),keepRecentTurns:ie(e?.keepRecentTurns,4),keepRecentSteps:ie(e?.keepRecentSteps,3),summaryMaxTokens:ie(e?.summaryMaxTokens,0)||1024,maxToolOutputChars:ie(e?.maxToolOutputChars,nn),clearToolResultsAfterTokens:ie(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:ie(e?.keepToolResults,3)}},"resolveCompaction"),ae=s(e=>Math.ceil(e.length/4),"estimateTokens"),it="[Summary of earlier conversation]",at=s(e=>e.role==="assistant"&&e.content.startsWith(it),"isSummaryTurn"),st=s(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
|
|
2
|
+
`),"renderTurns"),rn=`You compress conversation history for an AI agent.
|
|
3
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.`,
|
|
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.`,sn=`You compress the execution trace of an AI agent.
|
|
5
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.`,
|
|
7
|
-
${
|
|
8
|
-
${
|
|
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.`,Ie=s(async(e,t,o={})=>{let n=ae(st(e)),r={history:e,beforeTokens:n,afterTokens:n,compacted:false},i=o.thresholdTokens??Bt/2;if(!o.force&&n<=i)return r;let a=Math.max(0,o.keepRecentTurns??4),c=e.length-a;if(c<=0)return r;let l=e.slice(0,c);if(l.length===1&&at(l[0]))return r;try{let u=await generateText({model:t,instructions:rn,prompt:`Conversation to summarize:
|
|
7
|
+
${st(l)}`,maxOutputTokens:o.summaryMaxTokens??1024,abortSignal:V(o.signal,o.timeoutMs??0),maxRetries:0}),d=H(u.usage);o.onUsage?.(d);let m=u.text.trim();if(!m)return {...r,usage:d};let g=[{role:"assistant",content:`${it}
|
|
8
|
+
${m}`},...e.slice(c)];return {history:g,summary:m,beforeTokens:n,afterTokens:ae(st(g)),compacted:!0,usage:d}}catch{return r}},"compactHistory"),Jt=s(async(e,t,o,n)=>{try{let r=await generateText({model:o,instructions:sn,prompt:[t?`Summary of the steps before these:
|
|
9
9
|
${t}
|
|
10
10
|
`:"",`Steps to summarize:
|
|
11
11
|
${n.render(e,n.offset)}`].filter(Boolean).join(`
|
|
12
|
-
`),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:Y(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:j(r.usage)}:void 0}catch{return}},"summarizeTrace"),Ht=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:pe(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:pe(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:pe(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"),st=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Ht(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Ee={version:"0.0.36"};var an=ae.join(sn.homedir(),".agent","mcp-oauth.json"),Pe=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await 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 writeFile(o,JSON.stringify(t,null,2),{mode:384}),await chmod(o,384).catch(()=>{}),await 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 mkdir(ae.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));});}},it=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"]),at=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"),Me=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Pe,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},at(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=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 Me(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,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(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=Ee.version,lt,Tn=s(()=>(lt||(lt=trace.getTracer(hn,yn)),lt),"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"},G=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: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=Ee.version,ct=64,Se=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,ct-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Le=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Gt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Gt;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"),me=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 me},"state"),saveCodeVerifier:s(()=>{throw new me},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new me},"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(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof me?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Yt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,C)=>{let W=`${Se(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 L=[],N=0,R=0;for(let I of C){let v=W+Se(I.name);if(v.length>ct){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${ct}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=_n(v,a);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 $=I.description??"",q=I.annotations?.readOnlyHint===true;a[O]=dynamicTool({description:$,inputSchema:jsonSchema(I.inputSchema),execute:s(async(B,k)=>G("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let z=B??{};if(i)try{let S=await i(O,z);z=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),z={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:z},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(O,y);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Le("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:O,sandboxDir:m?void 0:Be()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Le(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),q&&X(a[O]),p.push({name:O,description:$,server:g,readOnly:q}),L.push(O),N++;}f.set(g,L),R>0?t("info",`[mcp] ${g}: ${N} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${N} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Gt} 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 C=b.connectTimeoutMs??l.connectTimeoutMs,W=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:Nn,L,N=false,R=H(g,b,I=>{L=I;},()=>N);try{return await(W>0?Fn(R,W,()=>{N=!0;}):R)}catch(I){L&&await L.close().catch(()=>{});let v=N?`connect timed out after ${W}ms`:I.message,O=!N&&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"),H=s(async(g,b,C,W)=>{let L,N=s(async()=>{if(W())throw await L?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(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($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`),at(b.url,`MCP server "${g}"`),await jn(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 N(),L=new Client({name:o,version:Un}),C(L),await L.connect(R),await N(),r&&L.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,L);return await N(),{name:g,client:L,listed:I}}catch(R){throw L&&await L.close().catch(()=>{}),R}},"connectOnce"),M=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of M){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"),Bt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return Bt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?Bt[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,Jt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=randomUUID().slice(0,8),p=ae.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await 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",
|
|
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
|
|
15
|
-
`):
|
|
16
|
-
`).split(/\n\s*\n/).map(
|
|
17
|
-
`);continue}t[
|
|
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=
|
|
19
|
-
`),"renderSkillsIndex"),
|
|
20
|
-
${c.content.trim()}`,
|
|
21
|
-
\u2026 [skill instructions clipped: budget exhausted]`);continue}if(
|
|
22
|
-
\u2026 [skill instructions clipped]`),i=o;continue}r.push(
|
|
23
|
-
|
|
24
|
-
`)},"renderActiveSkills"),
|
|
25
|
-
`)},"renderSearchCatalog"),
|
|
26
|
-
`)},"renderHistory"),
|
|
27
|
-
`)},"renderToolCatalog"),
|
|
12
|
+
`),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:V(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:H(r.usage)}:void 0}catch{return}},"summarizeTrace"),Gt=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:de(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:de(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:de(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),an=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"),lt=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Gt(o?await o(r):an(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Me={version:"0.0.37"};var hn=le.join(fn.homedir(),".agent","mcp-oauth.json"),$e=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=hn){this.filePath=t;}async readAll(){try{let t=JSON.parse(await 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 writeFile(o,JSON.stringify(t,null,2),{mode:384}),await chmod(o,384).catch(()=>{}),await 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 mkdir(le.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));});}},ct=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);}},yn=30,Tn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),kn=new Set(["localhost","127.0.0.1","[::1]","::1"]),ut=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:"||kn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Le=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new $e,this.ns=Tn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??yn)*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},ut(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=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");}},wn=s(e=>new Le(e),"createNodeOAuthProvider"),bn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),vn=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(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 An="@dudko.dev/agent",xn=Me.version,pt,Cn=s(()=>(pt||(pt=trace.getTracer(An,xn)),pt),"tracer"),P={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"},Y=s(async(e,t,o)=>Cn().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:SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Kn=s(e=>"command"in e&&!!e.command,"isStdioConfig"),Hn=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Wn=Me.version,dt=64,Ae=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),qn=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,dt-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Ue=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Bn=3e4,Qt=100,Jn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Qt;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||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),fe=class extends Error{static{s(this,"RefreshOnlyAbort");}},Gn=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 fe},"state"),saveCodeVerifier:s(()=>{throw new fe},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new fe},"redirectToAuthorization")}),"refreshOnly"),Yn=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(Gn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof fe?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),eo=s(async(e,t,o,n,r,i,a={})=>{let c=new Map,l={},u=[],d=[],m=new Map,g=s((y,k,A)=>{let j=`${Ae(y)}__`;for(let C of m.get(y)??[])delete l[C];for(let C=u.length-1;C>=0;C--)u[C].server===y&&u.splice(C,1);let R=[],$=0,L=0;for(let C of A){let I=j+Ae(C.name);if(I.length>dt){t("warn",`[mcp] ${y}: tool "${C.name}" prefixed name (${I.length} chars) exceeds the ${dt}-char limit enforced by major LLM providers; skipping`),L++;continue}let O=qn(I,l);if(!O){t("warn",`[mcp] ${y}: no free name left for tool "${C.name}"; skipping`),L++;continue}O!==I&&t("warn",`[mcp] ${y}: tool name "${I}" already taken; mounted as "${O}"`);let x=C.description??"",E=C.annotations?.readOnlyHint===true;l[O]=dynamicTool({description:x,inputSchema:jsonSchema(C.inputSchema),execute:s(async(q,J)=>Y("agent.tool_call",{[P.TOOL_NAME]:O},async b=>{let M=q??{};if(i)try{let v=await i(O,M);M=v&&typeof v=="object"&&!Array.isArray(v)?v:{value:v};}catch(v){t("warn",`[mcp] ${O}: inputSanitizer threw - ${v.message}; input replaced with placeholder`),M={_redacted:"inputSanitizer failed"};}let F;try{F=await k.callTool({name:C.name,arguments:M},void 0,J?.abortSignal?{signal:J.abortSignal}:void 0);}catch(v){throw b.setAttribute(P.TOOL_OK,false),v}let f=F.isError===true,p=F.content;if(n)try{p=await n(O,p);}catch(v){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${v.message}; output replaced with placeholder`),b.setAttribute(P.TOOL_OK,false),f)throw new Ue("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let S=await Qn(p,{toolName:O,sandboxDir:f?void 0:Ye()});if(f){b.setAttribute(P.TOOL_OK,false);let v=typeof S=="string"?S:JSON.stringify(S);throw new Ue(v&&v!=="[]"?v:`MCP tool "${C.name}" reported an error with no content`)}return b.setAttribute(P.TOOL_OK,true),S}),"execute")}),E&&Z(l[O]),u.push({name:O,description:x,server:y,readOnly:E}),R.push(O),$++;}m.set(y,R),L>0?t("info",`[mcp] ${y}: ${$} tools mounted, ${L} skipped (length cap)`):t("info",`[mcp] ${y}: ${$} tools mounted`);},"mountServerTools"),h=s((y,k)=>Jn(k,()=>t("warn",`[mcp] ${y}: tools/list still paginating after ${Qt} pages; the rest is ignored`)),"listServerTools"),w=s(async(y,k)=>{g(y,k,await h(y,k));},"registerServerTools"),T=s(async(y,k)=>{let A=k.connectTimeoutMs??a.connectTimeoutMs,j=typeof A=="number"&&Number.isFinite(A)&&A>=0?A:Bn,R,$=false,L=K(y,k,C=>{R=C;},()=>$);try{return await(j>0?Vn(L,j,()=>{$=!0;}):L)}catch(C){R&&await R.close().catch(()=>{});let I=$?`connect timed out after ${j}ms`:C.message,O=!$&&C instanceof UnauthorizedError;return t("error",O?`[mcp] ${y}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${y}: failed to connect - ${I}`),{name:y,error:I,needsAuthorization:O}}},"openConnection"),K=s(async(y,k,A,j)=>{let R,$=s(async()=>{if(j())throw await R?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let L;if(Kn(k)){let I=k.env?{...getDefaultEnvironment(),...k.env}:void 0;L=new StdioClientTransport({command:k.command,args:k.args,env:I,cwd:k.cwd});}else if(Hn(k)){if(k.headers&&k.getHeaders)throw new Error(`MCP server "${y}": specify either headers or getHeaders, not both`);let I=k.getHeaders?await k.getHeaders():k.headers;k.authProvider&&(I&&"Authorization"in I&&t("warn",`[mcp] ${y}: an explicit Authorization header shadows the OAuth token from authProvider`),ut(k.url,`MCP server "${y}"`),await Yn(k.authProvider,k.url,k.fetch,t,y)),L=new StreamableHTTPClientTransport(new URL$1(k.url),{requestInit:I?{headers:I}:void 0,authProvider:k.authProvider,fetch:k.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${y}": config must specify either { url } (HTTP) or { command } (stdio)`);L.onerror=I=>t("warn",`[mcp] ${y}: transport error - ${I.message}`),L.onclose=()=>t("warn",`[mcp] ${y}: transport closed`),await $(),R=new Client({name:o,version:Wn}),A(R),await R.connect(L),await $(),r&&R.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(y);});let C=await h(y,R);return await $(),{name:y,client:R,listed:C}}catch(L){throw R&&await R.close().catch(()=>{}),L}},"connectOnce"),D=await Promise.all(Object.entries(e).map(([y,k])=>T(y,k)));for(let y of D){if(!y.client||!y.listed){d.push({name:y.name,connected:false,error:y.error,...y.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(y.name,y.client),g(y.name,y.client,y.listed),d.push({name:y.name,connected:true});}return {tools:l,catalog:u,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(y=>y.close()));},"close"),refreshServer:s(async y=>{let k=c.get(y);if(!k)throw new Error(`MCP server "${y}" is not connected`);await w(y,k);},"refreshServer")}},"connectMcpServers"),Vn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(a=>{clearTimeout(i),n(a);},a=>{clearTimeout(i),r(a);});}),"withConnectTimeout"),Xt={image:".bin",audio:".bin",resource:".bin"},Xn=s((e,t)=>{if(!e)return Xt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?Xt[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"),Zn=/[^a-zA-Z0-9_-]/g,Zt=s(async(e,t,o,n,r,i)=>{await i();let a=Xn(t,o),c=n.replace(Zn,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),u=le.join(r,`${o}-${c}-${l}${a}`),d=Buffer.from(e,"base64");return await writeFile(u,d),{type:"file",kind:o,path:u,mimeType:t,bytes:d.byteLength}},"spillBase64"),Qn=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(u=>u?.type==="text"&&typeof u.text=="string"))return o.map(u=>u.text).join(`
|
|
13
|
+
`);let r=t?.sandboxDir,i=t?.toolName??"tool",a,c=s(()=>r?(a||(a=mkdir(r,{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(r&&(u?.type==="image"||u?.type==="audio")&&typeof u.data=="string"){let d=await Zt(u.data,typeof u.mimeType=="string"?u.mimeType:void 0,u.type,i,r,c);l.push(d);continue}if(r&&u?.type==="resource"&&u.resource&&typeof u.resource=="object"){let d=u.resource;if(typeof d.blob=="string"){let m=await Zt(d.blob,typeof d.mimeType=="string"?d.mimeType:void 0,"resource",i,r,c);typeof d.uri=="string"&&(m.uri=d.uri),l.push(m);continue}if(typeof d.text=="string"){l.push(d.text);continue}}l.push(u);}return l},"flattenContent"),mt=s((e,t,o,n,r)=>{let i=o?.length?new Set(o.map(Ae)):null,a=n?.length?new Set(n.map(Ae)):null,c=new Set,l={},u=[];for(let d of t){if((i?.has(d.name)||a?.has(d.name))&&c.add(d.name),i&&!i.has(d.name)||!i&&a?.has(d.name))continue;let m=e[d.name];m&&(l[d.name]=m,u.push(d));}if(r)for(let[d,m]of [["availableTools",o],["excludedTools",n]])for(let g of m??[])c.has(Ae(g))||r("warn",`[mcp] ${d}: "${g}" matches no discovered tool`);return {tools:l,catalog:u}},"filterTools");var _e=s((e,t,o,n)=>{let r=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(er.has(r)&&!a)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:a,apiKey:i,model:c,providerOptions:l}},"resolveStage"),er=new Set(["openai-compatible","azure"]),Q={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"},ee=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"),Ne=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await ee(Q.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await ee(Q.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 ee(Q["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await ee(Q.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await ee(Q.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 ee(Q.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await ee(Q["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await ee(Q["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await ee(Q.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,...a}=o;if(!r&&!("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 ee(Q.cloudflare),l="binding"in a?a:{accountId:r,apiKey:t.apiKey,...a};return c(l)(t.model)}}},"buildModelFromStage");var to=new WeakMap,oo=s(e=>{if(!e)return;let t=to.get(e);if(!t)throw new TypeError("`control` must be created with createRunControl()");return t},"portOf"),tr=s(()=>{let e=0,t=[],o,n=false,r=new Map,i={send(a){let c=typeof a=="string"?a.trim():"";if(!c||n)return false;let l={id:`msg-${e+=1}`,text:c};return t.push(l),o?.({type:"message.queued",id:l.id,text:l.text}),true},pending:s(()=>t.map(a=>a.text),"pending"),subagents:s(()=>[...r.values()].map(a=>a.info).sort((a,c)=>a.startedAt-c.startedAt),"subagents"),stopSubagent(a){let c=r.get(a);return c?(c.stop(),true):false}};return to.set(i,{attach(a){n&&(t=[],r.clear()),o=a,n=false;for(let c of t)a({type:"message.queued",id:c.id,text:c.text});},detach(){return o=void 0,n=true,r.clear(),t.map(a=>a.text)},drain(){let a=t;return t=[],a},registerSubagent(a,c){return r.set(a.id,{info:a,stop:c}),()=>{r.delete(a.id);}}}),i},"createRunControl");var or=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"),nr=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),no=s(e=>{try{return ae(JSON.stringify(e))}catch{return 0}},"estimate"),gt=s((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,r=s(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:nr(l.toolName)}}:l)}:a),"apply");return i=>{let a=r(i),c=no(a);if(c<=e.triggerTokens)return a;let l=or(i),u=0;for(let m of l.slice(0,Math.max(0,l.length-o)))n.has(m)||(n.add(m),u+=1);if(u===0)return a;let d=r(i);return t?.({cleared:u,beforeTokens:c,afterTokens:no(d)}),d}},"createToolResultClearer");var so=/^[a-z0-9-]{1,64}$/,sr="load_skill",ir="read_skill_file",ar=24e3,lo=s(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=le.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"),ft=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"||!so.test(t))throw new Error(`skill name must match ${so} (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,a=(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 l;try{l=lo(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"),lr=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"),cr=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 a=i[1],c=i[2].trim(),l=/^([>|])([+-]?)\s*(#.*)?$/.exec(c);if(l){let u=[];for(;n+1<o.length&&(/^\s/.test(o[n+1])||o[n+1].trim()==="");)u.push(o[++n]);for(;u.length&&u[u.length-1].trim()==="";)u.pop();let d=Math.min(...u.filter(g=>g.trim()).map(g=>/^\s*/.exec(g)[0].length)),m=u.map(g=>g.slice(Number.isFinite(d)?d:0));t[a]=l[1]==="|"?m.join(`
|
|
15
|
+
`):m.join(`
|
|
16
|
+
`).split(/\n\s*\n/).map(g=>g.replace(/\n/g," ").trim()).join(`
|
|
17
|
+
`);continue}t[a]=lr(c);}return t},"parseFrontmatter"),co=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=cr(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 ft({name:r.name,description:r.description,content:o.slice(n[0].length).trim(),...t?.length?{files:t}:{}})},"parseSkillMarkdown"),ur=new Set([".md",".txt",".json",".yaml",".yml",".csv",".ts",".js",".py",".sh",".html",".css",".xml",".toml"]),pr=256*1024,uo=s(async(e,t,o)=>{let n=await 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=le.join(t,r.name);if(r.isDirectory()){await uo(e,i,o);continue}if(!r.isFile())continue;let a=le.relative(e,i).split(le.sep).join("/");a==="SKILL.md"||!ur.has(le.extname(r.name).toLowerCase())||(await stat(i)).size>pr||o.push({path:a,content:await readFile(i,"utf8")});}},"collectFiles"),dr=s(async e=>{let t=await 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=le.join(e,r.name),a;try{a=await readFile(le.join(i,"SKILL.md"),"utf8");}catch{continue}let c=[];await uo(i,i,c);let l;try{l=co(a,c);}catch(u){throw new Error(`${le.join(i,"SKILL.md")}: ${u.message}`)}if(n.has(l.name))throw new Error(`duplicate skill name "${l.name}" in ${e}`);n.add(l.name),o.push(l);}return o},"loadSkillsFromDir"),po=s(e=>{let t=[],o=new Set;for(let n of e??[]){let r=ft(n);if(o.has(r.name))throw new Error(`duplicate skill name "${r.name}"`);o.add(r.name),t.push(r);}return t},"validateSkills"),mr=s((e,t)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}\u2026`:o},"oneLine"),ht=s(e=>e.map(t=>`- ${t.name}: ${mr(t.description,300)}`).join(`
|
|
19
|
+
`),"renderSkillsIndex"),mo=s((e,t,o=ar)=>{let n=new Map(e.map(a=>[a.name,a])),r=[],i=0;for(let a of t){let c=n.get(a);if(!c)continue;let l=`### Skill: ${c.name}
|
|
20
|
+
${c.content.trim()}`,u=o-i;if(u<=0){r.push(`### Skill: ${c.name}
|
|
21
|
+
\u2026 [skill instructions clipped: budget exhausted]`);continue}if(l.length>u){r.push(`${l.slice(0,u)}
|
|
22
|
+
\u2026 [skill instructions clipped]`),i=o;continue}r.push(l),i+=l.length;}return r.join(`
|
|
23
|
+
|
|
24
|
+
`)},"renderActiveSkills"),yt=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"),go=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 {[sr]:Z(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:s(async({name:n})=>{let r=o(n),i=W.getStore();return yt(e,r.name,"tool",i?.state,i?.emit),{name:r.name,content:r.content,files:(r.files??[]).map(a=>a.path)}},"execute")})),[ir]:Z(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:s(async({name:n,path:r})=>{let i=o(n),a;try{a=lo(r);}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 "${r}". Files: ${l.length?l.join(", "):"(none)"}`)}return c.content},"execute")}))}},"createSkillTools");var oe="find_tools",fr=40,hr=8,yr=20,je=s((e,t)=>{let o=e.toolSelectionStrategy??"auto";if(o==="auto"){let n=e.toolSearchThreshold??fr;return t>n?"search":"all"}return o},"resolveToolStrategy"),ze=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"),Tt=s((e,t)=>e.some(o=>o===t||t.length>=3&&o.startsWith(t)),"hit"),ho=s((e,t,o={})=>{let n=[...new Set(ze(t))];if(n.length===0)return [];let r=Math.floor(o.limit??hr),i=Math.min(yr,Math.max(1,Number.isFinite(r)?r:8)),a=o.server?.trim().toLowerCase(),c=[];return e.forEach((l,u)=>{if(a&&(l.server??"").toLowerCase()!==a)return;let d=ze(l.name),m=ze(l.server??""),g=ze(l.description??""),h=0;for(let w of n)h+=(Tt(d,w)?3:0)+(Tt(m,w)?2:0)+(Tt(g,w)?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"),Tr=12e3,kr=60,yo=s((e,t=Tr)=>{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=[],r=0,i=0;e:for(let[c,l]of o){let u=`[${c}]`;if(r+u.length+1>t)break;n.push(u),r+=u.length+1;for(let d of l){let m=(d.description||"").replace(/\s+/g," ").trim().slice(0,kr),g=`- ${d.name}: ${m}`;if(r+g.length+1>t)break e;n.push(g),r+=g.length+1,i++;}}let a=e.length-i;return a>0&&n.push(`\u2026 ${a} more tools \u2014 the executor can find them with ${oe}`),n.join(`
|
|
25
|
+
`)},"renderSearchCatalog"),To=s(e=>({[oe]:Z(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:s(async({query:t,server:o,limit:n})=>{let r=ho(e(),t,{server:o,limit:n}),i=r.map(l=>l.name),a=W.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:r.map(l=>({name:l.name,description:l.description,server:l.server??"<native>",readOnly:l.readOnly===true}))}},"execute")}))}),"createFindToolsTool");var ko=1500,wo=6e3,wt=s(e=>{if(!e?.length)return "(no prior conversation)";let t=at(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 a=t.content.length>wo?`${t.content.slice(0,wo)}... [truncated]`:t.content;i.push(`${t.role}: ${a}`);}r>0&&i.push(`(${r} earlier turns omitted)`);for(let a of n){let c=a.content.length>ko?`${a.content.slice(0,ko)}... [truncated]`:a.content;i.push(`${a.role}: ${c}`);}return i.join(`
|
|
26
|
+
`)},"renderHistory"),br={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},vr=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:n}=br[t],r=e.slice(0,o),i=e.length-r.length,a=r.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(`
|
|
27
|
+
`)},"renderToolCatalog"),bo=s((e,t)=>t==="search"?yo(e):vr(e,t),"renderCatalogFor"),kt=1500,Sr=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>kt?`${t.slice(0,kt)}... [truncated, ${t.length-kt} chars]`:t},"truncateOutput"),Ir=s((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(n=>` - ${n.name} ${n.ok?"ok":"fail"}: ${Sr(n.output)}`).join(`
|
|
28
28
|
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
|
|
29
|
-
`)},"renderTraceEntry"),
|
|
30
|
-
`),"renderTraceSteps"),
|
|
31
|
-
`)},"renderTrace"),
|
|
29
|
+
`)},"renderTraceEntry"),Fe=s((e,t=0)=>e.map((o,n)=>Ir(o,t+n)).join(`
|
|
30
|
+
`),"renderTraceSteps"),he=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 Fe(e);let n=[`Summary of earlier steps (1-${o}): ${t.summary}`];return o<e.length&&n.push(Fe(e.slice(o),o)),n.join(`
|
|
31
|
+
`)},"renderTrace"),bt=s(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
|
|
32
32
|
expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
|
|
33
33
|
suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
|
|
34
|
-
`),"renderPlan"),
|
|
34
|
+
`),"renderPlan"),Ke=s((e,t)=>t?`${e}
|
|
35
35
|
|
|
36
36
|
Domain context:
|
|
37
|
-
${t}`:e,"withDomainContext"),
|
|
37
|
+
${t}`:e,"withDomainContext"),He=8,vo=s(e=>`You are the Planner of a multi-step agent system.
|
|
38
38
|
|
|
39
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.
|
|
40
40
|
|
|
@@ -45,50 +45,58 @@ Rules:
|
|
|
45
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.
|
|
46
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).
|
|
47
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");
|
|
48
|
+
7. Output strict JSON matching the requested schema. No prose outside JSON.`,"plannerBase");vo(He);var Ar=`
|
|
49
49
|
|
|
50
50
|
ADDITIONAL RULE (tool-narrowed mode):
|
|
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.`,
|
|
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.`,xr=`
|
|
52
52
|
|
|
53
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 ${
|
|
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 ${oe}. Never invent names.`,Cr=`
|
|
55
55
|
|
|
56
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.`,
|
|
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.`,Or=s((e,t=He)=>vo(t)+(e==="compact"?Ar:e==="search"?xr:""),"buildPlannerSystem"),Rr=s(e=>e?.length?`
|
|
58
58
|
|
|
59
59
|
SKILLS:
|
|
60
|
-
${
|
|
60
|
+
${ht(e)}`:"","skillsIndexSection"),vt=s((e,t)=>{if(!e?.length||!t?.length)return "";let o=mo(e,t);return o?`
|
|
61
61
|
|
|
62
62
|
ACTIVE SKILLS (follow these instructions where they apply):
|
|
63
63
|
|
|
64
|
-
${o}`:""},"activeSkillsSection"),
|
|
64
|
+
${o}`:""},"activeSkillsSection"),So=s(e=>Ke(Or(e.mode,e.maxSteps)+(e.skills?.length?Cr:""),e.domain)+Rr(e.skills)+`
|
|
65
65
|
|
|
66
66
|
Available tools:
|
|
67
|
-
${
|
|
68
|
-
${
|
|
67
|
+
${bo(e.catalog,e.mode)}`,"composePlannerSystem"),Io=s((e,t)=>[t?.length?`Conversation history:
|
|
68
|
+
${wt(t)}
|
|
69
69
|
`:"",`User request:
|
|
70
70
|
${e}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
71
|
-
`),"buildPlannerUserPrompt"),
|
|
71
|
+
`),"buildPlannerUserPrompt"),Er=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
|
|
72
72
|
|
|
73
73
|
Rules:
|
|
74
74
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
75
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.
|
|
76
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.
|
|
77
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.
|
|
78
|
-
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,
|
|
78
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,Pr=`
|
|
79
79
|
|
|
80
80
|
TOOLS:
|
|
81
|
-
Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${
|
|
81
|
+
Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${oe} with a few keywords; the matching tools become callable from your next step on.`,Mr=`
|
|
82
82
|
|
|
83
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.`,
|
|
85
|
-
${
|
|
86
|
-
|
|
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.`,Ao=s(e=>Ke(Er,e.domain)+(e.skills?.length?`${Mr}
|
|
85
|
+
${ht(e.skills)}`:"")+(e.searchMode?`${Pr}${e.toolCount?` The catalogue has ${e.toolCount} tools.`:""}`:"")+vt(e.skills,e.activeSkills),"composeExecutorSystem"),xo=s(e=>e.trim().replace(/\n/g,`
|
|
86
|
+
`),"quoted"),St=s((e,t=0,o="")=>{if(!e||e.length===0)return "";let n=t>0?e.length-t:e.length,i=`Messages from the user, sent while the agent was working (oldest first; they speak for the user and win over the original request where they conflict):
|
|
87
|
+
${e.map((a,c)=>`${c+1}. ${xo(a)}${c>=n?" [NEW - not yet reflected in the plan]":""}`).join(`
|
|
88
|
+
`)}`;return o?`${i}
|
|
89
|
+
${o}`:i},"renderUserUpdates"),$r='Weigh the [NEW] messages against the remaining plan: "revise" the remaining steps so they are honoured (and keep honouring the older ones), "finish" if the user says to stop or the request is already met, "continue" only if the remaining steps already fit them.',Lr="Answer with these in mind: they changed what was asked. Say plainly if one of them could not be honoured in time.",Co=s(e=>`NEW MESSAGE FROM THE USER, sent while you were working:
|
|
90
|
+
${e.map(t=>`- ${xo(t)}`).join(`
|
|
91
|
+
`)}
|
|
92
|
+
It speaks for the user and wins over the request and the plan where they conflict. Take it into account from here on, then carry on with this step - or finish the step now if the message makes the rest of it pointless.`,"renderUserMessages"),Oo=s((e,t,o,n,r,i,a)=>[r?.length?`Conversation history:
|
|
93
|
+
${wt(r)}
|
|
87
94
|
`:"",`Original user request:
|
|
88
|
-
${e}`,
|
|
89
|
-
${
|
|
90
|
-
${
|
|
91
|
-
|
|
95
|
+
${e}`,a?.length?`
|
|
96
|
+
${St(a)}`:"","",`Overall plan:
|
|
97
|
+
${bt(t)}`,"",`Trace so far:
|
|
98
|
+
${he(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(`
|
|
99
|
+
`),"buildExecutorUserPrompt"),Ur=`You are the Replanner of an autonomous multi-step agent system. After an Executor step you decide what should happen next.
|
|
92
100
|
|
|
93
101
|
You have three options:
|
|
94
102
|
- "continue": the next planned step is still appropriate.
|
|
@@ -101,14 +109,15 @@ Rules:
|
|
|
101
109
|
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
110
|
4. Never revise into a step that asks the user for input, clarification or permission - the agent runs autonomously.
|
|
103
111
|
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.`,
|
|
112
|
+
6. Output strict JSON matching the schema. No prose outside JSON.`,Ro=s(e=>Ke(Ur,e.domain)+`
|
|
105
113
|
|
|
106
114
|
Available tools (for the revise option):
|
|
107
|
-
${
|
|
108
|
-
${e}`,
|
|
109
|
-
${
|
|
110
|
-
${
|
|
111
|
-
|
|
115
|
+
${bo(e.catalog,e.mode)}`+vt(e.skills,e.activeSkills),"composeReplannerSystem"),Eo=s((e,t,o,n,r,i,a=0)=>[`Original user request:
|
|
116
|
+
${e}`,i?.length?`
|
|
117
|
+
${St(i,a,$r)}`:"","",`Current plan:
|
|
118
|
+
${bt(t)}`,"",`Completed steps:
|
|
119
|
+
${he(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(`
|
|
120
|
+
`),"buildReplannerUserPrompt"),_r=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
112
121
|
|
|
113
122
|
Rules:
|
|
114
123
|
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.
|
|
@@ -116,10 +125,15 @@ Rules:
|
|
|
116
125
|
3. Mention the assumptions the agent made, briefly.
|
|
117
126
|
4. If the trace shows the request (or part of it) could not be completed, say so plainly and explain what blocked it.
|
|
118
127
|
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.`,
|
|
120
|
-
${
|
|
128
|
+
6. Use the user's language.`,Po=s(e=>Ke(_r,e.domain)+vt(e.skills,e.activeSkills),"composeSynthesizerSystem"),Mo=s((e,t,o,n,r,i)=>[n?.length?`Conversation history:
|
|
129
|
+
${wt(n)}
|
|
121
130
|
`:"",`User request:
|
|
122
|
-
${e}`,
|
|
123
|
-
${
|
|
124
|
-
${
|
|
125
|
-
`),"buildSynthesizerUserPrompt");var xr=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")}),Or=Fe,wt=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(xr).min(1),skills:z.array(z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),Ke=s(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):Or},"planStepCap"),fe=s(e=>{if(e.run)return e.run.strategy;let t=De(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"effectiveToolStrategy"),bt=s(e=>e==="plan-narrowed"?"compact":e==="search"?"search":"full","catalogModeFor"),vt=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"),Io=s(async(e,t,o,n)=>G("agent.plan",{[E.PHASE]:"plan"},async r=>{let i=new Set(o.toolCatalog.map(u=>u.name)),l=bt(fe(o)),c=Ke(o),{object:a,usage:p}=await oe(()=>Cr(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=vt(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"),Cr=s(async(e,t,o,n,r)=>{let i=re(n.config,"planner",ho({mode:o,catalog:n.toolCatalog,maxSteps:Ke(n),domain:n.config.systemPrompt,skills:n.skills})),l=streamObject({model:n.plannerModel,schema:wt,...i,prompt:yo(e,t),abortSignal:Y(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 H={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(M=>typeof M=="string"):void 0};n.emit({type:"plan.step-added",step:H,index:p}),p++;}}let[d,f]=await Promise.all([l.object,l.usage]);return {object:d,usage:j(f)}},"streamPlanOnce");var Pr=s((e,t)=>{if(fe(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"),Ao="[BLOCKER]",Mr=s(e=>e.includes(Ao)?{summary:e.split(Ao).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),St=4e3,Lr=s(e=>e.length>St?`${e.slice(0,St)}... [truncated, ${e.length-St} chars]`:e,"truncateForTrace"),xo=s(async(e,t,o,n,r,i,l)=>G("agent.execute_step",{[E.PHASE]:"execute",[E.STEP_ID]:o.id},async c=>{let a=Date.now(),p=await oe(()=>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=fe(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 z=i.config.inputSanitizer;if(!z)return P;try{return await z(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=[stepCountIs(i.config.maxStepsPerTask)],H=ne(i.config);u&&Ut(H)&&x.push(_t(()=>u.usage,H,()=>{T="tokens";}));let M=i.config.maxToolCalls;u&&typeof M=="number"&&M>0&&x.push(()=>u.toolCalls>=M?(T??="tool-calls",true):false);let g=re(i.config,"executor",To({domain:i.config.systemPrompt,skills:i.skills,activeSkills:u?.activeSkills,searchMode:!!f,toolCount:i.toolCatalog.length})),b=Re(i.config,"executor"),C=u?{summary:u.traceSummary,upTo:u.traceSummaryUpTo}:void 0,W=ye(i.config.promptCaching),L=de(i.config.compaction),N=L.clearToolResultsAfterTokens>0?ut({triggerTokens:L.clearToolResultsAfterTokens,keep:L.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=W.enabled||!!N,I=streamText({model:i.executorModel,tools:p,...d?{activeTools:d}:{},...f||R?{prepareStep:s(({messages:k})=>{let P=Ye(N?N(k):k,W);return {...f?{activeTools:[...f].filter(z=>z in p)}:{},...R?{messages:P}:{}}},"prepareStep")}:{},stopWhen:x,...g,prompt:ko(e,t,o,n,r,C),abortSignal:Y(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 z=a.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:z,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 z=a.get(k.toolCallId)?.input??await h(k.toolName,k.input);c.push({name:k.toolName,input:z,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,O]=await Promise.all([I.text,I.usage]),{summary:$,blocked:q}=Mr(v.trim());return {summary:$.length>0?Lr($):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:q,usage:O?j(O):ce()}},"runOnce");var Nr=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:wt.describe("Plan covering ONLY the remaining work")})]),Oo=s(async(e,t,o,n,r,i)=>G("agent.replan",{[E.PHASE]:"replan"},async l=>{let c=bt(fe(r)),a=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,{object:p,usage:d}=await oe(async()=>{let f=re(r.config,"replanner",wo({mode:c,catalog:r.toolCatalog,domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),u=await generateObject({model:r.plannerModel,schema:Nr,...f,prompt:bo(e,t,o,n,a),abortSignal:Y(i,r.config.llmTimeoutMs??0)}),h=j(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)=>G("agent.synthesize",{[E.PHASE]:"synthesize"},async l=>{let{text:c,usage:a}=await oe(()=>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=re(r.config,"synthesizer",vo({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=Re(r.config,"synthesizer"),p=streamText({model:r.synthesizerModel,...l,prompt:So(e,t,o,n,c),abortSignal:Y(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:j(f)}},"streamOnce");var Eo=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 Eo(t);let n=s(()=>Eo(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"),He=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Wr=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||ae.join(tmpdir(),"agent-sandbox");return ae.join(o,t)},"resolveSandboxDir"),Po=/^[a-zA-Z0-9_-]{1,128}$/,It=s((e,t)=>{if(!Po.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Po}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),qr=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(It(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(It(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"),Mo=s(async(e,t)=>{let o=await qr(e,t),n=o?.runId??randomUUID();It(n,"runId");let r=o?.startedAt??Date.now(),i=Wr(e,n);return K.run({runId:n,startedAt:r,sandboxDir:i},async()=>G("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 rm(i,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Br=s(e=>{let t=De(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=de(e.config.compaction),a=ne(e.config),p=e.config.maxToolCalls,d=j(o?.usage),f=K.getStore()?.startedAt??Date.now(),u=K.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"&&$t(d,w.usage);let m={...w,runId:K.getStore()?.runId};try{l(m);}catch{}try{e.emit(m);}catch{}},"emit")},x=K.getStore();x&&(x.emit=T.emit,x.state=h);let H=s((w,m)=>{gt(e.skills??[],w,m,h,T.emit);},"activate"),M=e.config.persistence,g=s(async(w,m)=>{let y=M?.[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 ve(i,e.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:be(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 C=s(async w=>{if(!c.auto||n?.aborted)return;let m=s(()=>({summary:h.traceSummary,upTo:h.traceSummaryUpTo}),"view"),y=ie(ge(w,m()));if(y<=c.thresholdTokens)return;let A=w.length-c.keepRecentSteps,S=h.traceSummary?h.traceSummaryUpTo:0;if(A<=S)return;let F=await Kt(w.slice(S,A),h.traceSummary,e.synthesizerModel,{summaryMaxTokens:be(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,render:ze,offset:S});F&&(T.emit({type:"usage",phase:"compact",usage:F.usage}),h.traceSummary=F.summary,h.traceSummaryUpTo=A,T.emit({type:"context.compacted",scope:"trace",beforeTokens:y,afterTokens:ie(ge(w,m()))}));},"maybeCompactTrace"),W=false,L=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"),N=s(()=>{let w=L();return w?(W||(W=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 Io(r,i,T,n);}catch(w){if(T.emit({type:"error",error:Ae(w),phase:"plan"}),He(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??[])H(w,"plan");}let I=o?[...o.trace]:[],v=R,O=o?.stepIndex??0,$=o?.iterations??0,q=o?.revisions??0,B=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:O,iterations:$,revisions:q,...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(;$<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(O>=v.steps.length||N())break;$++;let w=v.steps[O];x&&(x.currentStep=w),T.emit({type:"step.start",step:w,index:O});let m=new AbortController;if(t.onStepStart)try{t.onStepStart({step:w,index:O,abort:s(()=>m.abort(),"abort")});}catch(D){T.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${D.message}`});}let y=Ve([n,m.signal]),A;try{await C(I),A=await xo(r,v,w,I,i,T,y);}catch(D){if(n?.aborted)throw T.emit({type:"error",error:Ae(D),phase:"execute"}),await g("onRunComplete",k("cancelled",{error:D.message,completedAt:Date.now()})),D;if(m.signal.aborted&&He(D))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:Ae(D),phase:"execute"}),await g("onRunComplete",k("failed",{error:D.message,completedAt:Date.now()})),D}if(I.push(A),T.emit({type:"step.complete",step:w,result:A}),N()){O++;break}let S=v.steps[O+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(D=>T.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${D.message}`}),"onError")})){T.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),O++,await P();continue}let J;try{await C(I),J=await Oo(r,v,I,S,T,n);}catch(D){throw T.emit({type:"error",error:Ae(D),phase:"replan"}),await g("onRunComplete",k(He(D)||n?.aborted?"cancelled":"failed",{error:D.message,completedAt:Date.now()})),D}if(T.emit({type:"replan.decision",mode:J.mode,reason:J.reason,cause:"llm-decision"}),J.mode==="finish")break;if(J.mode==="revise"){if(q>=B){T.emit({type:"revisions.exceeded",cap:B});break}q++,v=Gr(T,J.newPlan),T.emit({type:"plan.revised",plan:v,reason:J.reason});for(let D of v.skills??[])H(D,"plan");O=0,await P();continue}O++,await P();}let z;try{await C(I),z=await Co(r,v,I,i,T,n);}catch(w){throw T.emit({type:"error",error:Ae(w),phase:"synthesize"}),await g("onRunComplete",k(He(w)||n?.aborted?"cancelled":"failed",{error:w.message,completedAt:Date.now()})),w}return T.emit({type:"final",text:z}),await g("onRunComplete",k("complete",{text:z,completedAt:Date.now()})),{text:z,plan:v,trace:I,iterations:$,usage:d,...b?{compactedHistory:b}:{}}},"runAgentLoopInner"),Gr=s((e,t)=>{let o=Ke(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=vt(e,t.skills),{skills:r,...i}=t;return {...i,steps:t.steps.slice(0,o),...n?{skills:n}:{}}},"reviseInto"),Ae=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var Lo=Symbol.for("@dudko.dev/agent:wrapped-tool"),We=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=K.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new We(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[Lo])return t;let r=le(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=st({...t,...a?{execute:a}:{}},o.maxToolOutputChars);return Object.defineProperty(p,Lo,{value:true,enumerable:false}),p},"wrapTool"),xe=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 qe={none:0,error:1,warn:2,info:3,debug:4},At=s(async(e,t)=>{let o=qe[e.logLevel]>=qe.debug,n=s(m=>{if(t)try{t(m);}catch(y){o&&console.error("[agent] event handler threw:",y);}},"emit"),r=s((m,y)=>{qe[e.logLevel]>=qe[m]&&n({type:"log",level:m,message:y});},"log"),i=ro(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=Pt(e.toolApproval,{sanitize:l,fallbackEmit:n}),a=de(e.compaction),p={approval:c,maxToolCalls:e.maxToolCalls,maxToolOutputChars:a.maxToolOutputChars},d=xe(io(i),p,{builtIn:true}),f=e.toolSelectionStrategy??"auto",u=f==="search"||f==="auto",h=false,T=s(()=>[],"catalogRef"),x=u?xe(po(()=>T()),p,{builtIn:true}):void 0,H=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[te]){if(f==="search")throw new Error(`Tool "${te}" collides with the built-in tool-search tool of the same name`);h||(h=true,r("warn",`[tools] a tool named "${te}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),M,g=s((m,y)=>{if(!e.tools)return m;let A=[];for(let[S,F]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]=F;let ue=typeof F=="object"&&F&&"description"in F?F.description:"";A.push({name:S,description:typeof ue=="string"?ue:"",server:"<native>",readOnly:le(F)});}return {tools:m.tools,catalog:[...m.catalog,...A]}},"mergeNativeTools"),b=s(async()=>{let m=await Yt(e.mcpServers,r,e.clientName,e.outputSanitizer,S=>M?.(S),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),y=pt(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`)}),H(A.tools);}catch(S){throw m.close().catch(()=>{}),S}return {connection:m,tools:xe(A.tools,p),catalog:A.catalog}},"connect"),C;try{C=await b();}catch(m){throw n({type:"error",error:m instanceof Error?m:new Error(String(m)),phase:"init"}),m}let W=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&W>0&&!C.connection.results.some(y=>y.connected)){let y=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 ${W} configured MCP server(s) failed to connect [${y}]`);throw n({type:"error",error:A,phase:"init"}),A}let L,N,R;try{let m=$e(e,void 0,void 0,"executor"),y=$e(e,e.planner,e.plannerModel,"planner"),A=$e(e,e.synthesizer,e.synthesizerModel,"synthesizer");[L,N,R]=await Promise.all([Ue(e.clientName,m),Ue(e.clientName,y),Ue(e.clientName,A)]);}catch(m){throw await C.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:L,plannerModel:N,synthesizerModel:R,tools:C.tools,toolCatalog:I(C.catalog),emit:n,...Object.keys(d).length?{builtinTools:d}:{},...i.length?{skills:i}:{},approval:c};T=s(()=>v.toolCatalog,"catalogRef");let O=s(()=>{x&&!h?v.findTools=x:delete v.findTools;},"syncFindTools");O();let $=0,q=false,B=false,k=false,P=new Set,z=s(async m=>{await C.connection.refreshServer(m);let y=pt(C.connection.tools,C.connection.catalog,e.availableTools,e.excludedTools),A=g(y,F=>{throw new Error(`Native tool "${F}" collides with an MCP-registered tool of the same name`)});H(A.tools);let S=xe(A.tools,p);for(let F of Object.keys(v.tools))delete v.tools[F];Object.assign(v.tools,S),v.toolCatalog=I(A.catalog),O(),r("info",`[mcp] ${m}: tool list refreshed (${A.catalog.length} tools total after filter)`);},"applyRefresh"),w=s(async()=>{if(!(k||q||B)&&!($>0||P.size===0)){k=true;try{for(;P.size>0&&$===0&&!q&&!B;){let m=P.values().next().value;P.delete(m);try{await z(m);}catch(y){r("warn",`[mcp] ${m}: refresh failed - ${y.message}`);}}}finally{k=false;}}},"drainPendingRefreshes");return M=s(m=>{P.add(m),w();},"onToolsChanged"),{run:s(async m=>{if(q)throw new Error("Agent is closed");if(B)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&&$>=y)throw new Error(`maxConcurrentRuns reached (${$}/${y}); rate-limit on the caller side or raise the cap`);$++;try{return await Mo(v,m)}finally{$--,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 ve(m.history,v.synthesizerModel,{thresholdTokens:a.thresholdTokens,keepRecentTurns:a.keepRecentTurns,summaryMaxTokens:be(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(q)throw new Error("Agent is closed");if(B)throw new Error("Already reconnecting");if(k)throw new Error("Agent is refreshing tools; retry shortly");if($>0)throw new Error(`Cannot reconnect with ${$} active run(s)`);B=true;try{let m=C.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),O(),C=y,await m.close().catch(()=>{});}finally{B=false;}},"reconnect"),close:s(async m=>{q=true;let y=m?.waitForRuns??false,A=m?.timeoutMs??3e4,S=Date.now()+A;if(y&&$>0)for(;$>0&&Date.now()<S;)await new Promise(D=>setTimeout(D,50));$>0&&n({type:"log",level:"warn",message:`[agent] close called with ${$} active run(s); they will fail mid-flight`});let F=Math.max(S-Date.now(),0),ue=false,J;await Promise.race([C.connection.close().catch(()=>{}),new Promise(D=>{J=setTimeout(()=>{ue=true,D();},F),J.unref?.();})]),J&&clearTimeout(J),ue&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${F}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>$,"activeRuns")}},"createAgent");var ns=8e3,rs=4,ss=4e3,Uo=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 Uo(e)}},"toCloneable"),xt=s((e,t=0)=>{if(typeof e=="string")return pe(e,ss);if(e instanceof Error||!e||typeof e!="object"||t>8)return e;if(Array.isArray(e))return e.map(n=>xt(n,t+1));let o={};for(let[n,r]of Object.entries(e))o[n]=xt(r,t+1);return o},"clipStrings"),as=s(e=>xt(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=import.meta.url;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:Uo(await l)}}catch(i){return {ok:false,output:Xe(i)}}},"runHostTool"),ms=s(e=>Object.entries(e).map(([t,o])=>({name:t,description:typeof o.description=="string"?o.description:"",inputSchema:asSchema(o.inputSchema).jsonSchema,...le(o)?{readOnly:true}:{}})),"describeTools"),gs=s(async(e,t,o,n)=>{let r={...e.config.tools??{},...e.tools??{}},i=await At({...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(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=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=tool({description:e.description,inputSchema:z.object({task: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=K.getStore()?.emit??(()=>{}),p=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=ce(),H=s(M=>{if(M.type==="usage"){let g=j(M.usage);a({type:"usage",phase:"subagent",usage:g});}a({type:"subagent.event",id:p,name:d,event:as(M)});},"onChildEvent");try{a({type:"subagent.start",id:p,name:d,task:i});let M=t==="worker"?await fs(e,i,f.signal,H):await gs(e,i,f.signal,H);x=j(M.usage);let g=pe(M.text,o);return a({type:"subagent.complete",id:p,name:d,text:g,usage:x}),g}catch(M){let g=h?`subagent "${d}" timed out after ${e.timeoutMs}ms`:Xe(M);throw a({type:"subagent.error",id:p,name:d,error:g}),h?new Error(g):M}finally{T&&clearTimeout(T),l?.removeEventListener("abort",u),n.release();}},"execute")});return X(r,e.readOnly===true)},"createSubagentTool");export{Pe as FileOAuthStore,it as MemoryOAuthStore,Me as NodeOAuthProvider,nt as SUMMARY_PREFIX,We as ToolBudgetError,he as ToolDeniedError,ke as addUsage,dn as beginMcpOAuth,Ge as buildInstructions,Ce as checkLimits,ve as compactHistory,At as createAgent,un as createNodeOAuthProvider,hs as createSubagentTool,ut as createToolResultClearer,Et as decideToolPermission,dt as defineSkill,ie as estimateTokens,mn as finishMcpOAuth,Do as getCurrentRunId,Be as getCurrentRunSandbox,le as isReadOnlyTool,or as loadSkillsFromDir,X as markReadOnly,Rt as matchToolRule,tt as mergeProviderOptions,j as normalizeUsage,oo as parseSkillMarkdown,Bo as redactHeaders,ne as resolveLimits,ye as resolvePromptCaching,Qe as resolveThinking,lo as searchTools,Ht as truncateToolModelOutput,Ye as withRollingBreakpoint,st as withToolOutputLimit};
|
|
131
|
+
${e}`,i?.length?`
|
|
132
|
+
${St(i,0,Lr)}`:"","",`Plan that was executed:
|
|
133
|
+
${bt(t)}`,"",`Execution trace:
|
|
134
|
+
${he(o,r)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
135
|
+
`),"buildSynthesizerUserPrompt");var Dr=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")}),zr=He,It=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(Dr).min(1),skills:z.array(z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),We=s(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):zr},"planStepCap"),ye=s(e=>{if(e.run)return e.run.strategy;let t=je(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"effectiveToolStrategy"),At=s(e=>e==="plan-narrowed"?"compact":e==="search"?"search":"full","catalogModeFor"),xt=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"),$o=s(async(e,t,o,n)=>Y("agent.plan",{[P.PHASE]:"plan"},async r=>{let i=new Set(o.toolCatalog.map(g=>g.name)),a=At(ye(o)),c=We(o),{object:l,usage:u}=await ne(()=>jr(e,t,a,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((g,h)=>o.emit({type:"retry",phase:"plan",attempt:g,error:h.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:u}),r.setAttribute(P.USAGE_TOTAL_TOKENS,u.totalTokens);let d=l.steps.slice(0,c);d.length<l.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${l.steps.length} steps; truncated to hard cap ${c}`});let m=xt(o,l.skills);return {thought:l.thought,...m?{skills:m}:{},steps:d.map(g=>{if(!g.suggestedTools?.length)return g;let h=g.suggestedTools.filter(T=>i.has(T)),w=g.suggestedTools.length-h.length;return w>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${g.id}" had ${w} unknown suggestedTools, stripped`}),h.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${g.id}" had no valid suggestedTools left; falling back to full toolset`}),{...g,suggestedTools:void 0,requiresTools:true}):{...g,suggestedTools:h}})}}),"createInitialPlan"),jr=s(async(e,t,o,n,r)=>{let i=se(n.config,"planner",So({mode:o,catalog:n.toolCatalog,maxSteps:We(n),domain:n.config.systemPrompt,skills:n.skills})),a=streamObject({model:n.plannerModel,schema:It,...i,prompt:Io(e,t),abortSignal:V(r,n.config.llmTimeoutMs??0)}),c="",l=false,u=0;for await(let g of a.partialObjectStream){let h=g?.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 w=g?.steps;if(Array.isArray(w)&&w.length>u)for(;u<w.length;){let T=w[u];if(!T||typeof T.description!="string"||!T.description.length)break;let K={id:typeof T.id=="string"&&T.id?T.id:`s${u+1}`,description:T.description,expectedOutcome:typeof T.expectedOutcome=="string"?T.expectedOutcome:"",suggestedTools:Array.isArray(T.suggestedTools)?T.suggestedTools.filter(D=>typeof D=="string"):void 0};n.emit({type:"plan.step-added",step:K,index:u}),u++;}}let[d,m]=await Promise.all([a.object,a.usage]);return {object:d,usage:H(m)}},"streamPlanOnce");var Hr=s((e,t)=>{if(ye(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"),Lo="[BLOCKER]",Wr=s(e=>e.includes(Lo)?{summary:e.split(Lo).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),Ct=4e3,qr=s(e=>e.length>Ct?`${e.slice(0,Ct)}... [truncated, ${e.length-Ct} chars]`:e,"truncateForTrace"),Uo=s(async(e,t,o,n,r,i,a)=>Y("agent.execute_step",{[P.PHASE]:"execute",[P.STEP_ID]:o.id},async c=>{let l=Date.now(),u=await ne(()=>Jr(e,t,o,n,r,i,a),{maxRetries:i.config.llmMaxRetries??2,signal:a,onRetry:s((d,m)=>i.emit({type:"retry",phase:"execute",attempt:d,error:m.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:u.usage}),c.setAttribute(P.USAGE_TOTAL_TOKENS,u.usage.totalTokens),c.setAttribute(P.STEP_BLOCKED,u.blocked),c.setAttribute(P.TOOL_COUNT,u.toolCalls.length),{step:o,summary:u.summary,toolCalls:u.toolCalls,durationMs:Date.now()-l,blocked:u.blocked}}),"executeStep"),Br=s((e,t)=>{let o=ye(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 r=Hr(e,t),i=Object.keys(n).length?{...r,...n}:r;return o==="plan-narrowed"?{tools:i,activeTools:Object.keys(i)}:{tools:i}},"buildExecutorTools"),Jr=s(async(e,t,o,n,r,i,a)=>{let c=[],l=new Map,{tools:u,activeTools:d,active:m}=Br(i,o),g=i.run;g&&(g.stepActive=m);let h=s(async(b,M)=>{let F=i.config.inputSanitizer;if(!F)return M;try{return await F(b,M)}catch(f){return i.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${b} - ${f.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),w,T=[stepCountIs(i.config.maxStepsPerTask)],K=re(i.config);g&&jt(K)&&T.push(Ft(()=>g.usage,K,()=>{w="tokens";}));let D=i.config.maxToolCalls;g&&typeof D=="number"&&D>0&&T.push(()=>g.toolCalls>=D?(w??="tool-calls",true):false);let y=se(i.config,"executor",Ao({domain:i.config.systemPrompt,skills:i.skills,activeSkills:g?.activeSkills,searchMode:!!m,toolCount:i.toolCatalog.length})),k=Pe(i.config,"executor"),A=g?{summary:g.traceSummary,upTo:g.traceSummaryUpTo}:void 0,j=ke(i.config.promptCaching),R=ge(i.config.compaction),$=R.clearToolResultsAfterTokens>0?gt({triggerTokens:R.clearToolResultsAfterTokens,keep:R.keepToolResults},b=>{i.emit({type:"log",level:"info",message:`[executor] cleared ${b.cleared} stale tool result(s) from the step's context`}),i.emit({type:"context.compacted",scope:"tool-results",beforeTokens:b.beforeTokens,afterTokens:b.afterTokens});}):void 0,L=j.enabled||!!$,C=i.takeRoundUpdates,I=streamText({model:i.executorModel,tools:u,...d?{activeTools:d}:{},...m||L||C?{prepareStep:s(({messages:b,stepNumber:M})=>{let F=C&&M>0?C():[],f=F.length?[...b,{role:"user",content:Co(F)}]:b,p=Ze($?$(f):f,j);return {...m?{activeTools:[...m].filter(S=>S in u)}:{},...L||F.length?{messages:p}:{}}},"prepareStep")}:{},stopWhen:T,...y,prompt:Oo(e,t,o,n,r,A,g?.userUpdates.map(b=>b.text)),abortSignal:V(a,i.config.llmTimeoutMs??0)});for await(let b of I.fullStream)switch(b.type){case "text-delta":b.text&&i.emit({type:"step.text-delta",step:o,delta:b.text});break;case "reasoning-delta":b.text&&k&&i.emit({type:"step.reasoning-delta",step:o,delta:b.text});break;case "tool-call":{let M=await h(b.toolName,b.input);l.set(b.toolCallId,{name:b.toolName,input:M}),i.emit({type:"step.tool-call",step:o,name:b.toolName,input:M});break}case "tool-result":{if(b.preliminary)break;let F=l.get(b.toolCallId)?.input??await h(b.toolName,b.input);c.push({name:b.toolName,input:F,output:b.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:b.toolName,output:b.output,ok:true}),l.delete(b.toolCallId);break}case "tool-error":{let F=l.get(b.toolCallId)?.input??await h(b.toolName,b.input);c.push({name:b.toolName,input:F,output:b.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:b.toolName,output:b.error,ok:false}),l.delete(b.toolCallId);break}case "error":{let M=b.error;throw M instanceof Error?M:new Error(String(M))}}let[O,x]=await Promise.all([I.text,I.usage]),{summary:E,blocked:q}=Wr(O.trim());return {summary:E.length>0?qr(E):w?`Stopped early: the run's ${w==="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:q,usage:x?H(x):pe()}},"runOnce");var Yr=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:It.describe("Plan covering ONLY the remaining work")})]),_o=s(async(e,t,o,n,r,i,a=0)=>Y("agent.replan",{[P.PHASE]:"replan"},async c=>{let l=At(ye(r)),u=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,{object:d,usage:m}=await ne(async()=>{let g=se(r.config,"replanner",Ro({mode:l,catalog:r.toolCatalog,domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),h=await generateObject({model:r.plannerModel,schema:Yr,...g,prompt:Eo(e,t,o,n,u,r.run?.userUpdates.map(T=>T.text),a),abortSignal:V(i,r.config.llmTimeoutMs??0)}),w=H(h.usage);return {object:h.object,usage:w}},{maxRetries:r.config.llmMaxRetries??2,signal:i,onRetry:s((g,h)=>r.emit({type:"retry",phase:"replan",attempt:g,error:h.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:m}),c.setAttribute(P.REPLAN_MODE,d.mode),c.setAttribute(P.USAGE_TOTAL_TOKENS,m.totalTokens),d}),"decideNextAction");var No=s(async(e,t,o,n,r,i)=>Y("agent.synthesize",{[P.PHASE]:"synthesize"},async a=>{let{text:c,usage:l}=await ne(()=>Xr(e,t,o,n,r,i),{maxRetries:r.config.llmMaxRetries??2,signal:i,onRetry:s((u,d)=>r.emit({type:"retry",phase:"synthesize",attempt:u,error:d.message}),"onRetry")});return r.emit({type:"usage",phase:"synthesize",usage:l}),a.setAttribute(P.USAGE_TOTAL_TOKENS,l.totalTokens),c}),"synthesizeAnswer"),Xr=s(async(e,t,o,n,r,i)=>{let a=se(r.config,"synthesizer",Po({domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),c=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,l=Pe(r.config,"synthesizer"),u=streamText({model:r.synthesizerModel,...a,prompt:Mo(e,t,o,n,c,r.run?.userUpdates.map(g=>g.text)),abortSignal:V(i,r.config.llmTimeoutMs??0)});for await(let g of u.fullStream)if(g.type==="text-delta")g.text&&r.emit({type:"final.text-delta",delta:g.text});else if(g.type==="reasoning-delta")g.text&&l&&r.emit({type:"final.reasoning-delta",delta:g.text});else if(g.type==="error"){let h=g.error;throw h instanceof Error?h:new Error(String(h))}let[d,m]=await Promise.all([u.text,u.usage]);return {text:d,usage:H(m)}},"streamOnce");var zo=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"),ts=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return zo(t);let n=s(()=>zo(t),"fallback"),{signal:r}=o,i=o.timeoutMs??0;if(r?.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&&!r?a:new Promise(l=>{let u=false,d,m=s(h=>{u||(u=true,d!==void 0&&clearTimeout(d),r?.removeEventListener("abort",g),l(h));},"finish");function g(){m(n());}s(g,"onAbort"),c&&(d=setTimeout(()=>m(n()),i)),r?.addEventListener("abort",g,{once:true}),a.then(m,()=>m(n()));})},"replanTriggered"),qe=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),os=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||le.join(tmpdir(),"agent-sandbox");return le.join(o,t)},"resolveSandboxDir"),jo=/^[a-zA-Z0-9_-]{1,128}$/,Ot=s((e,t)=>{if(!jo.test(e))throw new Error(`Unsafe runId from ${t}: must match ${jo}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),ns=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(Ot(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(Ot(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=s(async(e,t)=>{let o=oo(t.control),n=await ns(e,t),r=n?.runId??randomUUID();Ot(r,"runId");let i=n?.startedAt??Date.now(),a=os(e,r);return W.run({runId:r,startedAt:i,sandboxDir:a,...o?{control:o}:{}},async()=>Y("agent.run",{[P.RUN_ID]:r,[P.PROVIDER]:e.config.providerType,[P.MODEL]:e.config.model},async c=>{try{let l=await ss(e,t,n,o);return o&&(l.undelivered=o.detach()),c.setAttribute(P.ITERATIONS,l.iterations),c.setAttribute(P.USAGE_TOTAL_TOKENS,l.usage.totalTokens),c.setAttribute(P.USAGE_INPUT_TOKENS,l.usage.inputTokens),c.setAttribute(P.USAGE_OUTPUT_TOKENS,l.usage.outputTokens),l}finally{o?.detach(),e.config.keepSandbox||await rm(a,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),rs=s(e=>{let t=je(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"runToolStrategy"),ss=s(async(e,t,o,n)=>{let{signal:r}=t,i=o?.input??t.input,a=o?.history?[...o.history]:t.history?[...t.history]:void 0,c=t.onEvent??(()=>{}),l=ge(e.config.compaction),u=re(e.config),d=e.config.maxToolCalls,m=H(o?.usage),g=W.getStore()?.startedAt??Date.now(),h=W.getStore()?.runId??"<unknown>",w={usage:m,toolCalls:o?.toolCallCount??0,strategy:rs(e),discovered:[],activeSkills:[...o?.activeSkills??[]],traceSummary:o?.traceSummary,traceSummaryUpTo:o?.traceSummaryUpTo??0,userUpdates:(o?.userUpdates??[]).map(p=>({...p}))},T={...e,run:w,emit:s(p=>{p.type==="usage"&&zt(m,p.usage);let S={...p,runId:W.getStore()?.runId};try{c(S);}catch{}try{e.emit(S);}catch{}},"emit")},K=W.getStore();K&&(K.emit=T.emit,K.state=w),n?.attach(T.emit);let D=s(p=>{if(!n)return [];let S=n.drain();for(let v of S)w.userUpdates.push({text:v.text,reconciled:false}),T.emit({type:"message.delivered",id:v.id,text:v.text,at:p});return S.map(v=>v.text)},"deliver");n&&(T.takeRoundUpdates=()=>D("round"));let y=s((p,S)=>{yt(e.skills??[],p,S,w,T.emit);},"activate"),k=e.config.persistence,A=s(async(p,S)=>{let v=k?.[p];if(v)try{await v(S);}catch(U){T.emit({type:"log",level:"warn",message:`[persistence] ${p} threw: ${U.message}`});}},"callPersistence"),j;if(!o&&a?.length&&l.auto){let p=await Ie(a,e.synthesizerModel,{thresholdTokens:l.thresholdTokens,keepRecentTurns:l.keepRecentTurns,summaryMaxTokens:Se(e.config,l.summaryMaxTokens),signal:r,timeoutMs:e.config.llmTimeoutMs,onUsage:s(S=>T.emit({type:"usage",phase:"compact",usage:S}),"onUsage")});p.compacted&&(a=p.history,j=p.history,T.emit({type:"context.compacted",scope:"history",beforeTokens:p.beforeTokens,afterTokens:p.afterTokens}));}let R=s(async p=>{if(!l.auto||r?.aborted)return;let S=s(()=>({summary:w.traceSummary,upTo:w.traceSummaryUpTo}),"view"),v=ae(he(p,S()));if(v<=l.thresholdTokens)return;let U=p.length-l.keepRecentSteps,G=w.traceSummary?w.traceSummaryUpTo:0;if(U<=G)return;let B=await Jt(p.slice(G,U),w.traceSummary,e.synthesizerModel,{summaryMaxTokens:Se(e.config,l.summaryMaxTokens),signal:r,timeoutMs:e.config.llmTimeoutMs,render:Fe,offset:G});B&&(T.emit({type:"usage",phase:"compact",usage:B.usage}),w.traceSummary=B.summary,w.traceSummaryUpTo=U,T.emit({type:"context.compacted",scope:"trace",beforeTokens:v,afterTokens:ae(he(p,S()))}));},"maybeCompactTrace"),$=false,L=s(()=>{let p=Ee(m,u);if(p)return p;if(typeof d=="number"&&d>0&&w.toolCalls>=d)return {kind:"tool-calls",tokens:w.toolCalls,cap:d}},"budgetBreach"),C=s(()=>{let p=L();return p?($||($=true,T.emit({type:"budget.exceeded",...p})),true):false},"reportBudget"),I;if(o)I=o.plan,T.emit({type:"log",level:"info",message:`[resume] continuing run ${h} from step ${o.stepIndex}/${I.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),T.emit({type:"plan.created",plan:I});else {try{I=await $o(i,a,T,r);}catch(p){if(T.emit({type:"error",error:Ce(p),phase:"plan"}),qe(p)||r?.aborted)throw await A("onRunComplete",{runId:h,startedAt:g,status:"cancelled",input:i,history:a,trace:[],usage:m,stepIndex:0,iterations:0,revisions:0,error:p.message,completedAt:Date.now()}),p;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."}]};}T.emit({type:"plan.created",plan:I});for(let p of I.skills??[])y(p,"plan");}let O=o?[...o.trace]:[],x=I,E=o?.stepIndex??0,q=o?.iterations??0,J=o?.revisions??0,b=e.config.maxRevisions??2,M=s((p,S={})=>({runId:h,startedAt:g,status:p,input:i,history:a,plan:x,trace:O,usage:m,stepIndex:E,iterations:q,revisions:J,...w.traceSummary?{traceSummary:w.traceSummary,traceSummaryUpTo:w.traceSummaryUpTo}:{},...w.activeSkills.length?{activeSkills:[...w.activeSkills]}:{},...w.toolCalls?{toolCallCount:w.toolCalls}:{},...w.userUpdates.length?{userUpdates:w.userUpdates.map(v=>({...v}))}:{},...S}),"buildSnapshot");o||await A("onRunStart",M("executing"));let F=s(async()=>{await A("onStepComplete",M("executing"));},"persistCheckpoint");for(;q<e.config.maxIterations;){if(r?.aborted)throw new DOMException("Aborted","AbortError");if(E>=x.steps.length||C())break;q++;let p=x.steps[E];K&&(K.currentStep=p),T.emit({type:"step.start",step:p,index:E});let S=new AbortController;if(t.onStepStart)try{t.onStepStart({step:p,index:E,abort:s(()=>S.abort(),"abort")});}catch(z){T.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${z.message}`});}let v=Qe([r,S.signal]),U;try{await R(O),U=await Uo(i,x,p,O,a,T,v);}catch(z){if(r?.aborted)throw T.emit({type:"error",error:Ce(z),phase:"execute"}),await A("onRunComplete",M("cancelled",{error:z.message,completedAt:Date.now()})),z;if(S.signal.aborted&&qe(z))T.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),U={step:p,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw T.emit({type:"error",error:Ce(z),phase:"execute"}),await A("onRunComplete",M("failed",{error:z.message,completedAt:Date.now()})),z}if(O.push(U),T.emit({type:"step.complete",step:p,result:U}),C()){E++;break}D("step");let G=w.userUpdates.filter(z=>!z.reconciled).length,B=G>0&&q<e.config.maxIterations&&!r?.aborted,me=x.steps[E+1]??null,Pt=me===null;if(Pt&&!B){T.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!(B||await ts(e.config.replanAfter,U,{signal:r,timeoutMs:e.config.llmTimeoutMs??0,onError:s(z=>T.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${z.message}`}),"onError")}))){T.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),E++,await F();continue}let ce;try{await R(O),ce=await _o(i,x,O,me,T,r,G);}catch(z){throw T.emit({type:"error",error:Ce(z),phase:"replan"}),await A("onRunComplete",M(qe(z)||r?.aborted?"cancelled":"failed",{error:z.message,completedAt:Date.now()})),z}T.emit({type:"replan.decision",mode:ce.mode,reason:ce.reason,cause:B?"user-message":"llm-decision"});for(let z of w.userUpdates)z.reconciled=true;if(ce.mode==="finish")break;if(ce.mode==="revise"){if(!B&&J>=b){T.emit({type:"revisions.exceeded",cap:b});break}B||J++,x=is(T,ce.newPlan),T.emit({type:"plan.revised",plan:x,reason:ce.reason});for(let z of x.skills??[])y(z,"plan");E=0,await F();continue}if(Pt)break;E++,await F();}let f;try{D("final"),await R(O),f=await No(i,x,O,a,T,r);}catch(p){throw T.emit({type:"error",error:Ce(p),phase:"synthesize"}),await A("onRunComplete",M(qe(p)||r?.aborted?"cancelled":"failed",{error:p.message,completedAt:Date.now()})),p}return T.emit({type:"final",text:f}),await A("onRunComplete",M("complete",{text:f,completedAt:Date.now()})),{text:f,plan:x,trace:O,iterations:q,usage:m,...j?{compactedHistory:j}:{}}},"runAgentLoopInner"),is=s((e,t)=>{let o=We(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=xt(e,t.skills),{skills:r,...i}=t;return {...i,steps:t.steps.slice(0,o),...n?{skills:n}:{}}},"reviseInto"),Ce=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var Ko=Symbol.for("@dudko.dev/agent:wrapped-tool"),Be=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}},as=s(e=>{let t=W.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new Be(e);return t.toolCalls++,()=>{t.toolCalls--;}},"reserveToolCall"),ls=s(e=>Object.prototype.toString.call(e)==="[object AsyncGeneratorFunction]","isAsyncGeneratorFunction"),cs=s((e,t,o,n={})=>{if(t[Ko])return t;let r=ue(t),i=n.builtIn===true,a=t.execute,c=s(async(d,m)=>{let g=i?()=>{}:as(o.maxToolCalls);try{await o.approval.gate(e,d,{readOnly:r,builtIn:i,signal:m?.abortSignal});}catch(h){throw g(),h}},"before"),l;a&&(l=ls(a)?async function*(d,m){await c(d,m),yield*a(d,m);}:async(d,m)=>(await c(d,m),a(d,m)));let u=lt({...t,...l?{execute:l}:{}},o.maxToolOutputChars);return Object.defineProperty(u,Ko,{value:true,enumerable:false}),u},"wrapTool"),Oe=s((e,t,o={})=>{let n={};for(let[r,i]of Object.entries(e))n[r]=cs(r,i,t,o);return n},"wrapToolSet");var Je={none:0,error:1,warn:2,info:3,debug:4},Rt=s(async(e,t)=>{let o=Je[e.logLevel]>=Je.debug,n=s(f=>{if(t)try{t(f);}catch(p){o&&console.error("[agent] event handler threw:",p);}},"emit"),r=s((f,p)=>{Je[e.logLevel]>=Je[f]&&n({type:"log",level:f,message:p});},"log"),i=po(e.skills),a=s(async(f,p)=>{if(!e.inputSanitizer)return p;try{return await e.inputSanitizer(f,p)}catch{return "[input redacted: sanitizer failed]"}},"sanitizeForApproval"),c=_t(e.toolApproval,{sanitize:a,fallbackEmit:n}),l=ge(e.compaction),u={approval:c,maxToolCalls:e.maxToolCalls,maxToolOutputChars:l.maxToolOutputChars},d=Oe(go(i),u,{builtIn:true}),m=e.toolSelectionStrategy??"auto",g=m==="search"||m==="auto",h=false,w=s(()=>[],"catalogRef"),T=g?Oe(To(()=>w()),u,{builtIn:true}):void 0,K=s(f=>{for(let p of Object.keys(d))if(f[p])throw new Error(`Tool "${p}" collides with a built-in skill tool of the same name`);if(T&&f[oe]){if(m==="search")throw new Error(`Tool "${oe}" collides with the built-in tool-search tool of the same name`);h||(h=true,r("warn",`[tools] a tool named "${oe}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),D,y=s((f,p)=>{if(!e.tools)return f;let S=[];for(let[v,U]of Object.entries(e.tools)){if(f.tools[v]&&p(v),e.availableTools?.length&&!e.availableTools.includes(v)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(v))continue;f.tools[v]=U;let G=typeof U=="object"&&U&&"description"in U?U.description:"";S.push({name:v,description:typeof G=="string"?G:"",server:"<native>",readOnly:ue(U)});}return {tools:f.tools,catalog:[...f.catalog,...S]}},"mergeNativeTools"),k=s(async()=>{let f=await eo(e.mcpServers,r,e.clientName,e.outputSanitizer,v=>D?.(v),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),p=mt(f.tools,f.catalog,e.availableTools,e.excludedTools,r),S;try{S=y(p,v=>{throw new Error(`Native tool "${v}" collides with an MCP-registered tool of the same name`)}),K(S.tools);}catch(v){throw f.close().catch(()=>{}),v}return {connection:f,tools:Oe(S.tools,u),catalog:S.catalog}},"connect"),A;try{A=await k();}catch(f){throw n({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let j=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&j>0&&!A.connection.results.some(p=>p.connected)){let p=A.connection.results.filter(v=>!v.connected).map(v=>`${v.name}: ${v.error??"unknown"}`).join("; ");await A.connection.close().catch(()=>{});let S=new Error(`All ${j} configured MCP server(s) failed to connect [${p}]`);throw n({type:"error",error:S,phase:"init"}),S}let R,$,L;try{let f=_e(e,void 0,void 0,"executor"),p=_e(e,e.planner,e.plannerModel,"planner"),S=_e(e,e.synthesizer,e.synthesizerModel,"synthesizer");[R,$,L]=await Promise.all([Ne(e.clientName,f),Ne(e.clientName,p),Ne(e.clientName,S)]);}catch(f){throw await A.connection.close().catch(()=>{}),n({type:"error",error:f instanceof Error?f:new Error(String(f)),phase:"init"}),f}let C=s(f=>f.map(p=>({name:p.name,description:p.description,server:p.server,readOnly:p.readOnly===true})),"toEntries"),I={config:e,executorModel:R,plannerModel:$,synthesizerModel:L,tools:A.tools,toolCatalog:C(A.catalog),emit:n,...Object.keys(d).length?{builtinTools:d}:{},...i.length?{skills:i}:{},approval:c};w=s(()=>I.toolCatalog,"catalogRef");let O=s(()=>{T&&!h?I.findTools=T:delete I.findTools;},"syncFindTools");O();let x=0,E=false,q=false,J=false,b=new Set,M=s(async f=>{await A.connection.refreshServer(f);let p=mt(A.connection.tools,A.connection.catalog,e.availableTools,e.excludedTools),S=y(p,U=>{throw new Error(`Native tool "${U}" collides with an MCP-registered tool of the same name`)});K(S.tools);let v=Oe(S.tools,u);for(let U of Object.keys(I.tools))delete I.tools[U];Object.assign(I.tools,v),I.toolCatalog=C(S.catalog),O(),r("info",`[mcp] ${f}: tool list refreshed (${S.catalog.length} tools total after filter)`);},"applyRefresh"),F=s(async()=>{if(!(J||E||q)&&!(x>0||b.size===0)){J=true;try{for(;b.size>0&&x===0&&!E&&!q;){let f=b.values().next().value;b.delete(f);try{await M(f);}catch(p){r("warn",`[mcp] ${f}: refresh failed - ${p.message}`);}}}finally{J=false;}}},"drainPendingRefreshes");return D=s(f=>{b.add(f),F();},"onToolsChanged"),{run:s(async f=>{if(E)throw new Error("Agent is closed");if(q)throw new Error("Agent is reconnecting; retry shortly");if(J)throw new Error("Agent is refreshing tools; retry shortly");let p=e.maxConcurrentRuns;if(typeof p=="number"&&p>0&&x>=p)throw new Error(`maxConcurrentRuns reached (${x}/${p}); rate-limit on the caller side or raise the cap`);x++;try{return await Fo(I,f)}finally{x--,F();}},"run"),listTools:s(()=>I.toolCatalog.map(f=>({...f})),"listTools"),listSkills:s(()=>i.map(f=>({name:f.name,description:f.description})),"listSkills"),compact:s(async f=>{let p=await Ie(f.history,I.synthesizerModel,{thresholdTokens:l.thresholdTokens,keepRecentTurns:l.keepRecentTurns,summaryMaxTokens:Se(e,l.summaryMaxTokens),force:f.force,signal:f.signal,timeoutMs:e.llmTimeoutMs,onUsage:s(S=>n({type:"usage",phase:"compact",usage:S}),"onUsage")});return p.compacted&&n({type:"context.compacted",scope:"history",beforeTokens:p.beforeTokens,afterTokens:p.afterTokens}),{history:p.history,...p.summary?{summary:p.summary}:{},beforeTokens:p.beforeTokens,afterTokens:p.afterTokens,compacted:p.compacted}},"compact"),setToolApprovalMode:s(f=>c.setMode(f),"setToolApprovalMode"),getToolApprovalMode:s(()=>c.getMode(),"getToolApprovalMode"),reconnect:s(async()=>{if(E)throw new Error("Agent is closed");if(q)throw new Error("Already reconnecting");if(J)throw new Error("Agent is refreshing tools; retry shortly");if(x>0)throw new Error(`Cannot reconnect with ${x} active run(s)`);q=true;try{let f=A.connection;b.clear();let p=await k();for(let S of Object.keys(I.tools))delete I.tools[S];Object.assign(I.tools,p.tools),I.toolCatalog=C(p.catalog),O(),A=p,await f.close().catch(()=>{});}finally{q=false;}},"reconnect"),close:s(async f=>{E=true;let p=f?.waitForRuns??false,S=f?.timeoutMs??3e4,v=Date.now()+S;if(p&&x>0)for(;x>0&&Date.now()<v;)await new Promise(me=>setTimeout(me,50));x>0&&n({type:"log",level:"warn",message:`[agent] close called with ${x} active run(s); they will fail mid-flight`});let U=Math.max(v-Date.now(),0),G=false,B;await Promise.race([A.connection.close().catch(()=>{}),new Promise(me=>{B=setTimeout(()=>{G=true,me();},U),B.unref?.();})]),B&&clearTimeout(B),G&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${U}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>x,"activeRuns")}},"createAgent");var fs=8e3,hs=4,ys=4e3,Wo=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"),Ts=s(e=>{try{return structuredClone(e)}catch{return Wo(e)}},"toCloneable"),Et=s((e,t=0)=>{if(typeof e=="string")return de(e,ys);if(e instanceof Error||!e||typeof e!="object"||t>8)return e;if(Array.isArray(e))return e.map(n=>Et(n,t+1));let o={};for(let[n,r]of Object.entries(e))o[n]=Et(r,t+1);return o},"clipStrings"),ks=s(e=>Et(e),"slimEvent"),Ho=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[a,c]of Object.entries(r))n(c,`${i}.${a}`);}},"walk");n(e,t);},"assertWorkerSafeConfig"),ws=s(()=>{let e=import.meta.url;return new URL(e.endsWith(".ts")?"./subagent-worker.ts":"./subagent-worker.js",e)},"subagentWorkerUrl"),bs=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"),vs=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 a=s(()=>{n?.removeEventListener("abort",c),t++,r();},"grant");function c(){let l=o.indexOf(a);l>=0&&o.splice(l,1),i(n?.reason??new DOMException("Aborted","AbortError"));}if(s(c,"onAbort"),t<e){a();return}n?.addEventListener("abort",c,{once:true}),o.push(a);}),"acquire"),release:s(()=>{t--,o.shift()?.();},"release")}},"createSemaphore"),Ss=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:{}},a=e.execute(o,i);if(a&&typeof a[Symbol.asyncIterator]=="function"){let c;for await(let l of a)c=l;a=c;}return {ok:!0,output:Wo(await a)}}catch(i){return {ok:false,output:et(i)}}},"runHostTool"),Is=s(e=>Object.entries(e).map(([t,o])=>({name:t,description:typeof o.description=="string"?o.description:"",inputSchema:asSchema(o.inputSchema).jsonSchema,...ue(o)?{readOnly:true}:{}})),"describeTools"),As=s(async(e,t,o,n,r)=>{let i={...t.tools??{},...e.tools??{}},a=await Rt({...t,...Object.keys(i).length?{tools:i}:{}},r);try{let c=await a.run({input:o,signal:n});return {text:c.text,usage:c.usage}}finally{await a.close({timeoutMs:5e3}).catch(()=>{});}},"runInProcess"),xs=s((e,t,o,n,r)=>new Promise((i,a)=>{let c=e.tools??{},l=false,u;try{let h=bs();u=new Worker(ws(),{workerData:{subagent:e.name},...h?{execArgv:h}:{}});}catch(h){a(h);return}let d=s(h=>{l||(l=true,n.removeEventListener("abort",m),h(),u.terminate().catch(()=>{}));},"finish");function m(){u.postMessage({type:"abort"}),setTimeout(()=>d(()=>a(n.reason??new DOMException("Aborted","AbortError"))),1e3).unref?.();}s(m,"onAbort");let g=AsyncResource.bind(h=>{switch(h.type){case "event":r(h.event);break;case "tool-call":Ss(c[h.name],h.name,h.input,h.callId,n).then(w=>{l||u.postMessage({type:"tool-result",callId:h.callId,ok:w.ok,output:w.output});});break;case "done":d(()=>i({text:h.text,usage:h.usage}));break;case "error":d(()=>a(n.aborted?n.reason??new DOMException("Aborted","AbortError"):new Error(h.error)));break}});if(u.on("message",g),u.on("error",h=>d(()=>a(h))),u.on("exit",h=>d(()=>a(new Error(`subagent worker exited with code ${h} before finishing`)))),n.aborted){m();return}n.addEventListener("abort",m,{once:true}),u.postMessage({type:"run",task:o,config:Ts(t),proxied:Is(c)});}),"runInWorker"),Cs=s(e=>{let t=e.isolation??"worker";if(!e.name||typeof e.name!="string")throw new Error("createSubagentTool: name is required");t==="worker"&&Ho(e.config,`subagent "${e.name}": config`);let o=e.profiles??{},n=Object.keys(o);for(let[m,g]of Object.entries(o)){if(!m.trim())throw new Error(`subagent "${e.name}": a profile needs a non-empty name`);if(!g||typeof g.description!="string"||!g.description.trim())throw new Error(`subagent "${e.name}": profile "${m}" needs a description - the parent model chooses by it`);t==="worker"&&g.config&&Ho(g.config,`subagent "${e.name}": profile "${m}" config`);}let r=s(m=>{if(m){if(!Object.hasOwn(o,m))throw new Error(`subagent "${e.name}": unknown profile "${m}" - choose one of: ${n.join(", ")}`);return o[m]}},"pickProfile"),i=e.outputMaxChars??fs,a=vs(Math.max(1,e.maxConcurrent??hs)),c=n.length?`${e.description}
|
|
136
|
+
|
|
137
|
+
Optional \`profile\` (omit it for the default):
|
|
138
|
+
${n.map(m=>`- ${m}: ${o[m].description}`).join(`
|
|
139
|
+
`)}`:e.description,l=z.string().describe("A complete, self-contained task for the subagent, with all context it needs"),u=n.length?z.object({task:l,profile:z.enum(n).optional().describe("One of this tool's profiles, described above. Omit it for the default.")}):z.object({task:l}),d=tool({description:c,inputSchema:u,execute:s(async({task:m,profile:g},{abortSignal:h})=>{let w=r(g),T={...e.config,...w?.config},K=W.getStore(),D=K?.emit??(()=>{}),y=randomUUID(),k=e.name;await a.acquire(h);let A=new AbortController,j=s(()=>A.abort(h?.reason),"onParentAbort");h?.addEventListener("abort",j,{once:true}),h?.aborted&&j();let R=false,$=false,L,C=typeof e.timeoutMs=="number"&&e.timeoutMs>0?setTimeout(()=>{R=true,A.abort(new Error(`subagent "${k}" timed out after ${e.timeoutMs}ms`));},e.timeoutMs):void 0,I=pe(),O=s(x=>{if(x.type==="usage"){let E=H(x.usage);D({type:"usage",phase:"subagent",usage:E});}D({type:"subagent.event",id:y,name:k,event:ks(x)});},"onChildEvent");try{D({type:"subagent.start",id:y,name:k,task:m,...w?{profile:g}:{}}),L=K?.control?.registerSubagent({id:y,name:k,task:m,...w?{profile:g}:{},startedAt:Date.now()},()=>{$=!0,A.abort(new DOMException("Aborted","AbortError"));});let x=t==="worker"?await xs(e,T,m,A.signal,O):await As(e,T,m,A.signal,O);I=H(x.usage);let E=de(x.text,i);return D({type:"subagent.complete",id:y,name:k,text:E,usage:I}),E}catch(x){let E=$?`subagent "${k}" was stopped by the user before it finished - carry on without its result, or take another approach`:R?`subagent "${k}" timed out after ${e.timeoutMs}ms`:et(x);throw D({type:"subagent.error",id:y,name:k,error:E,...$?{stopped:true}:{}}),$||R?new Error(E):x}finally{L?.(),C&&clearTimeout(C),h?.removeEventListener("abort",j),a.release();}},"execute")});return Z(d,e.readOnly===true)},"createSubagentTool");export{$e as FileOAuthStore,ct as MemoryOAuthStore,Le as NodeOAuthProvider,it as SUMMARY_PREFIX,Be as ToolBudgetError,Te as ToolDeniedError,be as addUsage,bn as beginMcpOAuth,Xe as buildInstructions,Ee as checkLimits,Ie as compactHistory,Rt as createAgent,wn as createNodeOAuthProvider,tr as createRunControl,Cs as createSubagentTool,gt as createToolResultClearer,Ut as decideToolPermission,ft as defineSkill,ae as estimateTokens,vn as finishMcpOAuth,Jo as getCurrentRunId,Ye as getCurrentRunSandbox,ue as isReadOnlyTool,dr as loadSkillsFromDir,Z as markReadOnly,Lt as matchToolRule,rt as mergeProviderOptions,H as normalizeUsage,co as parseSkillMarkdown,tn as redactHeaders,re as resolveLimits,ke as resolvePromptCaching,ot as resolveThinking,ho as searchTools,Gt as truncateToolModelOutput,Ze as withRollingBreakpoint,lt as withToolOutputLimit};
|