@dudko.dev/agent 0.0.35 → 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/cli.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {randomUUID}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {tool,dynamicTool,jsonSchema,generateText,generateObject,streamObject,stepCountIs,streamText}from'ai';import {UnauthorizedError,auth}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {readdir,readFile,stat,rm,mkdir,writeFile}from'fs/promises';import
|
|
2
|
+
import {parseArgs}from'util';import {stdout,stdin}from'process';import {createInterface}from'readline/promises';import {randomUUID}from'crypto';import {AsyncLocalStorage}from'async_hooks';import {tool,dynamicTool,jsonSchema,generateText,generateObject,streamObject,stepCountIs,streamText}from'ai';import {UnauthorizedError,auth}from'@modelcontextprotocol/sdk/client/auth.js';import {Client}from'@modelcontextprotocol/sdk/client/index.js';import {getDefaultEnvironment,StdioClientTransport}from'@modelcontextprotocol/sdk/client/stdio.js';import {StreamableHTTPClientTransport}from'@modelcontextprotocol/sdk/client/streamableHttp.js';import {ToolListChangedNotificationSchema}from'@modelcontextprotocol/sdk/types.js';import {readdir,readFile,stat,rm,mkdir,writeFile}from'fs/promises';import le from'path';import {URL as URL$1}from'url';import In,{tmpdir}from'os';import {SpanStatusCode,trace}from'@opentelemetry/api';import {z}from'zod';import'worker_threads';var ln=Object.defineProperty;var s=(e,t)=>ln(e,"name",{value:t,configurable:true});var Pt=`Usage: dd-agent [options]
|
|
3
3
|
|
|
4
4
|
Options:
|
|
5
5
|
--env-file=<path> Load env vars from a dotenv file before starting
|
|
@@ -32,6 +32,7 @@ Optional env vars (see env.example for the full list):
|
|
|
32
32
|
AGENT_MAX_TOTAL_TOKENS
|
|
33
33
|
AGENT_MAX_TOOL_CALLS cap on tool calls per run
|
|
34
34
|
AGENT_TOOL_APPROVAL autopilot | ask-writes | ask-all | read-only
|
|
35
|
+
AGENT_TOOL_RULES JSON: { "<tool or glob*>": "allow" | "ask" | "deny" } - beats the mode
|
|
35
36
|
AGENT_SKILLS_DIR folder of <skill>/SKILL.md skills
|
|
36
37
|
AGENT_CONTEXT_WINDOW_TOKENS model window (auto-compaction threshold = 50%)
|
|
37
38
|
AGENT_COMPACTION off disables automatic compaction
|
|
@@ -39,48 +40,50 @@ Optional env vars (see env.example for the full list):
|
|
|
39
40
|
Commands inside the REPL:
|
|
40
41
|
/status, /tools, /history, /reset, /reconnect, /exit
|
|
41
42
|
/compact summarise the conversation history now
|
|
43
|
+
/agents, /stop [n] while a run goes: list running subagents / stop one (the run goes on);
|
|
44
|
+
any other text you type then is said to the running agent
|
|
42
45
|
/autopilot toggle autopilot (no tool approval prompts)
|
|
43
46
|
/approval <mode> autopilot | ask-writes | ask-all | read-only
|
|
44
47
|
|
|
45
48
|
When the approval mode asks, answer y (allow once), n (deny) or a (always
|
|
46
49
|
allow this tool for the session).
|
|
47
|
-
`,Yo={provider:"AGENT_PROVIDER_TYPE",model:"AGENT_MODEL","planner-model":"AGENT_PLANNER_MODEL","synthesizer-model":"AGENT_SYNTHESIZER_MODEL","base-url":"AGENT_BASE_URL","log-level":"AGENT_LOG_LEVEL","max-iterations":"AGENT_MAX_ITERATIONS","max-steps-per-task":"AGENT_MAX_STEPS_PER_TASK","tool-strategy":"AGENT_TOOL_SELECTION_STRATEGY"},Ot=s(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"},provider:{type:"string"},model:{type:"string"},"planner-model":{type:"string"},"synthesizer-model":{type:"string"},"base-url":{type:"string"},"log-level":{type:"string"},"max-iterations":{type:"string"},"max-steps-per-task":{type:"string"},"tool-strategy":{type:"string"}},strict:true,allowPositionals:false}),o={},n=t;for(let[r,i]of Object.entries(Yo)){let a=n[r];typeof a=="string"&&a.length>0&&(o[i]=a);}return {envFile:t["env-file"],help:!!t.help,overrides:o}},"parseCliArgs");var K=new AsyncLocalStorage;var Be=s(()=>K.getStore()?.sandboxDir,"getCurrentRunSandbox");var Ve=new Set(["autopilot","ask-writes","ask-all","read-only"]),xt=s(e=>typeof e=="string"&&Ve.has(e),"isToolApprovalMode"),fe=class extends Error{static{s(this,"ToolDeniedError");}reason;constructor(t){super(`Tool call denied by the user${t?`: ${t}`:""}. Do not retry it; continue without it, or report what is blocked.`),this.name="ToolDeniedError",this.reason=t;}toJSON(){return this.message}},Z=s((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),le=s(e=>!!e&&typeof e=="object"&&e.readOnly===true,"isReadOnlyTool"),Rt=new Map,Zo=s(e=>{let t=Rt.get(e);if(!t){let o=e.split("*").map(n=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t=new RegExp(`^${o}$`),Rt.set(e,t);}return t},"globToRegExp"),Ct=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("*")&&Zo(n).test(t)&&(!o||n.length>o.pattern.length)&&(o={pattern:n,permission:r});return o},"matchToolRule"),Pt=s(e=>{if(e.builtIn)return {permission:"allow",source:"builtin"};if(e.remembered?.has(e.name))return {permission:"allow",source:"remembered"};let t=Ct(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"),Qo=s(e=>typeof e=="boolean"?{approved:e}:e&&typeof e=="object"?{approved:e.approved===true,reason:e.reason,remember:e.remember}:{approved:false,reason:"invalid approval decision"},"normalizeDecision"),xe=class extends Error{static{s(this,"ApprovalTimeout");}},en=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 xe);},t)),e.then(l=>{a(),n(l);},l=>{a(),r(l);});}),"awaitDecision"),Mt=s((e,t={})=>{let o=e?.mode??"autopilot";if(!xt(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(!xt(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=Pt({name:i,readOnly:c.readOnly,mode:o,rules:e?.rules,remembered:n,builtIn:c.builtIn});if(l.permission==="allow")return;let p=K.getStore(),d=p?.emit??t.fallbackEmit??(()=>{}),T=randomUUID(),f=s((u,m)=>{throw d({type:"tool.approval-resolved",id:T,name:i,approved:false,reason:u,automatic:m}),new fe(u)},"deny");l.permission==="deny"&&f(l.source==="rule"?`denied by rule "${l.rule}"`:`"${o}" mode allows read-only tools only`,true);let y=e?.onRequest;if(!y){f("no approval handler configured",true);return}let k=t.sanitize?await t.sanitize(i,a):a,A=p?.currentStep;d({type:"tool.approval-requested",id:T,name:i,input:k,readOnly:c.readOnly,...A?{step:A}:{}});let $={id:T,toolName:i,input:k,readOnly:c.readOnly,...A?{step:A}:{},...p?.runId?{runId:p.runId}:{}},D;try{D=await en(Promise.resolve().then(()=>y($)),e?.timeoutMs,c.signal);}catch(u){if(u instanceof xe&&f(`no decision within ${e?.timeoutMs}ms`,true),c.signal?.aborted)throw d({type:"tool.approval-resolved",id:T,name:i,approved:false,reason:"aborted",automatic:true}),u;f(`approval handler failed: ${u?.message??String(u)}`,true);return}let h=Qo(D);if(h.approved&&h.remember&&n.add(i),d({type:"tool.approval-resolved",id:T,name:i,approved:h.approved,...h.reason?{reason:h.reason}:{},automatic:false}),!h.approved)throw new fe(h.reason)},"gate")}},"createApprovalController");var he=s(e=>e===false?{enabled:false}:e===void 0||e===true?{enabled:true}:{enabled:true,...e.ttl?{ttl:e.ttl}:{},...e.key?{key:e.key}:{}},"resolvePromptCaching"),Ye=s((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),_t=s((e,t,o)=>e.enabled?{openai:{promptCacheKey:e.key??`${t}:${o}`}}:void 0,"cacheProviderOptions"),tn=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"),Je=s((e,t)=>{if(!t.enabled||e.length===0)return e;let o=e.map((i,a)=>a<e.length-1?tn(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 $t=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"?$t(o.cause,t):false},"isRetriable"),te=s(async(e,t)=>{let o=t.baseDelayMs??500,n;for(let r=0;r<=t.maxRetries;r++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(n=i,r===t.maxRetries||!$t(i))throw i;t.onRetry?.(r+1,i);let a=o*2**r+Math.random()*250;await on(a,t.signal);}}throw n},"withRetry"),on=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"),Xe=s(e=>{let t=e.filter(o=>!!o);return t.length===0?new AbortController().signal:t.length===1?t[0]:AbortSignal.any(t)},"combineSignals"),B=s((e,t)=>!Number.isFinite(t)||t<=0?e??new AbortController().signal:Xe([e,AbortSignal.timeout(t)]),"withTimeout");var ce=s(()=>({inputTokens:0,outputTokens:0,totalTokens:0,reasoningTokens:0,cachedInputTokens:0,cacheWriteTokens:0}),"emptyUsage"),ye=s(e=>typeof e=="number"&&Number.isFinite(e)?e:0,"n"),G=s(e=>{if(!e)return ce();let t=ye(e.inputTokens),o=ye(e.outputTokens);return {inputTokens:t,outputTokens:o,totalTokens:typeof e.totalTokens=="number"?e.totalTokens:t+o,reasoningTokens:ye(e.outputTokenDetails?.reasoningTokens??e.reasoningTokens),cachedInputTokens:ye(e.inputTokenDetails?.cacheReadTokens??e.cachedInputTokens),cacheWriteTokens:ye(e.inputTokenDetails?.cacheWriteTokens)}},"normalizeUsage"),Te=s((e,t)=>({inputTokens:e.inputTokens+t.inputTokens,outputTokens:e.outputTokens+t.outputTokens,totalTokens:e.totalTokens+t.totalTokens,reasoningTokens:(e.reasoningTokens??0)+(t.reasoningTokens??0),cachedInputTokens:(e.cachedInputTokens??0)+(t.cachedInputTokens??0),cacheWriteTokens:(e.cacheWriteTokens??0)+(t.cacheWriteTokens??0)}),"addUsage"),Lt=s((e,t)=>{Object.assign(e,Te(e,t));},"accumulateUsage"),ke=s((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText");var oe=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"),Nt=s(e=>!!(e&&(we(e.maxInputTokens)||we(e.maxOutputTokens)||we(e.maxReasoningTokens)||we(e.maxTotalTokens))),"hasTokenLimits"),Re=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"),nn=s(e=>e.reduce((t,o)=>Te(t,G(o.usage)),ce()),"sumStepUsage"),Ut=s((e,t,o)=>({steps:n})=>{let r=Re(Te(e(),nn(n)),t);return r?(o?.(r),true):false},"limitsStopCondition");var Dt=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=Dt(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"),Ce=s((e,t)=>Dt(et(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),Ze=s(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),jt=s((e,t)=>{let o={...e};for(let[n,r]of Object.entries(t))o[n]=Ze(o[n])&&Ze(r)?jt(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]=jt(t[n]??{},r));return t},"mergeProviderOptions");var zt=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),ne=s((e,t,o)=>{let n=he(e.promptCaching),r=Qe(et(e,t)),i=tt(r.providerOptions,_t(n,e.clientName,t)),a=zt(oe(e).perCall?.[t]);return {instructions:Ye(o,n),...r.reasoning?{reasoning:r.reasoning}:{},...i?{providerOptions:i}:{},...a?{maxOutputTokens:a}:{}}},"stageCallOptions"),ve=s((e,t)=>{let o=zt(oe(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var Kt=128e3,rn=2e4,re=s((e,t)=>typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):t,"nonNeg"),pe=s(e=>{let t=re(e?.contextWindowTokens,0)||Kt;return {auto:e?.auto!==false,contextWindowTokens:t,thresholdTokens:re(e?.thresholdTokens,0)||Math.floor(t/2),keepRecentTurns:re(e?.keepRecentTurns,4),keepRecentSteps:re(e?.keepRecentSteps,3),summaryMaxTokens:re(e?.summaryMaxTokens,0)||1024,maxToolOutputChars:re(e?.maxToolOutputChars,rn),clearToolResultsAfterTokens:re(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:re(e?.keepToolResults,3)}},"resolveCompaction"),se=s(e=>Math.ceil(e.length/4),"estimateTokens"),nt="[Summary of earlier conversation]",Se=s(e=>e.role==="assistant"&&e.content.startsWith(nt),"isSummaryTurn"),ot=s(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
|
|
48
|
-
`),"renderTurns"),
|
|
50
|
+
`,pn={provider:"AGENT_PROVIDER_TYPE",model:"AGENT_MODEL","planner-model":"AGENT_PLANNER_MODEL","synthesizer-model":"AGENT_SYNTHESIZER_MODEL","base-url":"AGENT_BASE_URL","log-level":"AGENT_LOG_LEVEL","max-iterations":"AGENT_MAX_ITERATIONS","max-steps-per-task":"AGENT_MAX_STEPS_PER_TASK","tool-strategy":"AGENT_TOOL_SELECTION_STRATEGY"},Mt=s(e=>{let{values:t}=parseArgs({args:e,options:{"env-file":{type:"string"},help:{type:"boolean",short:"h"},provider:{type:"string"},model:{type:"string"},"planner-model":{type:"string"},"synthesizer-model":{type:"string"},"base-url":{type:"string"},"log-level":{type:"string"},"max-iterations":{type:"string"},"max-steps-per-task":{type:"string"},"tool-strategy":{type:"string"}},strict:true,allowPositionals:false}),o={},r=t;for(let[n,i]of Object.entries(pn)){let l=r[n];typeof l=="string"&&l.length>0&&(o[i]=l);}return {envFile:t["env-file"],help:!!t.help,overrides:o}},"parseCliArgs");var F=new AsyncLocalStorage;var Xe=s(()=>F.getStore()?.sandboxDir,"getCurrentRunSandbox");var Ze=new Set(["autopilot","ask-writes","ask-all","read-only"]),_t=s(e=>typeof e=="string"&&Ze.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}},ee=s((e,t=true)=>(e.readOnly=t,e),"markReadOnly"),de=s(e=>!!e&&typeof e=="object"&&e.readOnly===true,"isReadOnlyTool"),Lt=new Map,mn=s(e=>{let t=Lt.get(e);if(!t){let o=e.split("*").map(r=>r.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");t=new RegExp(`^${o}$`),Lt.set(e,t);}return t},"globToRegExp"),Nt=s((e,t)=>{if(!e)return;if(Object.hasOwn(e,t)&&!t.includes("*"))return {pattern:t,permission:e[t]};let o;for(let[r,n]of Object.entries(e))r.includes("*")&&mn(r).test(t)&&(!o||r.length>o.pattern.length)&&(o={pattern:r,permission:n});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=Nt(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"),gn=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"),$e=class extends Error{static{s(this,"ApprovalTimeout");}},fn=s((e,t,o)=>new Promise((r,n)=>{let i,l=s(()=>{i&&clearTimeout(i),o?.removeEventListener("abort",a);},"done");function a(){l(),n(o?.reason??new DOMException("Aborted","AbortError"));}if(s(a,"onAbort"),o?.aborted){a();return}o?.addEventListener("abort",a,{once:true}),typeof t=="number"&&t>0&&(i=setTimeout(()=>{l(),n(new $e);},t)),e.then(c=>{l(),r(c);},c=>{l(),n(c);});}),"awaitDecision"),Dt=s((e,t={})=>{let o=e?.mode??"autopilot";if(!_t(o))throw new Error(`toolApproval.mode must be ${[...Ze].join(" | ")}, got: ${JSON.stringify(o)}`);let r=new Set;return {getMode:s(()=>o,"getMode"),setMode:s(i=>{if(!_t(i))throw new Error(`tool approval mode must be ${[...Ze].join(" | ")}, got: ${JSON.stringify(i)}`);o=i;},"setMode"),remembered:r,gate:s(async(i,l,a)=>{let c=Ut({name:i,readOnly:a.readOnly,mode:o,rules:e?.rules,remembered:r,builtIn:a.builtIn});if(c.permission==="allow")return;let p=F.getStore(),g=p?.emit??t.fallbackEmit??(()=>{}),h=randomUUID(),f=s((b,x)=>{throw g({type:"tool.approval-resolved",id:h,name:i,approved:false,reason:b,automatic:x}),new Te(b)},"deny");c.permission==="deny"&&f(c.source==="rule"?`denied by rule "${c.rule}"`:`"${o}" mode allows read-only tools only`,true);let S=e?.onRequest;if(!S){f("no approval handler configured",true);return}let A=t.sanitize?await t.sanitize(i,l):l,w=p?.currentStep;g({type:"tool.approval-requested",id:h,name:i,input:A,readOnly:a.readOnly,...w?{step:w}:{}});let R={id:h,toolName:i,input:A,readOnly:a.readOnly,...w?{step:w}:{},...p?.runId?{runId:p.runId}:{}},j;try{j=await fn(Promise.resolve().then(()=>S(R)),e?.timeoutMs,a.signal);}catch(b){if(b instanceof $e&&f(`no decision within ${e?.timeoutMs}ms`,true),a.signal?.aborted)throw g({type:"tool.approval-resolved",id:h,name:i,approved:false,reason:"aborted",automatic:true}),b;f(`approval handler failed: ${b?.message??String(b)}`,true);return}let y=gn(j);if(y.approved&&y.remember&&r.add(i),g({type:"tool.approval-resolved",id:h,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"),Qe=s((e,t)=>t.enabled?{role:"system",content:e,providerOptions:{anthropic:{cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}}:e,"buildInstructions"),jt=s((e,t,o)=>e.enabled?{openai:{promptCacheKey:e.key??`${t}:${o}`}}:void 0,"cacheProviderOptions"),hn=s(e=>{let t=e.providerOptions;if(!t?.anthropic||!("cacheControl"in t.anthropic))return e;let{cacheControl:o,...r}=t.anthropic,{anthropic:n,...i}=t,l=Object.keys(r).length?{...i,anthropic:r}:i,{providerOptions:a,...c}=e;return Object.keys(l).length?{...c,providerOptions:l}:c},"withoutBreakpoint"),et=s((e,t)=>{if(!t.enabled||e.length===0)return e;let o=e.map((i,l)=>l<e.length-1?hn(i):i),r=o[o.length-1],n=r.providerOptions??{};return o[o.length-1]={...r,providerOptions:{...n,anthropic:{...n.anthropic,cacheControl:{type:"ephemeral",...t.ttl?{ttl:t.ttl}:{}}}}},o},"withRollingBreakpoint");var zt=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 r=o.statusCode??o.status;return typeof r=="number"?r===429||r>=500:o.name==="TypeError"?true:o.cause&&typeof o.cause=="object"?zt(o.cause,t):false},"isRetriable"),ne=s(async(e,t)=>{let o=t.baseDelayMs??500,r;for(let n=0;n<=t.maxRetries;n++){if(t.signal?.aborted)throw new DOMException("Aborted","AbortError");try{return await e()}catch(i){if(r=i,n===t.maxRetries||!zt(i))throw i;t.onRetry?.(n+1,i);let l=o*2**n+Math.random()*250;await yn(l,t.signal);}}throw r},"withRetry"),yn=s((e,t)=>new Promise((o,r)=>{if(t?.aborted){r(new DOMException("Aborted","AbortError"));return}let n=setTimeout(()=>{t?.removeEventListener("abort",i),o();},e),i=s(()=>{clearTimeout(n),r(new DOMException("Aborted","AbortError"));},"onAbort");t?.addEventListener("abort",i,{once:true});}),"sleep"),tt=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:tt([e,AbortSignal.timeout(t)]),"withTimeout");var me=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"),G=s(e=>{if(!e)return me();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"),Gt=s((e,t)=>{Object.assign(e,be(e,t));},"accumulateUsage"),ve=s((e,t)=>t>0&&e.length>t?`${e.slice(0,t)}\u2026 [truncated ${e.length-t} chars]`:e,"clipText");var re=s(e=>{let t=e.limits?.maxTotalTokens??e.maxTotalTokens;return {...e.limits,...t!==void 0?{maxTotalTokens:t}:{}}},"resolveLimits"),Se=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0,"isCap"),Kt=s(e=>!!(e&&(Se(e.maxInputTokens)||Se(e.maxOutputTokens)||Se(e.maxReasoningTokens)||Se(e.maxTotalTokens))),"hasTokenLimits"),Pe=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[r,n,i]of o)if(Se(i)&&n>=i)return {kind:r,tokens:n,cap:i}},"checkLimits"),Tn=s(e=>e.reduce((t,o)=>be(t,G(o.usage)),me()),"sumStepUsage"),Ft=s((e,t,o)=>({steps:r})=>{let n=Pe(be(e(),Tn(r)),t);return n?(o?.(n),true):false},"limitsStopCondition");var Ht=s(e=>{if(!(e===void 0||e===false))return e===true?{level:"medium"}:typeof e=="string"?{level:e}:{...e,level:e.level??"medium"}},"normalizeThinking"),nt=s(e=>{let t=Ht(e);if(!t)return {};let o=t.level??"medium";if(o==="none")return {reasoning:"none"};let r=t.includeThoughts!==false,n=t.budgetTokens;if(typeof n=="number"&&Number.isFinite(n)&&n>0){let i=Math.floor(n);return {reasoning:o,providerOptions:{anthropic:{thinking:{type:"enabled",budgetTokens:i}},google:{thinkingConfig:{thinkingBudget:i,includeThoughts:r}}}}}return r?{reasoning:o,providerOptions:{google:{thinkingConfig:{includeThoughts:true}},openai:{reasoningSummary:"auto"}}}:{reasoning:o}},"resolveThinking"),rt=s((e,t)=>{let o=e.stageThinking?.[t];return o!==void 0?o:e.thinking},"stageThinkingSetting"),Me=s((e,t)=>Ht(rt(e,t))?.includeThoughts!==false,"stageEmitsThoughts"),ot=s(e=>!!e&&typeof e=="object"&&!Array.isArray(e),"isPlainObject"),Wt=s((e,t)=>{let o={...e};for(let[r,n]of Object.entries(t))o[r]=ot(o[r])&&ot(n)?Wt(o[r],n):n;return o},"deepMerge"),st=s((...e)=>{let t;for(let o of e)if(o)for(let[r,n]of Object.entries(o))ot(n)&&(t??={},t[r]=Wt(t[r]??{},n));return t},"mergeProviderOptions");var qt=s(e=>typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0,"positive"),se=s((e,t,o)=>{let r=ke(e.promptCaching),n=nt(rt(e,t)),i=st(n.providerOptions,jt(r,e.clientName,t)),l=qt(re(e).perCall?.[t]);return {instructions:Qe(o,r),...n.reasoning?{reasoning:n.reasoning}:{},...i?{providerOptions:i}:{},...l?{maxOutputTokens:l}:{}}},"stageCallOptions"),Ie=s((e,t)=>{let o=qt(re(e).perCall?.compaction);return o?Math.min(o,t):t},"compactionMaxTokens");var Vt=128e3,kn=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)||Vt;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,kn),clearToolResultsAfterTokens:ie(e?.clearToolResultsAfterTokens,Math.floor(t/4)),keepToolResults:ie(e?.keepToolResults,3)}},"resolveCompaction"),ae=s(e=>Math.ceil(e.length/4),"estimateTokens"),at="[Summary of earlier conversation]",Ae=s(e=>e.role==="assistant"&&e.content.startsWith(at),"isSummaryTurn"),it=s(e=>e.map(t=>`${t.role}: ${t.content}`).join(`
|
|
51
|
+
`),"renderTurns"),wn=`You compress conversation history for an AI agent.
|
|
49
52
|
|
|
50
|
-
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.`,
|
|
53
|
+
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.`,bn=`You compress the execution trace of an AI agent.
|
|
51
54
|
|
|
52
|
-
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.`,
|
|
53
|
-
${
|
|
54
|
-
${
|
|
55
|
+
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.`,Ee=s(async(e,t,o={})=>{let r=ae(it(e)),n={history:e,beforeTokens:r,afterTokens:r,compacted:false},i=o.thresholdTokens??Vt/2;if(!o.force&&r<=i)return n;let l=Math.max(0,o.keepRecentTurns??4),a=e.length-l;if(a<=0)return n;let c=e.slice(0,a);if(c.length===1&&Ae(c[0]))return n;try{let p=await generateText({model:t,instructions:wn,prompt:`Conversation to summarize:
|
|
56
|
+
${it(c)}`,maxOutputTokens:o.summaryMaxTokens??1024,abortSignal:V(o.signal,o.timeoutMs??0),maxRetries:0}),g=G(p.usage);o.onUsage?.(g);let h=p.text.trim();if(!h)return {...n,usage:g};let f=[{role:"assistant",content:`${at}
|
|
57
|
+
${h}`},...e.slice(a)];return {history:f,summary:h,beforeTokens:r,afterTokens:ae(it(f)),compacted:!0,usage:g}}catch{return n}},"compactHistory"),Yt=s(async(e,t,o,r)=>{try{let n=await generateText({model:o,instructions:bn,prompt:[t?`Summary of the steps before these:
|
|
55
58
|
${t}
|
|
56
59
|
`:"",`Steps to summarize:
|
|
57
|
-
${
|
|
58
|
-
`),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:B(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:G(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:ke(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:ke(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:ke(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),ln=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),rt=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Ht(o?await o(r):ln(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Pe={version:"0.0.35"};ie.join(pn.homedir(),".agent","mcp-oauth.json");var dn=new Set(["localhost","127.0.0.1","[::1]","::1"]),Wt=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:"||dn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var fn="@dudko.dev/agent",hn=Pe.version,st,yn=s(()=>(st||(st=trace.getTracer(fn,hn)),st),"tracer"),M={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"},q=s(async(e,t,o)=>yn().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 Mn=s(e=>"command"in e&&!!e.command,"isStdioConfig"),_n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),$n=Pe.version,it=64,Ie=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),Ln=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,it-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Me=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Vt=100,Un=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Vt;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"),ue=class extends Error{static{s(this,"RefreshOnlyAbort");}},Dn=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 ue},"state"),saveCodeVerifier:s(()=>{throw new ue},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new ue},"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(Dn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof ue?`[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,a={})=>{let c=new Map,l={},p=[],d=[],T=new Map,f=s((h,u,m)=>{let x=`${Ie(h)}__`;for(let E of T.get(h)??[])delete l[E];for(let E=p.length-1;E>=0;E--)p[E].server===h&&p.splice(E,1);let R=[],N=0,P=0;for(let E of m){let b=x+Ie(E.name);if(b.length>it){t("warn",`[mcp] ${h}: tool "${E.name}" prefixed name (${b.length} chars) exceeds the ${it}-char limit enforced by major LLM providers; skipping`),P++;continue}let C=Ln(b,l);if(!C){t("warn",`[mcp] ${h}: no free name left for tool "${E.name}"; skipping`),P++;continue}C!==b&&t("warn",`[mcp] ${h}: tool name "${b}" already taken; mounted as "${C}"`);let L=E.description??"",F=E.annotations?.readOnlyHint===true;l[C]=dynamicTool({description:L,inputSchema:jsonSchema(E.inputSchema),execute:s(async(H,v)=>q("agent.tool_call",{[M.TOOL_NAME]:C},async _=>{let j=H??{};if(i)try{let I=await i(C,j);j=I&&typeof I=="object"&&!Array.isArray(I)?I:{value:I};}catch(I){t("warn",`[mcp] ${C}: inputSanitizer threw - ${I.message}; input replaced with placeholder`),j={_redacted:"inputSanitizer failed"};}let S;try{S=await u.callTool({name:E.name,arguments:j},void 0,v?.abortSignal?{signal:v.abortSignal}:void 0);}catch(I){throw _.setAttribute(M.TOOL_OK,false),I}let g=S.isError===true,w=S.content;if(n)try{w=await n(C,w);}catch(I){if(t("warn",`[mcp] ${C}: outputSanitizer threw - ${I.message}; output replaced with placeholder`),_.setAttribute(M.TOOL_OK,false),g)throw new Me("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let O=await Fn(w,{toolName:C,sandboxDir:g?void 0:Be()});if(g){_.setAttribute(M.TOOL_OK,false);let I=typeof O=="string"?O:JSON.stringify(O);throw new Me(I&&I!=="[]"?I:`MCP tool "${E.name}" reported an error with no content`)}return _.setAttribute(M.TOOL_OK,true),O}),"execute")}),F&&Z(l[C]),p.push({name:C,description:L,server:h,readOnly:F}),R.push(C),N++;}T.set(h,R),P>0?t("info",`[mcp] ${h}: ${N} tools mounted, ${P} skipped (length cap)`):t("info",`[mcp] ${h}: ${N} tools mounted`);},"mountServerTools"),y=s((h,u)=>Un(u,()=>t("warn",`[mcp] ${h}: tools/list still paginating after ${Vt} pages; the rest is ignored`)),"listServerTools"),k=s(async(h,u)=>{f(h,u,await y(h,u));},"registerServerTools"),A=s(async(h,u)=>{let m=u.connectTimeoutMs??a.connectTimeoutMs,x=typeof m=="number"&&Number.isFinite(m)&&m>=0?m:Nn,R,N=false,P=$(h,u,E=>{R=E;},()=>N);try{return await(x>0?zn(P,x,()=>{N=!0;}):P)}catch(E){R&&await R.close().catch(()=>{});let b=N?`connect timed out after ${x}ms`:E.message,C=!N&&E instanceof UnauthorizedError;return t("error",C?`[mcp] ${h}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${h}: failed to connect - ${b}`),{name:h,error:b,needsAuthorization:C}}},"openConnection"),$=s(async(h,u,m,x)=>{let R,N=s(async()=>{if(x())throw await R?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let P;if(Mn(u)){let b=u.env?{...getDefaultEnvironment(),...u.env}:void 0;P=new StdioClientTransport({command:u.command,args:u.args,env:b,cwd:u.cwd});}else if(_n(u)){if(u.headers&&u.getHeaders)throw new Error(`MCP server "${h}": specify either headers or getHeaders, not both`);let b=u.getHeaders?await u.getHeaders():u.headers;u.authProvider&&(b&&"Authorization"in b&&t("warn",`[mcp] ${h}: an explicit Authorization header shadows the OAuth token from authProvider`),Wt(u.url,`MCP server "${h}"`),await jn(u.authProvider,u.url,u.fetch,t,h)),P=new StreamableHTTPClientTransport(new URL$1(u.url),{requestInit:b?{headers:b}:void 0,authProvider:u.authProvider,fetch:u.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${h}": config must specify either { url } (HTTP) or { command } (stdio)`);P.onerror=b=>t("warn",`[mcp] ${h}: transport error - ${b.message}`),P.onclose=()=>t("warn",`[mcp] ${h}: transport closed`),await N(),R=new Client({name:o,version:$n}),m(R),await R.connect(P),await N(),r&&R.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(h);});let E=await y(h,R);return await N(),{name:h,client:R,listed:E}}catch(P){throw R&&await R.close().catch(()=>{}),P}},"connectOnce"),D=await Promise.all(Object.entries(e).map(([h,u])=>A(h,u)));for(let h of D){if(!h.client||!h.listed){d.push({name:h.name,connected:false,error:h.error,...h.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(h.name,h.client),f(h.name,h.client,h.listed),d.push({name:h.name,connected:true});}return {tools:l,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(h=>h.close()));},"close"),refreshServer:s(async h=>{let u=c.get(h);if(!u)throw new Error(`MCP server "${h}" is not connected`);await k(h,u);},"refreshServer")}},"connectMcpServers"),zn=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"),qt={image:".bin",audio:".bin",resource:".bin"},Gn=s((e,t)=>{if(!e)return qt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?qt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Kn=/[^a-zA-Z0-9_-]/g,Bt=s(async(e,t,o,n,r,i)=>{await i();let a=Gn(t,o),c=n.replace(Kn,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),p=ie.join(r,`${o}-${c}-${l}${a}`),d=Buffer.from(e,"base64");return await writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Fn=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(`
|
|
59
|
-
`);let
|
|
60
|
-
`);for(let
|
|
61
|
-
`):
|
|
60
|
+
${r.render(e,r.offset)}`].filter(Boolean).join(`
|
|
61
|
+
`),maxOutputTokens:r.summaryMaxTokens??1024,abortSignal:V(r.signal,r.timeoutMs??0),maxRetries:0}),i=n.text.trim();return i?{summary:i,usage:G(n.usage)}:void 0}catch{return}},"summarizeTrace"),Jt=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:ve(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:ve(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:ve(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),vn=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 n=>Jt(o?await o(n):vn(n.output),t),"toModelOutput")}},"withToolOutputLimit");var _e={version:"0.0.37"};le.join(In.homedir(),".agent","mcp-oauth.json");var En=new Set(["localhost","127.0.0.1","[::1]","::1"]),Xt=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:"||En.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var Rn="@dudko.dev/agent",Cn=_e.version,ct,$n=s(()=>(ct||(ct=trace.getTracer(Rn,Cn)),ct),"tracer"),M={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},B=s(async(e,t,o)=>$n().startActiveSpan(e,async r=>{for(let[n,i]of Object.entries(t))i!==void 0&&r.setAttribute(n,i);try{let n=await o(r);return r.end(),n}catch(n){let i=n instanceof Error?n:new Error(String(n));throw r.recordException(i),r.setStatus({code:SpanStatusCode.ERROR,message:i.message}),r.end(),n}}),"withSpan");var qn=s(e=>"command"in e&&!!e.command,"isStdioConfig"),Bn=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Vn=_e.version,pt=64,Oe=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),Yn=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let r=`_${o}`,n=e.slice(0,pt-r.length)+r;if(!t[n])return n}return ""},"uniqueKey"),Le=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Jn=3e4,eo=100,Xn=s(async(e,t)=>{let o=[],r,n=new Set;for(let i=0;i<eo;i++){let l=await e.listTools(r?{cursor:r}:void 0);o.push(...l.tools);let a=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!a||n.has(a))return o;n.add(a),r=a;}return t?.(),o},"listAllTools"),fe=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 fe},"state"),saveCodeVerifier:s(()=>{throw new fe},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new fe},"redirectToAuthorization")}),"refreshOnly"),Qn=s(async(e,t,o,r,n)=>{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(a){r("info",a instanceof fe?`[mcp] ${n}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${n}: proactive token refresh failed (${a.message}); continuing`);}},"refreshIfExpired"),to=s(async(e,t,o,r,n,i,l={})=>{let a=new Map,c={},p=[],g=[],h=new Map,f=s((y,b,x)=>{let N=`${Oe(y)}__`;for(let k of h.get(y)??[])delete c[k];for(let k=p.length-1;k>=0;k--)p[k].server===y&&p.splice(k,1);let P=[],u=0,m=0;for(let k of x){let v=N+Oe(k.name);if(v.length>pt){t("warn",`[mcp] ${y}: tool "${k.name}" prefixed name (${v.length} chars) exceeds the ${pt}-char limit enforced by major LLM providers; skipping`),m++;continue}let C=Yn(v,c);if(!C){t("warn",`[mcp] ${y}: no free name left for tool "${k.name}"; skipping`),m++;continue}C!==v&&t("warn",`[mcp] ${y}: tool name "${v}" already taken; mounted as "${C}"`);let $=k.description??"",U=k.annotations?.readOnlyHint===true;c[C]=dynamicTool({description:$,inputSchema:jsonSchema(k.inputSchema),execute:s(async(K,W)=>B("agent.tool_call",{[M.TOOL_NAME]:C},async I=>{let _=K??{};if(i)try{let E=await i(C,_);_=E&&typeof E=="object"&&!Array.isArray(E)?E:{value:E};}catch(E){t("warn",`[mcp] ${C}: inputSanitizer threw - ${E.message}; input replaced with placeholder`),_={_redacted:"inputSanitizer failed"};}let z;try{z=await b.callTool({name:k.name,arguments:_},void 0,W?.abortSignal?{signal:W.abortSignal}:void 0);}catch(E){throw I.setAttribute(M.TOOL_OK,false),E}let T=z.isError===true,d=z.content;if(r)try{d=await r(C,d);}catch(E){if(t("warn",`[mcp] ${C}: outputSanitizer threw - ${E.message}; output replaced with placeholder`),I.setAttribute(M.TOOL_OK,false),T)throw new Le("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let O=await nr(d,{toolName:C,sandboxDir:T?void 0:Xe()});if(T){I.setAttribute(M.TOOL_OK,false);let E=typeof O=="string"?O:JSON.stringify(O);throw new Le(E&&E!=="[]"?E:`MCP tool "${k.name}" reported an error with no content`)}return I.setAttribute(M.TOOL_OK,true),O}),"execute")}),U&&ee(c[C]),p.push({name:C,description:$,server:y,readOnly:U}),P.push(C),u++;}h.set(y,P),m>0?t("info",`[mcp] ${y}: ${u} tools mounted, ${m} skipped (length cap)`):t("info",`[mcp] ${y}: ${u} tools mounted`);},"mountServerTools"),S=s((y,b)=>Xn(b,()=>t("warn",`[mcp] ${y}: tools/list still paginating after ${eo} pages; the rest is ignored`)),"listServerTools"),A=s(async(y,b)=>{f(y,b,await S(y,b));},"registerServerTools"),w=s(async(y,b)=>{let x=b.connectTimeoutMs??l.connectTimeoutMs,N=typeof x=="number"&&Number.isFinite(x)&&x>=0?x:Jn,P,u=false,m=R(y,b,k=>{P=k;},()=>u);try{return await(N>0?er(m,N,()=>{u=!0;}):m)}catch(k){P&&await P.close().catch(()=>{});let v=u?`connect timed out after ${N}ms`:k.message,C=!u&&k instanceof UnauthorizedError;return t("error",C?`[mcp] ${y}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${y}: failed to connect - ${v}`),{name:y,error:v,needsAuthorization:C}}},"openConnection"),R=s(async(y,b,x,N)=>{let P,u=s(async()=>{if(N())throw await P?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let m;if(qn(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;m=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if(Bn(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${y}": 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] ${y}: an explicit Authorization header shadows the OAuth token from authProvider`),Xt(b.url,`MCP server "${y}"`),await Qn(b.authProvider,b.url,b.fetch,t,y)),m=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 "${y}": config must specify either { url } (HTTP) or { command } (stdio)`);m.onerror=v=>t("warn",`[mcp] ${y}: transport error - ${v.message}`),m.onclose=()=>t("warn",`[mcp] ${y}: transport closed`),await u(),P=new Client({name:o,version:Vn}),x(P),await P.connect(m),await u(),n&&P.setNotificationHandler(ToolListChangedNotificationSchema,()=>{n(y);});let k=await S(y,P);return await u(),{name:y,client:P,listed:k}}catch(m){throw P&&await P.close().catch(()=>{}),m}},"connectOnce"),j=await Promise.all(Object.entries(e).map(([y,b])=>w(y,b)));for(let y of j){if(!y.client||!y.listed){g.push({name:y.name,connected:false,error:y.error,...y.needsAuthorization?{needsAuthorization:true}:{}});continue}a.set(y.name,y.client),f(y.name,y.client,y.listed),g.push({name:y.name,connected:true});}return {tools:c,catalog:p,results:g,close:s(async()=>{await Promise.allSettled([...a.values()].map(y=>y.close()));},"close"),refreshServer:s(async y=>{let b=a.get(y);if(!b)throw new Error(`MCP server "${y}" is not connected`);await A(y,b);},"refreshServer")}},"connectMcpServers"),er=s((e,t,o)=>new Promise((r,n)=>{let i=setTimeout(()=>{o(),n(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),r(l);},l=>{clearTimeout(i),n(l);});}),"withConnectTimeout"),Zt={image:".bin",audio:".bin",resource:".bin"},tr=s((e,t)=>{if(!e)return Zt[t];let o=e.indexOf("/"),n=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !n||/[^a-z0-9.+-]/.test(n)?Zt[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"}[n]??`.${n.replace(/\+/g,"-")}`},"extFromMime"),or=/[^a-zA-Z0-9_-]/g,Qt=s(async(e,t,o,r,n,i)=>{await i();let l=tr(t,o),a=r.replace(or,"_").slice(0,32)||"tool",c=randomUUID().slice(0,8),p=le.join(n,`${o}-${a}-${c}${l}`),g=Buffer.from(e,"base64");return await writeFile(p,g),{type:"file",kind:o,path:p,mimeType:t,bytes:g.byteLength}},"spillBase64"),nr=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(`
|
|
62
|
+
`);let n=t?.sandboxDir,i=t?.toolName??"tool",l,a=s(()=>n?(l||(l=mkdir(n,{recursive:true}).then(()=>{})),l):Promise.resolve(),"ensureDir"),c=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){c.push(p.text);continue}if(n&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let g=await Qt(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,i,n,a);c.push(g);continue}if(n&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let g=p.resource;if(typeof g.blob=="string"){let h=await Qt(g.blob,typeof g.mimeType=="string"?g.mimeType:void 0,"resource",i,n,a);typeof g.uri=="string"&&(h.uri=g.uri),c.push(h);continue}if(typeof g.text=="string"){c.push(g.text);continue}}c.push(p);}return c},"flattenContent"),ut=s((e,t,o,r,n)=>{let i=o?.length?new Set(o.map(Oe)):null,l=r?.length?new Set(r.map(Oe)):null,a=new Set,c={},p=[];for(let g of t){if((i?.has(g.name)||l?.has(g.name))&&a.add(g.name),i&&!i.has(g.name)||!i&&l?.has(g.name))continue;let h=e[g.name];h&&(c[g.name]=h,p.push(g));}if(n)for(let[g,h]of [["availableTools",o],["excludedTools",r]])for(let f of h??[])a.has(Oe(f))||n("warn",`[mcp] ${g}: "${f}" matches no discovered tool`);return {tools:c,catalog:p}},"filterTools");var Ne=s((e,t,o,r)=>{let n=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,l=t?.baseURL??e.baseURL,a=t?.model??o??e.model,c=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${r}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${r}.apiKey (cross-provider key inheritance is unsafe)`);if(rr.has(n)&&!l)throw new Error(`${r}: provider "${n}" requires a baseURL (set ${r}.baseURL or the top-level baseURL)`);return {providerType:n,baseURL:l,apiKey:i,model:a,providerOptions:c}},"resolveStage"),rr=new Set(["openai-compatible","azure"]),X={openai:"@ai-sdk/openai",anthropic:"@ai-sdk/anthropic",google:"@ai-sdk/google","openai-compatible":"@ai-sdk/openai-compatible",xai:"@ai-sdk/xai",azure:"@ai-sdk/azure","amazon-bedrock":"@ai-sdk/amazon-bedrock","google-vertex":"@ai-sdk/google-vertex",deepseek:"@ai-sdk/deepseek",cloudflare:"workers-ai-provider"},Z=s(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),Ue=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:r}=await Z(X.openai);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:r}=await Z(X.anthropic);return r({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:r}=await Z(X["openai-compatible"]);return r({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:r}=await Z(X.google);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:r}=await Z(X.xai);return r({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:r}=await Z(X.azure);return r({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:r}=await Z(X["amazon-bedrock"]);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:r}=await Z(X["google-vertex"]);return r({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:r}=await Z(X.deepseek);return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:r}=await import('ai');return r({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let n=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...l}=o;if(!n&&!("binding"in l))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:a}=await Z(X.cloudflare),c="binding"in l?l:{accountId:n,apiKey:t.apiKey,...l};return a(c)(t.model)}}},"buildModelFromStage");var oo=new WeakMap,no=s(e=>{if(!e)return;let t=oo.get(e);if(!t)throw new TypeError("`control` must be created with createRunControl()");return t},"portOf"),dt=s(()=>{let e=0,t=[],o,r=false,n=new Map,i={send(l){let a=typeof l=="string"?l.trim():"";if(!a||r)return false;let c={id:`msg-${e+=1}`,text:a};return t.push(c),o?.({type:"message.queued",id:c.id,text:c.text}),true},pending:s(()=>t.map(l=>l.text),"pending"),subagents:s(()=>[...n.values()].map(l=>l.info).sort((l,a)=>l.startedAt-a.startedAt),"subagents"),stopSubagent(l){let a=n.get(l);return a?(a.stop(),true):false}};return oo.set(i,{attach(l){r&&(t=[],n.clear()),o=l,r=false;for(let a of t)l({type:"message.queued",id:a.id,text:a.text});},detach(){return o=void 0,r=true,n.clear(),t.map(l=>l.text)},drain(){let l=t;return t=[],l},registerSubagent(l,a){return n.set(l.id,{info:l,stop:a}),()=>{n.delete(l.id);}}}),i},"createRunControl");var sr=s(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((r,n)=>r.type==="tool-result"?[`${o}:${n}`]:[]):[]),"positionsOf"),ir=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),ro=s(e=>{try{return ae(JSON.stringify(e))}catch{return 0}},"estimate"),mt=s((e,t)=>{let o=Math.max(0,e.keep??3),r=new Set,n=s(i=>r.size===0?i:i.map((l,a)=>l.role==="tool"&&Array.isArray(l.content)?{...l,content:l.content.map((c,p)=>c.type==="tool-result"&&r.has(`${a}:${p}`)?{...c,output:{type:"text",value:ir(c.toolName)}}:c)}:l),"apply");return i=>{let l=n(i),a=ro(l);if(a<=e.triggerTokens)return l;let c=sr(i),p=0;for(let h of c.slice(0,Math.max(0,c.length-o)))r.has(h)||(r.add(h),p+=1);if(p===0)return l;let g=n(i);return t?.({cleared:p,beforeTokens:a,afterTokens:ro(g)}),g}},"createToolResultClearer");var io=/^[a-z0-9-]{1,64}$/,lr="load_skill",cr="read_skill_file",pr=24e3,co=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"),gt=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:r,files:n}=e;if(typeof t!="string"||!io.test(t))throw new Error(`skill name must match ${io} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof r!="string")throw new Error(`skill "${t}": content must be a string`);if(n!==void 0&&!Array.isArray(n))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,l=(n??[]).map(a=>{if(!a||typeof a.path!="string"||typeof a.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let c;try{c=co(a.path);}catch(p){throw new Error(`skill "${t}": ${p.message}`)}if(i.has(c))throw new Error(`skill "${t}": duplicate file "${c}"`);return i.add(c),{path:c,content:a.content}});return {name:t,description:o.trim(),content:r,...l.length?{files:l}:{}}},"defineSkill"),ur=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"),dr=s(e=>{let t={},o=e.split(`
|
|
63
|
+
`);for(let r=0;r<o.length;r++){let n=o[r],i=/^([A-Za-z0-9_-]+)\s*:(.*)$/.exec(n);if(!i)continue;let l=i[1],a=i[2].trim(),c=/^([>|])([+-]?)\s*(#.*)?$/.exec(a);if(c){let p=[];for(;r+1<o.length&&(/^\s/.test(o[r+1])||o[r+1].trim()==="");)p.push(o[++r]);for(;p.length&&p[p.length-1].trim()==="";)p.pop();let g=Math.min(...p.filter(f=>f.trim()).map(f=>/^\s*/.exec(f)[0].length)),h=p.map(f=>f.slice(Number.isFinite(g)?g:0));t[l]=c[1]==="|"?h.join(`
|
|
64
|
+
`):h.join(`
|
|
62
65
|
`).split(/\n\s*\n/).map(f=>f.replace(/\n/g," ").trim()).join(`
|
|
63
|
-
`);continue}t[
|
|
64
|
-
`),
|
|
65
|
-
`),"renderSkillsIndex"),
|
|
66
|
-
${
|
|
67
|
-
\u2026 [skill instructions clipped: budget exhausted]`);continue}if(
|
|
68
|
-
\u2026 [skill instructions clipped]`),i=o;continue}
|
|
69
|
-
|
|
70
|
-
`)},"renderActiveSkills"),
|
|
71
|
-
`)},"renderSearchCatalog"),
|
|
72
|
-
`)},"renderHistory"),
|
|
73
|
-
`)},"renderToolCatalog"),
|
|
66
|
+
`);continue}t[l]=ur(a);}return t},"parseFrontmatter"),po=s((e,t)=>{let o=e.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
67
|
+
`),r=/^\s*---[ \t]*\n([\s\S]*?)\n---[ \t]*(?:\n|$)/.exec(o);if(!r)throw new Error('SKILL.md must start with a frontmatter block between "---" lines');let n=dr(r[1]);if(!n.name)throw new Error('SKILL.md frontmatter is missing "name"');if(!n.description)throw new Error(`SKILL.md "${n.name}": frontmatter is missing "description"`);return gt({name:n.name,description:n.description,content:o.slice(r[0].length).trim(),...t?.length?{files:t}:{}})},"parseSkillMarkdown"),mr=new Set([".md",".txt",".json",".yaml",".yml",".csv",".ts",".js",".py",".sh",".html",".css",".xml",".toml"]),gr=256*1024,uo=s(async(e,t,o)=>{let r=await readdir(t,{withFileTypes:true});r.sort((n,i)=>n.name.localeCompare(i.name));for(let n of r){if(n.name.startsWith(".")||n.name==="node_modules")continue;let i=le.join(t,n.name);if(n.isDirectory()){await uo(e,i,o);continue}if(!n.isFile())continue;let l=le.relative(e,i).split(le.sep).join("/");l==="SKILL.md"||!mr.has(le.extname(n.name).toLowerCase())||(await stat(i)).size>gr||o.push({path:l,content:await readFile(i,"utf8")});}},"collectFiles"),ft=s(async e=>{let t=await readdir(e,{withFileTypes:true});t.sort((n,i)=>n.name.localeCompare(i.name));let o=[],r=new Set;for(let n of t){if(!n.isDirectory()||n.name.startsWith(".")||n.name==="node_modules")continue;let i=le.join(e,n.name),l;try{l=await readFile(le.join(i,"SKILL.md"),"utf8");}catch{continue}let a=[];await uo(i,i,a);let c;try{c=po(l,a);}catch(p){throw new Error(`${le.join(i,"SKILL.md")}: ${p.message}`)}if(r.has(c.name))throw new Error(`duplicate skill name "${c.name}" in ${e}`);r.add(c.name),o.push(c);}return o},"loadSkillsFromDir"),mo=s(e=>{let t=[],o=new Set;for(let r of e??[]){let n=gt(r);if(o.has(n.name))throw new Error(`duplicate skill name "${n.name}"`);o.add(n.name),t.push(n);}return t},"validateSkills"),fr=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}: ${fr(t.description,300)}`).join(`
|
|
68
|
+
`),"renderSkillsIndex"),go=s((e,t,o=pr)=>{let r=new Map(e.map(l=>[l.name,l])),n=[],i=0;for(let l of t){let a=r.get(l);if(!a)continue;let c=`### Skill: ${a.name}
|
|
69
|
+
${a.content.trim()}`,p=o-i;if(p<=0){n.push(`### Skill: ${a.name}
|
|
70
|
+
\u2026 [skill instructions clipped: budget exhausted]`);continue}if(c.length>p){n.push(`${c.slice(0,p)}
|
|
71
|
+
\u2026 [skill instructions clipped]`),i=o;continue}n.push(c),i+=c.length;}return n.join(`
|
|
72
|
+
|
|
73
|
+
`)},"renderActiveSkills"),yt=s((e,t,o,r,n)=>e.some(i=>i.name===t)?(r&&!r.activeSkills.includes(t)&&(r.activeSkills.push(t),n?.({type:"skill.activated",name:t,by:o})),true):false,"activateSkill"),fo=s(e=>{if(!e.length)return {};let t=e.map(r=>r.name),o=s(r=>{let n=e.find(i=>i.name===r);if(!n)throw new Error(`Unknown skill "${r}". Available skills: ${t.join(", ")}`);return n},"find");return {[lr]:ee(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:r})=>{let n=o(r),i=F.getStore();return yt(e,n.name,"tool",i?.state,i?.emit),{name:n.name,content:n.content,files:(n.files??[]).map(l=>l.path)}},"execute")})),[cr]:ee(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:r,path:n})=>{let i=o(r),l;try{l=co(n);}catch(c){throw new Error(c.message)}let a=(i.files??[]).find(c=>c.path===l);if(!a){let c=(i.files??[]).map(p=>p.path);throw new Error(`Skill "${i.name}" has no file "${n}". Files: ${c.length?c.join(", "):"(none)"}`)}return a.content},"execute")}))}},"createSkillTools");var te="find_tools",yr=40,Tr=8,kr=20,ze=s((e,t)=>{let o=e.toolSelectionStrategy??"auto";if(o==="auto"){let r=e.toolSearchThreshold??yr;return t>r?"search":"all"}return o},"resolveToolStrategy"),je=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"),yo=s((e,t,o={})=>{let r=[...new Set(je(t))];if(r.length===0)return [];let n=Math.floor(o.limit??Tr),i=Math.min(kr,Math.max(1,Number.isFinite(n)?n:8)),l=o.server?.trim().toLowerCase(),a=[];return e.forEach((c,p)=>{if(l&&(c.server??"").toLowerCase()!==l)return;let g=je(c.name),h=je(c.server??""),f=je(c.description??""),S=0;for(let A of r)S+=(Tt(g,A)?3:0)+(Tt(h,A)?2:0)+(Tt(f,A)?1:0);S>0&&a.push({entry:c,score:S,index:p});}),a.sort((c,p)=>p.score-c.score||c.index-p.index),a.slice(0,i).map(c=>c.entry)},"searchTools"),wr=12e3,br=60,To=s((e,t=wr)=>{if(e.length===0)return "(no tools available)";let o=new Map;for(let a of e){let c=a.server??"<native>",p=o.get(c)??[];p.push(a),o.set(c,p);}let r=[],n=0,i=0;e:for(let[a,c]of o){let p=`[${a}]`;if(n+p.length+1>t)break;r.push(p),n+=p.length+1;for(let g of c){let h=(g.description||"").replace(/\s+/g," ").trim().slice(0,br),f=`- ${g.name}: ${h}`;if(n+f.length+1>t)break e;r.push(f),n+=f.length+1,i++;}}let l=e.length-i;return l>0&&r.push(`\u2026 ${l} more tools \u2014 the executor can find them with ${te}`),r.join(`
|
|
74
|
+
`)},"renderSearchCatalog"),ko=s(e=>({[te]:ee(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:r})=>{let n=yo(e(),t,{server:o,limit:r}),i=n.map(c=>c.name),l=F.getStore(),a=l?.state;if(a)for(let c of i){let p=a.discovered.indexOf(c);p>=0&&a.discovered.splice(p,1),a.discovered.push(c),a.stepActive?.add(c);}return l?.emit&&l.currentStep&&l.emit({type:"tools.discovered",step:l.currentStep,query:t,names:i}),{tools:n.map(c=>({name:c.name,description:c.description,server:c.server??"<native>",readOnly:c.readOnly===true}))}},"execute")}))}),"createFindToolsTool");var wo=1500,bo=6e3,wt=s(e=>{if(!e?.length)return "(no prior conversation)";let t=Ae(e[0])?e[0]:void 0,o=t?e.slice(1):e,r=o.slice(-8),n=o.length-r.length,i=[];if(t){let l=t.content.length>bo?`${t.content.slice(0,bo)}... [truncated]`:t.content;i.push(`${t.role}: ${l}`);}n>0&&i.push(`(${n} earlier turns omitted)`);for(let l of r){let a=l.content.length>wo?`${l.content.slice(0,wo)}... [truncated]`:l.content;i.push(`${l.role}: ${a}`);}return i.join(`
|
|
75
|
+
`)},"renderHistory"),Sr={full:{tools:80,descChars:240},compact:{tools:200,descChars:80}},Ir=s((e,t="full")=>{if(e.length===0)return "(no tools available)";let{tools:o,descChars:r}=Sr[t],n=e.slice(0,o),i=e.length-n.length,l=n.map(a=>{let c=(a.description||"").replace(/\s+/g," ").trim().slice(0,r);return `- ${a.name}: ${c}`});return i>0&&l.push(`... and ${i} more tools`),l.join(`
|
|
76
|
+
`)},"renderToolCatalog"),vo=s((e,t)=>t==="search"?To(e):Ir(e,t),"renderCatalogFor"),kt=1500,Ar=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"),Er=s((e,t)=>{let o=e.toolCalls.length?e.toolCalls.map(r=>` - ${r.name} ${r.ok?"ok":"fail"}: ${Ar(r.output)}`).join(`
|
|
74
77
|
`):" (no tool calls)";return [`Step ${t+1}: ${e.step.description}`,` Result: ${e.summary}`," Tool calls:",o].join(`
|
|
75
|
-
`)},"renderTraceEntry"),
|
|
76
|
-
`),"renderTraceSteps"),
|
|
77
|
-
`)},"renderTrace"),
|
|
78
|
+
`)},"renderTraceEntry"),Ge=s((e,t=0)=>e.map((o,r)=>Er(o,t+r)).join(`
|
|
79
|
+
`),"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 Ge(e);let r=[`Summary of earlier steps (1-${o}): ${t.summary}`];return o<e.length&&r.push(Ge(e.slice(o),o)),r.join(`
|
|
80
|
+
`)},"renderTrace"),bt=s(e=>[`Plan thought: ${e.thought}`,"Steps:",...e.steps.map((t,o)=>` ${o+1}. [${t.id}] ${t.description}
|
|
78
81
|
expected: ${t.expectedOutcome}`+(t.suggestedTools?.length?`
|
|
79
82
|
suggested tools: ${t.suggestedTools.join(", ")}`:""))].join(`
|
|
80
|
-
`),"renderPlan"),
|
|
83
|
+
`),"renderPlan"),Ke=s((e,t)=>t?`${e}
|
|
81
84
|
|
|
82
85
|
Domain context:
|
|
83
|
-
${t}`:e,"withDomainContext"),
|
|
86
|
+
${t}`:e,"withDomainContext"),Fe=8,So=s(e=>`You are the Planner of a multi-step agent system.
|
|
84
87
|
|
|
85
88
|
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.
|
|
86
89
|
|
|
@@ -91,50 +94,58 @@ Rules:
|
|
|
91
94
|
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.
|
|
92
95
|
5. The last step must produce the deliverable for the user (do not append a separate "summarize" step - the system synthesizes the final answer).
|
|
93
96
|
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.
|
|
94
|
-
7. Output strict JSON matching the requested schema. No prose outside JSON.`,"plannerBase");
|
|
97
|
+
7. Output strict JSON matching the requested schema. No prose outside JSON.`,"plannerBase");So(Fe);var Or=`
|
|
95
98
|
|
|
96
99
|
ADDITIONAL RULE (tool-narrowed mode):
|
|
97
|
-
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.`,
|
|
100
|
+
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=`
|
|
98
101
|
|
|
99
102
|
ADDITIONAL RULE (tool-search mode):
|
|
100
|
-
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 ${
|
|
103
|
+
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 ${te}. Never invent names.`,Rr=`
|
|
101
104
|
|
|
102
105
|
SKILL SELECTION:
|
|
103
|
-
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.`,
|
|
106
|
+
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.`,Cr=s((e,t=Fe)=>So(t)+(e==="compact"?Or:e==="search"?xr:""),"buildPlannerSystem"),$r=s(e=>e?.length?`
|
|
104
107
|
|
|
105
108
|
SKILLS:
|
|
106
|
-
${
|
|
109
|
+
${ht(e)}`:"","skillsIndexSection"),vt=s((e,t)=>{if(!e?.length||!t?.length)return "";let o=go(e,t);return o?`
|
|
107
110
|
|
|
108
111
|
ACTIVE SKILLS (follow these instructions where they apply):
|
|
109
112
|
|
|
110
|
-
${o}`:""},"activeSkillsSection"),
|
|
113
|
+
${o}`:""},"activeSkillsSection"),Io=s(e=>Ke(Cr(e.mode,e.maxSteps)+(e.skills?.length?Rr:""),e.domain)+$r(e.skills)+`
|
|
111
114
|
|
|
112
115
|
Available tools:
|
|
113
|
-
${
|
|
114
|
-
${
|
|
116
|
+
${vo(e.catalog,e.mode)}`,"composePlannerSystem"),Ao=s((e,t)=>[t?.length?`Conversation history:
|
|
117
|
+
${wt(t)}
|
|
115
118
|
`:"",`User request:
|
|
116
119
|
${e}`,"","Produce the plan now."].filter(Boolean).join(`
|
|
117
|
-
`),"buildPlannerUserPrompt"),
|
|
120
|
+
`),"buildPlannerUserPrompt"),Pr=`You are the Executor of a multi-step agent system. You receive ONE step at a time and you must accomplish only that step.
|
|
118
121
|
|
|
119
122
|
Rules:
|
|
120
123
|
1. Stay focused on the CURRENT step. Do not jump ahead, do not redo finished steps.
|
|
121
124
|
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.
|
|
122
125
|
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.
|
|
123
126
|
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.
|
|
124
|
-
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,
|
|
127
|
+
5. Be concise. Do not narrate your reasoning at length - the Replanner reads only your final summary.`,Mr=`
|
|
125
128
|
|
|
126
129
|
TOOLS:
|
|
127
|
-
Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${
|
|
130
|
+
Only part of the tool catalogue is loaded. When you need a capability that is not among your tools, call ${te} with a few keywords; the matching tools become callable from your next step on.`,_r=`
|
|
128
131
|
|
|
129
132
|
SKILLS:
|
|
130
|
-
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.`,
|
|
131
|
-
${
|
|
132
|
-
|
|
133
|
+
Packaged instructions for specific kinds of work. When one of these applies to the current step and is not active yet, call load_skill with its name before doing the work; read_skill_file reads files it bundles.`,Eo=s(e=>Ke(Pr,e.domain)+(e.skills?.length?`${_r}
|
|
134
|
+
${ht(e.skills)}`:"")+(e.searchMode?`${Mr}${e.toolCount?` The catalogue has ${e.toolCount} tools.`:""}`:"")+vt(e.skills,e.activeSkills),"composeExecutorSystem"),Oo=s(e=>e.trim().replace(/\n/g,`
|
|
135
|
+
`),"quoted"),St=s((e,t=0,o="")=>{if(!e||e.length===0)return "";let r=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):
|
|
136
|
+
${e.map((l,a)=>`${a+1}. ${Oo(l)}${a>=r?" [NEW - not yet reflected in the plan]":""}`).join(`
|
|
137
|
+
`)}`;return o?`${i}
|
|
138
|
+
${o}`:i},"renderUserUpdates"),Lr='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.',Nr="Answer with these in mind: they changed what was asked. Say plainly if one of them could not be honoured in time.",xo=s(e=>`NEW MESSAGE FROM THE USER, sent while you were working:
|
|
139
|
+
${e.map(t=>`- ${Oo(t)}`).join(`
|
|
140
|
+
`)}
|
|
141
|
+
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"),Ro=s((e,t,o,r,n,i,l)=>[n?.length?`Conversation history:
|
|
142
|
+
${wt(n)}
|
|
133
143
|
`:"",`Original user request:
|
|
134
|
-
${e}`,
|
|
135
|
-
${
|
|
136
|
-
${
|
|
137
|
-
|
|
144
|
+
${e}`,l?.length?`
|
|
145
|
+
${St(l)}`:"","",`Overall plan:
|
|
146
|
+
${bt(t)}`,"",`Trace so far:
|
|
147
|
+
${he(r,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(`
|
|
148
|
+
`),"buildExecutorUserPrompt"),Ur=`You are the Replanner of an autonomous multi-step agent system. After an Executor step you decide what should happen next.
|
|
138
149
|
|
|
139
150
|
You have three options:
|
|
140
151
|
- "continue": the next planned step is still appropriate.
|
|
@@ -147,14 +158,15 @@ Rules:
|
|
|
147
158
|
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.
|
|
148
159
|
4. Never revise into a step that asks the user for input, clarification or permission - the agent runs autonomously.
|
|
149
160
|
5. When revising, the new plan must NOT repeat already-completed work; it covers only what is still needed.
|
|
150
|
-
6. Output strict JSON matching the schema. No prose outside JSON.`,
|
|
161
|
+
6. Output strict JSON matching the schema. No prose outside JSON.`,Co=s(e=>Ke(Ur,e.domain)+`
|
|
151
162
|
|
|
152
163
|
Available tools (for the revise option):
|
|
153
|
-
${
|
|
154
|
-
${e}`,
|
|
155
|
-
${
|
|
156
|
-
${
|
|
157
|
-
|
|
164
|
+
${vo(e.catalog,e.mode)}`+vt(e.skills,e.activeSkills),"composeReplannerSystem"),$o=s((e,t,o,r,n,i,l=0)=>[`Original user request:
|
|
165
|
+
${e}`,i?.length?`
|
|
166
|
+
${St(i,l,Lr)}`:"","",`Current plan:
|
|
167
|
+
${bt(t)}`,"",`Completed steps:
|
|
168
|
+
${he(o,n)}`,"",r?`Next planned step: [${r.id}] ${r.description}`:"There is no next step in the current plan.","","Decide now: continue, revise, or finish."].join(`
|
|
169
|
+
`),"buildReplannerUserPrompt"),Dr=`You are the Synthesizer. Produce the final answer for the user from the agent's plan and execution trace.
|
|
158
170
|
|
|
159
171
|
Rules:
|
|
160
172
|
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.
|
|
@@ -162,28 +174,38 @@ Rules:
|
|
|
162
174
|
3. Mention the assumptions the agent made, briefly.
|
|
163
175
|
4. If the trace shows the request (or part of it) could not be completed, say so plainly and explain what blocked it.
|
|
164
176
|
5. Do not end with questions or offers unless the request genuinely cannot be completed without input from the user.
|
|
165
|
-
6. Use the user's language.`,
|
|
166
|
-
${
|
|
177
|
+
6. Use the user's language.`,Po=s(e=>Ke(Dr,e.domain)+vt(e.skills,e.activeSkills),"composeSynthesizerSystem"),Mo=s((e,t,o,r,n,i)=>[r?.length?`Conversation history:
|
|
178
|
+
${wt(r)}
|
|
167
179
|
`:"",`User request:
|
|
168
|
-
${e}`,
|
|
169
|
-
${
|
|
170
|
-
${
|
|
171
|
-
`),"buildSynthesizerUserPrompt");var Ir=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")}),Ar=ze,Tt=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(Ir).min(1),skills:z.array(z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),Ge=s(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):Ar},"planStepCap"),me=s(e=>{if(e.run)return e.run.strategy;let t=Ue(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"effectiveToolStrategy"),kt=s(e=>e==="plan-narrowed"?"compact":e==="search"?"search":"full","catalogModeFor"),wt=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)=>q("agent.plan",{[M.PHASE]:"plan"},async r=>{let i=new Set(o.toolCatalog.map(f=>f.name)),a=kt(me(o)),c=Ge(o),{object:l,usage:p}=await te(()=>Er(e,t,a,o,n),{maxRetries:o.config.llmMaxRetries??2,signal:n,onRetry:s((f,y)=>o.emit({type:"retry",phase:"plan",attempt:f,error:y.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:p}),r.setAttribute(M.USAGE_TOTAL_TOKENS,p.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 T=wt(o,l.skills);return {thought:l.thought,...T?{skills:T}:{},steps:d.map(f=>{if(!f.suggestedTools?.length)return f;let y=f.suggestedTools.filter(A=>i.has(A)),k=f.suggestedTools.length-y.length;return k>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${f.id}" had ${k} unknown suggestedTools, stripped`}),y.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${f.id}" had no valid suggestedTools left; falling back to full toolset`}),{...f,suggestedTools:void 0,requiresTools:true}):{...f,suggestedTools:y}})}}),"createInitialPlan"),Er=s(async(e,t,o,n,r)=>{let i=ne(n.config,"planner",ho({mode:o,catalog:n.toolCatalog,maxSteps:Ge(n),domain:n.config.systemPrompt,skills:n.skills})),a=streamObject({model:n.plannerModel,schema:Tt,...i,prompt:yo(e,t),abortSignal:B(r,n.config.llmTimeoutMs??0)}),c="",l=false,p=0;for await(let f of a.partialObjectStream){let y=f?.thought;typeof y=="string"&&y!==c&&(y.startsWith(c)?n.emit({type:"plan.thought-delta",delta:y.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=y);let k=f?.steps;if(Array.isArray(k)&&k.length>p)for(;p<k.length;){let A=k[p];if(!A||typeof A.description!="string"||!A.description.length)break;let $={id:typeof A.id=="string"&&A.id?A.id:`s${p+1}`,description:A.description,expectedOutcome:typeof A.expectedOutcome=="string"?A.expectedOutcome:"",suggestedTools:Array.isArray(A.suggestedTools)?A.suggestedTools.filter(D=>typeof D=="string"):void 0};n.emit({type:"plan.step-added",step:$,index:p}),p++;}}let[d,T]=await Promise.all([a.object,a.usage]);return {object:d,usage:G(T)}},"streamPlanOnce");var Rr=s((e,t)=>{if(me(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]",Cr=s(e=>e.includes(Ao)?{summary:e.split(Ao).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),vt=4e3,Pr=s(e=>e.length>vt?`${e.slice(0,vt)}... [truncated, ${e.length-vt} chars]`:e,"truncateForTrace"),Eo=s(async(e,t,o,n,r,i,a)=>q("agent.execute_step",{[M.PHASE]:"execute",[M.STEP_ID]:o.id},async c=>{let l=Date.now(),p=await te(()=>_r(e,t,o,n,r,i,a),{maxRetries:i.config.llmMaxRetries??2,signal:a,onRetry:s((d,T)=>i.emit({type:"retry",phase:"execute",attempt:d,error:T.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:p.usage}),c.setAttribute(M.USAGE_TOTAL_TOKENS,p.usage.totalTokens),c.setAttribute(M.STEP_BLOCKED,p.blocked),c.setAttribute(M.TOOL_COUNT,p.toolCalls.length),{step:o,summary:p.summary,toolCalls:p.toolCalls,durationMs:Date.now()-l,blocked:p.blocked}}),"executeStep"),Mr=s((e,t)=>{let o=me(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=Rr(e,t),i=Object.keys(n).length?{...r,...n}:r;return o==="plan-narrowed"?{tools:i,activeTools:Object.keys(i)}:{tools:i}},"buildExecutorTools"),_r=s(async(e,t,o,n,r,i,a)=>{let c=[],l=new Map,{tools:p,activeTools:d,active:T}=Mr(i,o),f=i.run;f&&(f.stepActive=T);let y=s(async(v,_)=>{let j=i.config.inputSanitizer;if(!j)return _;try{return await j(v,_)}catch(S){return i.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${v} - ${S.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),k,A=[stepCountIs(i.config.maxStepsPerTask)],$=oe(i.config);f&&Nt($)&&A.push(Ut(()=>f.usage,$,()=>{k="tokens";}));let D=i.config.maxToolCalls;f&&typeof D=="number"&&D>0&&A.push(()=>f.toolCalls>=D?(k??="tool-calls",true):false);let h=ne(i.config,"executor",To({domain:i.config.systemPrompt,skills:i.skills,activeSkills:f?.activeSkills,searchMode:!!T,toolCount:i.toolCatalog.length})),u=Ce(i.config,"executor"),m=f?{summary:f.traceSummary,upTo:f.traceSummaryUpTo}:void 0,x=he(i.config.promptCaching),R=pe(i.config.compaction),N=R.clearToolResultsAfterTokens>0?lt({triggerTokens:R.clearToolResultsAfterTokens,keep:R.keepToolResults},v=>{i.emit({type:"log",level:"info",message:`[executor] cleared ${v.cleared} stale tool result(s) from the step's context`}),i.emit({type:"context.compacted",scope:"tool-results",beforeTokens:v.beforeTokens,afterTokens:v.afterTokens});}):void 0,P=x.enabled||!!N,E=streamText({model:i.executorModel,tools:p,...d?{activeTools:d}:{},...T||P?{prepareStep:s(({messages:v})=>{let _=Je(N?N(v):v,x);return {...T?{activeTools:[...T].filter(j=>j in p)}:{},...P?{messages:_}:{}}},"prepareStep")}:{},stopWhen:A,...h,prompt:ko(e,t,o,n,r,m),abortSignal:B(a,i.config.llmTimeoutMs??0)});for await(let v of E.fullStream)switch(v.type){case "text-delta":v.text&&i.emit({type:"step.text-delta",step:o,delta:v.text});break;case "reasoning-delta":v.text&&u&&i.emit({type:"step.reasoning-delta",step:o,delta:v.text});break;case "tool-call":{let _=await y(v.toolName,v.input);l.set(v.toolCallId,{name:v.toolName,input:_}),i.emit({type:"step.tool-call",step:o,name:v.toolName,input:_});break}case "tool-result":{if(v.preliminary)break;let j=l.get(v.toolCallId)?.input??await y(v.toolName,v.input);c.push({name:v.toolName,input:j,output:v.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:v.toolName,output:v.output,ok:true}),l.delete(v.toolCallId);break}case "tool-error":{let j=l.get(v.toolCallId)?.input??await y(v.toolName,v.input);c.push({name:v.toolName,input:j,output:v.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:v.toolName,output:v.error,ok:false}),l.delete(v.toolCallId);break}case "error":{let _=v.error;throw _ instanceof Error?_:new Error(String(_))}}let[b,C]=await Promise.all([E.text,E.usage]),{summary:L,blocked:F}=Cr(b.trim());return {summary:L.length>0?Pr(L):k?`Stopped early: the run's ${k==="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:F,usage:C?G(C):ce()}},"runOnce");var Lr=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:Tt.describe("Plan covering ONLY the remaining work")})]),Oo=s(async(e,t,o,n,r,i)=>q("agent.replan",{[M.PHASE]:"replan"},async a=>{let c=kt(me(r)),l=r.run?{summary:r.run.traceSummary,upTo:r.run.traceSummaryUpTo}:void 0,{object:p,usage:d}=await te(async()=>{let T=ne(r.config,"replanner",wo({mode:c,catalog:r.toolCatalog,domain:r.config.systemPrompt,skills:r.skills,activeSkills:r.run?.activeSkills})),f=await generateObject({model:r.plannerModel,schema:Lr,...T,prompt:vo(e,t,o,n,l),abortSignal:B(i,r.config.llmTimeoutMs??0)}),y=G(f.usage);return {object:f.object,usage:y}},{maxRetries:r.config.llmMaxRetries??2,signal:i,onRetry:s((T,f)=>r.emit({type:"retry",phase:"replan",attempt:T,error:f.message}),"onRetry")});return r.emit({type:"usage",phase:"replan",usage:d}),a.setAttribute(M.REPLAN_MODE,p.mode),a.setAttribute(M.USAGE_TOTAL_TOKENS,d.totalTokens),p}),"decideNextAction");var xo=s(async(e,t,o,n,r,i)=>q("agent.synthesize",{[M.PHASE]:"synthesize"},async a=>{let{text:c,usage:l}=await te(()=>Ur(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:l}),a.setAttribute(M.USAGE_TOTAL_TOKENS,l.totalTokens),c}),"synthesizeAnswer"),Ur=s(async(e,t,o,n,r,i)=>{let a=ne(r.config,"synthesizer",So({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=Ce(r.config,"synthesizer"),p=streamText({model:r.synthesizerModel,...a,prompt:bo(e,t,o,n,c),abortSignal:B(i,r.config.llmTimeoutMs??0)});for await(let f of p.fullStream)if(f.type==="text-delta")f.text&&r.emit({type:"final.text-delta",delta:f.text});else if(f.type==="reasoning-delta")f.text&&l&&r.emit({type:"final.reasoning-delta",delta:f.text});else if(f.type==="error"){let y=f.error;throw y instanceof Error?y:new Error(String(y))}let[d,T]=await Promise.all([p.text,p.usage]);return {text:d,usage:G(T)}},"streamOnce");var Co=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"),Gr=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return Co(t);let n=s(()=>Co(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 p=false,d,T=s(y=>{p||(p=true,d!==void 0&&clearTimeout(d),r?.removeEventListener("abort",f),l(y));},"finish");function f(){T(n());}s(f,"onAbort"),c&&(d=setTimeout(()=>T(n()),i)),r?.addEventListener("abort",f,{once:true}),a.then(T,()=>T(n()));})},"replanTriggered"),Ke=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),Kr=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||ie.join(tmpdir(),"agent-sandbox");return ie.join(o,t)},"resolveSandboxDir"),Po=/^[a-zA-Z0-9_-]{1,128}$/,St=s((e,t)=>{if(!Po.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Po}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),Fr=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(St(t.resumeFromRunId,"options.resumeFromRunId"),!e.config.persistence?.loadRun)throw new Error("resumeFromRunId requires config.persistence.loadRun to be implemented");let o=await e.config.persistence.loadRun(t.resumeFromRunId);if(!o)throw new Error(`No persisted run found for runId "${t.resumeFromRunId}"`);if(St(o.runId,"snapshot.runId"),o.runId!==t.resumeFromRunId)throw new Error(`Persistence returned runId "${o.runId}" for resumeFromRunId "${t.resumeFromRunId}"; refusing to resume on mismatch`);if(o.status==="complete")throw new Error(`Run "${t.resumeFromRunId}" is already complete; nothing to resume`);if(!o.plan)throw new Error(`Run "${t.resumeFromRunId}" has no saved plan (status="${o.status}"); cannot resume`);return o},"resolveResume"),Mo=s(async(e,t)=>{let o=await Fr(e,t),n=o?.runId??randomUUID();St(n,"runId");let r=o?.startedAt??Date.now(),i=Kr(e,n);return K.run({runId:n,startedAt:r,sandboxDir:i},async()=>q("agent.run",{[M.RUN_ID]:n,[M.PROVIDER]:e.config.providerType,[M.MODEL]:e.config.model},async a=>{try{let c=await Wr(e,t,o);return a.setAttribute(M.ITERATIONS,c.iterations),a.setAttribute(M.USAGE_TOTAL_TOKENS,c.usage.totalTokens),a.setAttribute(M.USAGE_INPUT_TOKENS,c.usage.inputTokens),a.setAttribute(M.USAGE_OUTPUT_TOKENS,c.usage.outputTokens),c}finally{e.config.keepSandbox||await rm(i,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),Hr=s(e=>{let t=Ue(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"runToolStrategy"),Wr=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,a=t.onEvent??(()=>{}),c=pe(e.config.compaction),l=oe(e.config),p=e.config.maxToolCalls,d=G(o?.usage),T=K.getStore()?.startedAt??Date.now(),f=K.getStore()?.runId??"<unknown>",y={usage:d,toolCalls:o?.toolCallCount??0,strategy:Hr(e),discovered:[],activeSkills:[...o?.activeSkills??[]],traceSummary:o?.traceSummary,traceSummaryUpTo:o?.traceSummaryUpTo??0},k={...e,run:y,emit:s(S=>{S.type==="usage"&&Lt(d,S.usage);let g={...S,runId:K.getStore()?.runId};try{a(g);}catch{}try{e.emit(g);}catch{}},"emit")},A=K.getStore();A&&(A.emit=k.emit,A.state=y);let $=s((S,g)=>{dt(e.skills??[],S,g,y,k.emit);},"activate"),D=e.config.persistence,h=s(async(S,g)=>{let w=D?.[S];if(w)try{await w(g);}catch(O){k.emit({type:"log",level:"warn",message:`[persistence] ${S} threw: ${O.message}`});}},"callPersistence"),u;if(!o&&i?.length&&c.auto){let S=await be(i,e.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:ve(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,onUsage:s(g=>k.emit({type:"usage",phase:"compact",usage:g}),"onUsage")});S.compacted&&(i=S.history,u=S.history,k.emit({type:"context.compacted",scope:"history",beforeTokens:S.beforeTokens,afterTokens:S.afterTokens}));}let m=s(async S=>{if(!c.auto||n?.aborted)return;let g=s(()=>({summary:y.traceSummary,upTo:y.traceSummaryUpTo}),"view"),w=se(de(S,g()));if(w<=c.thresholdTokens)return;let O=S.length-c.keepRecentSteps,I=y.traceSummary?y.traceSummaryUpTo:0;if(O<=I)return;let z=await Ft(S.slice(I,O),y.traceSummary,e.synthesizerModel,{summaryMaxTokens:ve(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,render:De,offset:I});z&&(k.emit({type:"usage",phase:"compact",usage:z.usage}),y.traceSummary=z.summary,y.traceSummaryUpTo=O,k.emit({type:"context.compacted",scope:"trace",beforeTokens:w,afterTokens:se(de(S,g()))}));},"maybeCompactTrace"),x=false,R=s(()=>{let S=Re(d,l);if(S)return S;if(typeof p=="number"&&p>0&&y.toolCalls>=p)return {kind:"tool-calls",tokens:y.toolCalls,cap:p}},"budgetBreach"),N=s(()=>{let S=R();return S?(x||(x=true,k.emit({type:"budget.exceeded",...S})),true):false},"reportBudget"),P;if(o)P=o.plan,k.emit({type:"log",level:"info",message:`[resume] continuing run ${f} from step ${o.stepIndex}/${P.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),k.emit({type:"plan.created",plan:P});else {try{P=await Io(r,i,k,n);}catch(S){if(k.emit({type:"error",error:Ee(S),phase:"plan"}),Ke(S)||n?.aborted)throw await h("onRunComplete",{runId:f,startedAt:T,status:"cancelled",input:r,history:i,trace:[],usage:d,stepIndex:0,iterations:0,revisions:0,error:S.message,completedAt:Date.now()}),S;P={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."}]};}k.emit({type:"plan.created",plan:P});for(let S of P.skills??[])$(S,"plan");}let E=o?[...o.trace]:[],b=P,C=o?.stepIndex??0,L=o?.iterations??0,F=o?.revisions??0,H=e.config.maxRevisions??2,v=s((S,g={})=>({runId:f,startedAt:T,status:S,input:r,history:i,plan:b,trace:E,usage:d,stepIndex:C,iterations:L,revisions:F,...y.traceSummary?{traceSummary:y.traceSummary,traceSummaryUpTo:y.traceSummaryUpTo}:{},...y.activeSkills.length?{activeSkills:[...y.activeSkills]}:{},...y.toolCalls?{toolCallCount:y.toolCalls}:{},...g}),"buildSnapshot");o||await h("onRunStart",v("executing"));let _=s(async()=>{await h("onStepComplete",v("executing"));},"persistCheckpoint");for(;L<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(C>=b.steps.length||N())break;L++;let S=b.steps[C];A&&(A.currentStep=S),k.emit({type:"step.start",step:S,index:C});let g=new AbortController;if(t.onStepStart)try{t.onStepStart({step:S,index:C,abort:s(()=>g.abort(),"abort")});}catch(U){k.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${U.message}`});}let w=Xe([n,g.signal]),O;try{await m(E),O=await Eo(r,b,S,E,i,k,w);}catch(U){if(n?.aborted)throw k.emit({type:"error",error:Ee(U),phase:"execute"}),await h("onRunComplete",v("cancelled",{error:U.message,completedAt:Date.now()})),U;if(g.signal.aborted&&Ke(U))k.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),O={step:S,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw k.emit({type:"error",error:Ee(U),phase:"execute"}),await h("onRunComplete",v("failed",{error:U.message,completedAt:Date.now()})),U}if(E.push(O),k.emit({type:"step.complete",step:S,result:O}),N()){C++;break}let I=b.steps[C+1]??null;if(I===null){k.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!await Gr(e.config.replanAfter,O,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:s(U=>k.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${U.message}`}),"onError")})){k.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),C++,await _();continue}let W;try{await m(E),W=await Oo(r,b,E,I,k,n);}catch(U){throw k.emit({type:"error",error:Ee(U),phase:"replan"}),await h("onRunComplete",v(Ke(U)||n?.aborted?"cancelled":"failed",{error:U.message,completedAt:Date.now()})),U}if(k.emit({type:"replan.decision",mode:W.mode,reason:W.reason,cause:"llm-decision"}),W.mode==="finish")break;if(W.mode==="revise"){if(F>=H){k.emit({type:"revisions.exceeded",cap:H});break}F++,b=qr(k,W.newPlan),k.emit({type:"plan.revised",plan:b,reason:W.reason});for(let U of b.skills??[])$(U,"plan");C=0,await _();continue}C++,await _();}let j;try{await m(E),j=await xo(r,b,E,i,k,n);}catch(S){throw k.emit({type:"error",error:Ee(S),phase:"synthesize"}),await h("onRunComplete",v(Ke(S)||n?.aborted?"cancelled":"failed",{error:S.message,completedAt:Date.now()})),S}return k.emit({type:"final",text:j}),await h("onRunComplete",v("complete",{text:j,completedAt:Date.now()})),{text:j,plan:b,trace:E,iterations:L,usage:d,...u?{compactedHistory:u}:{}}},"runAgentLoopInner"),qr=s((e,t)=>{let o=Ge(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=wt(e,t.skills),{skills:r,...i}=t;return {...i,steps:t.steps.slice(0,o),...n?{skills:n}:{}}},"reviseInto"),Ee=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var _o=Symbol.for("@dudko.dev/agent:wrapped-tool"),Fe=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}},Br=s(e=>{let t=K.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new Fe(e);return t.toolCalls++,()=>{t.toolCalls--;}},"reserveToolCall"),Vr=s(e=>Object.prototype.toString.call(e)==="[object AsyncGeneratorFunction]","isAsyncGeneratorFunction"),Yr=s((e,t,o,n={})=>{if(t[_o])return t;let r=le(t),i=n.builtIn===true,a=t.execute,c=s(async(d,T)=>{let f=i?()=>{}:Br(o.maxToolCalls);try{await o.approval.gate(e,d,{readOnly:r,builtIn:i,signal:T?.abortSignal});}catch(y){throw f(),y}},"before"),l;a&&(l=Vr(a)?async function*(d,T){await c(d,T),yield*a(d,T);}:async(d,T)=>(await c(d,T),a(d,T)));let p=rt({...t,...l?{execute:l}:{}},o.maxToolOutputChars);return Object.defineProperty(p,_o,{value:true,enumerable:false}),p},"wrapTool"),Oe=s((e,t,o={})=>{let n={};for(let[r,i]of Object.entries(e))n[r]=Yr(r,i,t,o);return n},"wrapToolSet");var He={none:0,error:1,warn:2,info:3,debug:4},We=s(async(e,t)=>{let o=He[e.logLevel]>=He.debug,n=s(g=>{if(t)try{t(g);}catch(w){o&&console.error("[agent] event handler threw:",w);}},"emit"),r=s((g,w)=>{He[e.logLevel]>=He[g]&&n({type:"log",level:g,message:w});},"log"),i=ro(e.skills),a=s(async(g,w)=>{if(!e.inputSanitizer)return w;try{return await e.inputSanitizer(g,w)}catch{return "[input redacted: sanitizer failed]"}},"sanitizeForApproval"),c=Mt(e.toolApproval,{sanitize:a,fallbackEmit:n}),l=pe(e.compaction),p={approval:c,maxToolCalls:e.maxToolCalls,maxToolOutputChars:l.maxToolOutputChars},d=Oe(io(i),p,{builtIn:true}),T=e.toolSelectionStrategy??"auto",f=T==="search"||T==="auto",y=false,k=s(()=>[],"catalogRef"),A=f?Oe(po(()=>k()),p,{builtIn:true}):void 0,$=s(g=>{for(let w of Object.keys(d))if(g[w])throw new Error(`Tool "${w}" collides with a built-in skill tool of the same name`);if(A&&g[Q]){if(T==="search")throw new Error(`Tool "${Q}" collides with the built-in tool-search tool of the same name`);y||(y=true,r("warn",`[tools] a tool named "${Q}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),D,h=s((g,w)=>{if(!e.tools)return g;let O=[];for(let[I,z]of Object.entries(e.tools)){if(g.tools[I]&&w(I),e.availableTools?.length&&!e.availableTools.includes(I)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(I))continue;g.tools[I]=z;let ae=typeof z=="object"&&z&&"description"in z?z.description:"";O.push({name:I,description:typeof ae=="string"?ae:"",server:"<native>",readOnly:le(z)});}return {tools:g.tools,catalog:[...g.catalog,...O]}},"mergeNativeTools"),u=s(async()=>{let g=await Yt(e.mcpServers,r,e.clientName,e.outputSanitizer,I=>D?.(I),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),w=at(g.tools,g.catalog,e.availableTools,e.excludedTools,r),O;try{O=h(w,I=>{throw new Error(`Native tool "${I}" collides with an MCP-registered tool of the same name`)}),$(O.tools);}catch(I){throw g.close().catch(()=>{}),I}return {connection:g,tools:Oe(O.tools,p),catalog:O.catalog}},"connect"),m;try{m=await u();}catch(g){throw n({type:"error",error:g instanceof Error?g:new Error(String(g)),phase:"init"}),g}let x=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&x>0&&!m.connection.results.some(w=>w.connected)){let w=m.connection.results.filter(I=>!I.connected).map(I=>`${I.name}: ${I.error??"unknown"}`).join("; ");await m.connection.close().catch(()=>{});let O=new Error(`All ${x} configured MCP server(s) failed to connect [${w}]`);throw n({type:"error",error:O,phase:"init"}),O}let R,N,P;try{let g=_e(e,void 0,void 0,"executor"),w=_e(e,e.planner,e.plannerModel,"planner"),O=_e(e,e.synthesizer,e.synthesizerModel,"synthesizer");[R,N,P]=await Promise.all([$e(e.clientName,g),$e(e.clientName,w),$e(e.clientName,O)]);}catch(g){throw await m.connection.close().catch(()=>{}),n({type:"error",error:g instanceof Error?g:new Error(String(g)),phase:"init"}),g}let E=s(g=>g.map(w=>({name:w.name,description:w.description,server:w.server,readOnly:w.readOnly===true})),"toEntries"),b={config:e,executorModel:R,plannerModel:N,synthesizerModel:P,tools:m.tools,toolCatalog:E(m.catalog),emit:n,...Object.keys(d).length?{builtinTools:d}:{},...i.length?{skills:i}:{},approval:c};k=s(()=>b.toolCatalog,"catalogRef");let C=s(()=>{A&&!y?b.findTools=A:delete b.findTools;},"syncFindTools");C();let L=0,F=false,H=false,v=false,_=new Set,j=s(async g=>{await m.connection.refreshServer(g);let w=at(m.connection.tools,m.connection.catalog,e.availableTools,e.excludedTools),O=h(w,z=>{throw new Error(`Native tool "${z}" collides with an MCP-registered tool of the same name`)});$(O.tools);let I=Oe(O.tools,p);for(let z of Object.keys(b.tools))delete b.tools[z];Object.assign(b.tools,I),b.toolCatalog=E(O.catalog),C(),r("info",`[mcp] ${g}: tool list refreshed (${O.catalog.length} tools total after filter)`);},"applyRefresh"),S=s(async()=>{if(!(v||F||H)&&!(L>0||_.size===0)){v=true;try{for(;_.size>0&&L===0&&!F&&!H;){let g=_.values().next().value;_.delete(g);try{await j(g);}catch(w){r("warn",`[mcp] ${g}: refresh failed - ${w.message}`);}}}finally{v=false;}}},"drainPendingRefreshes");return D=s(g=>{_.add(g),S();},"onToolsChanged"),{run:s(async g=>{if(F)throw new Error("Agent is closed");if(H)throw new Error("Agent is reconnecting; retry shortly");if(v)throw new Error("Agent is refreshing tools; retry shortly");let w=e.maxConcurrentRuns;if(typeof w=="number"&&w>0&&L>=w)throw new Error(`maxConcurrentRuns reached (${L}/${w}); rate-limit on the caller side or raise the cap`);L++;try{return await Mo(b,g)}finally{L--,S();}},"run"),listTools:s(()=>b.toolCatalog.map(g=>({...g})),"listTools"),listSkills:s(()=>i.map(g=>({name:g.name,description:g.description})),"listSkills"),compact:s(async g=>{let w=await be(g.history,b.synthesizerModel,{thresholdTokens:l.thresholdTokens,keepRecentTurns:l.keepRecentTurns,summaryMaxTokens:ve(e,l.summaryMaxTokens),force:g.force,signal:g.signal,timeoutMs:e.llmTimeoutMs,onUsage:s(O=>n({type:"usage",phase:"compact",usage:O}),"onUsage")});return w.compacted&&n({type:"context.compacted",scope:"history",beforeTokens:w.beforeTokens,afterTokens:w.afterTokens}),{history:w.history,...w.summary?{summary:w.summary}:{},beforeTokens:w.beforeTokens,afterTokens:w.afterTokens,compacted:w.compacted}},"compact"),setToolApprovalMode:s(g=>c.setMode(g),"setToolApprovalMode"),getToolApprovalMode:s(()=>c.getMode(),"getToolApprovalMode"),reconnect:s(async()=>{if(F)throw new Error("Agent is closed");if(H)throw new Error("Already reconnecting");if(v)throw new Error("Agent is refreshing tools; retry shortly");if(L>0)throw new Error(`Cannot reconnect with ${L} active run(s)`);H=true;try{let g=m.connection;_.clear();let w=await u();for(let O of Object.keys(b.tools))delete b.tools[O];Object.assign(b.tools,w.tools),b.toolCatalog=E(w.catalog),C(),m=w,await g.close().catch(()=>{});}finally{H=false;}},"reconnect"),close:s(async g=>{F=true;let w=g?.waitForRuns??false,O=g?.timeoutMs??3e4,I=Date.now()+O;if(w&&L>0)for(;L>0&&Date.now()<I;)await new Promise(U=>setTimeout(U,50));L>0&&n({type:"log",level:"warn",message:`[agent] close called with ${L} active run(s); they will fail mid-flight`});let z=Math.max(I-Date.now(),0),ae=false,W;await Promise.race([m.connection.close().catch(()=>{}),new Promise(U=>{W=setTimeout(()=>{ae=true,U();},z),W.unref?.();})]),W&&clearTimeout(W),ae&&n({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${z}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>L,"activeRuns")}},"createAgent");var qe=["openai","anthropic","openai-compatible","google","xai","azure","amazon-bedrock","google-vertex","deepseek","gateway","cloudflare"],Jr=new Set(["openai-compatible","azure"]),$o=["none","error","warn","info","debug"],Lo=["all","plan-narrowed","search","auto"],No=["provider-default","none","minimal","low","medium","high","xhigh"],Uo=["autopilot","ask-writes","ask-all","read-only"],Go=s(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!qe.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${qe.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!$o.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${$o.join(" | ")}, got: ${t}`);let o=Jr.has(e)?bt("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:bt("AGENT_API_KEY"),model:bt("AGENT_MODEL"),providerOptions:Fo("AGENT_PROVIDER_OPTIONS"),planner:Do("AGENT_PLANNER"),synthesizer:Do("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:os(process.env.MCP_SERVERS),availableTools:jo(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:jo(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:zo(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:zo(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:ee(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:ee(process.env.AGENT_MAX_TOTAL_TOKENS),limits:Zr(),maxToolCalls:ee(process.env.AGENT_MAX_TOOL_CALLS),thinking:Xr(process.env.AGENT_THINKING),toolApproval:Qr(process.env.AGENT_TOOL_APPROVAL),compaction:es(),llmTimeoutMs:ee(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:ee(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:ts(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),Xr=s(e=>{let t=e?.trim().toLowerCase();if(!t)return;if(t==="off")return "none";if(No.includes(t))return t;let o=Number(t);if(Number.isFinite(o)&&o>0)return {level:"medium",budgetTokens:Math.floor(o)};throw new Error(`AGENT_THINKING must be off | ${No.join(" | ")} | <budget tokens>, got: ${e}`)},"parseThinking"),Zr=s(()=>{let e={},t=ee(process.env.AGENT_MAX_INPUT_TOKENS),o=ee(process.env.AGENT_MAX_OUTPUT_TOKENS),n=ee(process.env.AGENT_MAX_REASONING_TOKENS);return t&&(e.maxInputTokens=t),o&&(e.maxOutputTokens=o),n&&(e.maxReasoningTokens=n),Object.keys(e).length?e:void 0},"parseLimits"),Qr=s(e=>{let t=e?.trim();if(t){if(!Uo.includes(t))throw new Error(`AGENT_TOOL_APPROVAL must be ${Uo.join(" | ")}, got: ${t}`);return {mode:t}}},"parseApproval"),es=s(()=>{let e=process.env.AGENT_COMPACTION?.trim().toLowerCase(),t=ee(process.env.AGENT_CONTEXT_WINDOW_TOKENS),o={};if(e)if(["off","false","0","no"].includes(e))o.auto=false;else if(["on","auto","true","1","yes"].includes(e))o.auto=true;else throw new Error(`AGENT_COMPACTION must be on | off, got: ${process.env.AGENT_COMPACTION}`);return t&&(o.contextWindowTokens=t),Object.keys(o).length?o:void 0},"parseCompaction"),Ko=s(()=>process.env.AGENT_SKILLS_DIR?.trim()||void 0,"skillsDirFromEnv"),Do=s(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),n=process.env[`${e}_API_KEY`]?.trim(),r=Fo(`${e}_PROVIDER_OPTIONS`);if(!(!t&&!o&&!n&&!r)){if(t&&!qe.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${qe.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:n||void 0,providerOptions:r}}},"parseStageOverride"),Fo=s(e=>{let t=process.env[e]?.trim();if(!t)return;let o;try{o=JSON.parse(t);}catch(n){throw new Error(`${e} must be valid JSON: ${n.message}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e} must be a JSON object (got ${typeof o})`);return o},"parseProviderOptions"),ts=s(e=>{let t=e?.trim();if(t){if(!Lo.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${Lo.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),ee=s(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),bt=s(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),jo=s(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),zo=s((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),os=s(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(n){throw new Error(`MCP_SERVERS must be valid JSON: ${n.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[n,r]of Object.entries(t)){if(!r||typeof r!="object")throw new Error(`MCP_SERVERS.${n} must be an object`);let i=r,a=typeof i.url=="string"&&i.url.length>0,c=typeof i.command=="string"&&i.command.length>0;if(a&&c)throw new Error(`MCP_SERVERS.${n}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!a&&!c)throw new Error(`MCP_SERVERS.${n}: must specify "url" (HTTP) or "command" (stdio)`);if(a){let l=i.headers&&typeof i.headers=="object"&&!Array.isArray(i.headers)?i.headers:void 0;o[n]={url:i.url,headers:l};continue}if(i.args!==void 0&&!Array.isArray(i.args))throw new Error(`MCP_SERVERS.${n}.args must be a string array`);if(i.env!==void 0&&(!i.env||typeof i.env!="object"||Array.isArray(i.env)))throw new Error(`MCP_SERVERS.${n}.env must be a string-to-string map`);if(i.cwd!==void 0&&typeof i.cwd!="string")throw new Error(`MCP_SERVERS.${n}.cwd must be a string`);o[n]={command:i.command,args:i.args,env:i.env,cwd:i.cwd};}return o},"parseMcpServers");var ss=16,Ho=["autopilot","ask-writes","ask-all","read-only"],is=stdout.isTTY?"\x1B[2m":"",as=stdout.isTTY?"\x1B[22m":"",ge=s((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),It=s(e=>{try{return ge(JSON.stringify(e))}catch{return String(e)}},"formatJson"),Wo=s(e=>e===void 0||e===false?"provider default":e===true?"medium":typeof e=="string"?e:`${e.level??"medium"}${e.budgetTokens?` (budget ${e.budgetTokens})`:""}`,"describeThinking"),ls=s(e=>{for(;e.length>ss;){let t=e.length&&Se(e[0])?1:0;e.splice(t,1);}},"trimHistory"),qo=s(async()=>{let e=Go(),t=Ko();t&&(e.skills=await pt(t));let o=Object.keys(e.mcpServers),n=e.planner?.model??e.plannerModel??e.model,r=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${n} synth=${r} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[session] thinking=${Wo(e.thinking)} approval=${e.toolApproval?.mode??"autopilot"} skills=${e.skills?.length??0}`),console.log(`[mcp] servers=${o.length?o.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /compact, /autopilot, /approval <mode>, /reconnect, /exit
|
|
172
|
-
`);let i="none",a=s(()=>{i!=="none"&&(process.stdout.write(i==="reasoning"?`${as}
|
|
180
|
+
${e}`,i?.length?`
|
|
181
|
+
${St(i,0,Nr)}`:"","",`Plan that was executed:
|
|
182
|
+
${bt(t)}`,"",`Execution trace:
|
|
183
|
+
${he(o,n)}`,"","Write the final answer for the user now."].filter(Boolean).join(`
|
|
184
|
+
`),"buildSynthesizerUserPrompt");var zr=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")}),Gr=Fe,It=z.object({thought:z.string().min(1).describe("One-paragraph reasoning about how to approach the request"),steps:z.array(zr).min(1),skills:z.array(z.string()).optional().describe("Names of skills from the SKILLS list that apply to this request")}),He=s(e=>{let t=e.config.maxPlanSteps;return typeof t=="number"&&Number.isFinite(t)&&t>=1?Math.floor(t):Gr},"planStepCap"),ye=s(e=>{if(e.run)return e.run.strategy;let t=ze(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"),Et=s((e,t)=>{if(!t?.length)return;let o=new Set((e.skills??[]).map(i=>i.name)),r=[...new Set(t.filter(i=>o.has(i)))],n=t.filter(i=>!o.has(i));return n.length&&e.emit({type:"log",level:"warn",message:`[plan] dropped unknown skills: ${n.join(", ")}`}),r.length?r:void 0},"filterPlanSkills"),_o=s(async(e,t,o,r)=>B("agent.plan",{[M.PHASE]:"plan"},async n=>{let i=new Set(o.toolCatalog.map(f=>f.name)),l=At(ye(o)),a=He(o),{object:c,usage:p}=await ne(()=>Kr(e,t,l,o,r),{maxRetries:o.config.llmMaxRetries??2,signal:r,onRetry:s((f,S)=>o.emit({type:"retry",phase:"plan",attempt:f,error:S.message}),"onRetry")});o.emit({type:"usage",phase:"plan",usage:p}),n.setAttribute(M.USAGE_TOTAL_TOKENS,p.totalTokens);let g=c.steps.slice(0,a);g.length<c.steps.length&&o.emit({type:"log",level:"warn",message:`[plan] model returned ${c.steps.length} steps; truncated to hard cap ${a}`});let h=Et(o,c.skills);return {thought:c.thought,...h?{skills:h}:{},steps:g.map(f=>{if(!f.suggestedTools?.length)return f;let S=f.suggestedTools.filter(w=>i.has(w)),A=f.suggestedTools.length-S.length;return A>0&&o.emit({type:"log",level:"warn",message:`[plan] step "${f.id}" had ${A} unknown suggestedTools, stripped`}),S.length===0?(o.emit({type:"log",level:"warn",message:`[plan] step "${f.id}" had no valid suggestedTools left; falling back to full toolset`}),{...f,suggestedTools:void 0,requiresTools:true}):{...f,suggestedTools:S}})}}),"createInitialPlan"),Kr=s(async(e,t,o,r,n)=>{let i=se(r.config,"planner",Io({mode:o,catalog:r.toolCatalog,maxSteps:He(r),domain:r.config.systemPrompt,skills:r.skills})),l=streamObject({model:r.plannerModel,schema:It,...i,prompt:Ao(e,t),abortSignal:V(n,r.config.llmTimeoutMs??0)}),a="",c=false,p=0;for await(let f of l.partialObjectStream){let S=f?.thought;typeof S=="string"&&S!==a&&(S.startsWith(a)?r.emit({type:"plan.thought-delta",delta:S.slice(a.length)}):c||(r.emit({type:"log",level:"warn",message:"[plan] thought was rewritten mid-stream; streamed deltas may be inconsistent"}),c=true),a=S);let A=f?.steps;if(Array.isArray(A)&&A.length>p)for(;p<A.length;){let w=A[p];if(!w||typeof w.description!="string"||!w.description.length)break;let R={id:typeof w.id=="string"&&w.id?w.id:`s${p+1}`,description:w.description,expectedOutcome:typeof w.expectedOutcome=="string"?w.expectedOutcome:"",suggestedTools:Array.isArray(w.suggestedTools)?w.suggestedTools.filter(j=>typeof j=="string"):void 0};r.emit({type:"plan.step-added",step:R,index:p}),p++;}}let[g,h]=await Promise.all([l.object,l.usage]);return {object:g,usage:G(h)}},"streamPlanOnce");var Wr=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 r={};for(let n of o){let i=e.tools[n];i&&(r[n]=i);}return r},"buildActiveToolSet"),Lo="[BLOCKER]",qr=s(e=>e.includes(Lo)?{summary:e.split(Lo).join("").trim(),blocked:true}:{summary:e,blocked:false},"splitBlockerSentinel"),Ot=4e3,Br=s(e=>e.length>Ot?`${e.slice(0,Ot)}... [truncated, ${e.length-Ot} chars]`:e,"truncateForTrace"),No=s(async(e,t,o,r,n,i,l)=>B("agent.execute_step",{[M.PHASE]:"execute",[M.STEP_ID]:o.id},async a=>{let c=Date.now(),p=await ne(()=>Yr(e,t,o,r,n,i,l),{maxRetries:i.config.llmMaxRetries??2,signal:l,onRetry:s((g,h)=>i.emit({type:"retry",phase:"execute",attempt:g,error:h.message}),"onRetry")});return i.emit({type:"usage",phase:"execute",usage:p.usage}),a.setAttribute(M.USAGE_TOTAL_TOKENS,p.usage.totalTokens),a.setAttribute(M.STEP_BLOCKED,p.blocked),a.setAttribute(M.TOOL_COUNT,p.toolCalls.length),{step:o,summary:p.summary,toolCalls:p.toolCalls,durationMs:Date.now()-c,blocked:p.blocked}}),"executeStep"),Vr=s((e,t)=>{let o=ye(e),r=e.builtinTools??{};if(o==="search"){let l={...e.tools,...r,...e.findTools??{}},a=new Set([...Object.keys(r),...Object.keys(e.findTools??{})]);for(let c of t.suggestedTools??[])e.tools[c]&&a.add(c);for(let c of (e.run?.discovered??[]).slice(-16))e.tools[c]&&a.add(c);return {tools:l,active:a}}let n=Wr(e,t),i=Object.keys(r).length?{...n,...r}:n;return o==="plan-narrowed"?{tools:i,activeTools:Object.keys(i)}:{tools:i}},"buildExecutorTools"),Yr=s(async(e,t,o,r,n,i,l)=>{let a=[],c=new Map,{tools:p,activeTools:g,active:h}=Vr(i,o),f=i.run;f&&(f.stepActive=h);let S=s(async(I,_)=>{let z=i.config.inputSanitizer;if(!z)return _;try{return await z(I,_)}catch(T){return i.emit({type:"log",level:"warn",message:`[executor] inputSanitizer threw for ${I} - ${T.message}; event input redacted`}),"[input redacted: sanitizer failed]"}},"sanitizeForEvent"),A,w=[stepCountIs(i.config.maxStepsPerTask)],R=re(i.config);f&&Kt(R)&&w.push(Ft(()=>f.usage,R,()=>{A="tokens";}));let j=i.config.maxToolCalls;f&&typeof j=="number"&&j>0&&w.push(()=>f.toolCalls>=j?(A??="tool-calls",true):false);let y=se(i.config,"executor",Eo({domain:i.config.systemPrompt,skills:i.skills,activeSkills:f?.activeSkills,searchMode:!!h,toolCount:i.toolCatalog.length})),b=Me(i.config,"executor"),x=f?{summary:f.traceSummary,upTo:f.traceSummaryUpTo}:void 0,N=ke(i.config.promptCaching),P=ge(i.config.compaction),u=P.clearToolResultsAfterTokens>0?mt({triggerTokens:P.clearToolResultsAfterTokens,keep:P.keepToolResults},I=>{i.emit({type:"log",level:"info",message:`[executor] cleared ${I.cleared} stale tool result(s) from the step's context`}),i.emit({type:"context.compacted",scope:"tool-results",beforeTokens:I.beforeTokens,afterTokens:I.afterTokens});}):void 0,m=N.enabled||!!u,k=i.takeRoundUpdates,v=streamText({model:i.executorModel,tools:p,...g?{activeTools:g}:{},...h||m||k?{prepareStep:s(({messages:I,stepNumber:_})=>{let z=k&&_>0?k():[],T=z.length?[...I,{role:"user",content:xo(z)}]:I,d=et(u?u(T):T,N);return {...h?{activeTools:[...h].filter(O=>O in p)}:{},...m||z.length?{messages:d}:{}}},"prepareStep")}:{},stopWhen:w,...y,prompt:Ro(e,t,o,r,n,x,f?.userUpdates.map(I=>I.text)),abortSignal:V(l,i.config.llmTimeoutMs??0)});for await(let I of v.fullStream)switch(I.type){case "text-delta":I.text&&i.emit({type:"step.text-delta",step:o,delta:I.text});break;case "reasoning-delta":I.text&&b&&i.emit({type:"step.reasoning-delta",step:o,delta:I.text});break;case "tool-call":{let _=await S(I.toolName,I.input);c.set(I.toolCallId,{name:I.toolName,input:_}),i.emit({type:"step.tool-call",step:o,name:I.toolName,input:_});break}case "tool-result":{if(I.preliminary)break;let z=c.get(I.toolCallId)?.input??await S(I.toolName,I.input);a.push({name:I.toolName,input:z,output:I.output,ok:true}),i.emit({type:"step.tool-result",step:o,name:I.toolName,output:I.output,ok:true}),c.delete(I.toolCallId);break}case "tool-error":{let z=c.get(I.toolCallId)?.input??await S(I.toolName,I.input);a.push({name:I.toolName,input:z,output:I.error,ok:false}),i.emit({type:"step.tool-result",step:o,name:I.toolName,output:I.error,ok:false}),c.delete(I.toolCallId);break}case "error":{let _=I.error;throw _ instanceof Error?_:new Error(String(_))}}let[C,$]=await Promise.all([v.text,v.usage]),{summary:U,blocked:K}=qr(C.trim());return {summary:U.length>0?Br(U):A?`Stopped early: the run's ${A==="tokens"?"token":"tool-call"} budget was reached after ${a.length} tool call(s).`:a.length>0?`Executed ${a.length} tool call(s) without producing a final message; consider raising maxStepsPerTask.`:"Step produced no output.",toolCalls:a,blocked:K,usage:$?G($):me()}},"runOnce");var Xr=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")})]),Uo=s(async(e,t,o,r,n,i,l=0)=>B("agent.replan",{[M.PHASE]:"replan"},async a=>{let c=At(ye(n)),p=n.run?{summary:n.run.traceSummary,upTo:n.run.traceSummaryUpTo}:void 0,{object:g,usage:h}=await ne(async()=>{let f=se(n.config,"replanner",Co({mode:c,catalog:n.toolCatalog,domain:n.config.systemPrompt,skills:n.skills,activeSkills:n.run?.activeSkills})),S=await generateObject({model:n.plannerModel,schema:Xr,...f,prompt:$o(e,t,o,r,p,n.run?.userUpdates.map(w=>w.text),l),abortSignal:V(i,n.config.llmTimeoutMs??0)}),A=G(S.usage);return {object:S.object,usage:A}},{maxRetries:n.config.llmMaxRetries??2,signal:i,onRetry:s((f,S)=>n.emit({type:"retry",phase:"replan",attempt:f,error:S.message}),"onRetry")});return n.emit({type:"usage",phase:"replan",usage:h}),a.setAttribute(M.REPLAN_MODE,g.mode),a.setAttribute(M.USAGE_TOTAL_TOKENS,h.totalTokens),g}),"decideNextAction");var Do=s(async(e,t,o,r,n,i)=>B("agent.synthesize",{[M.PHASE]:"synthesize"},async l=>{let{text:a,usage:c}=await ne(()=>Qr(e,t,o,r,n,i),{maxRetries:n.config.llmMaxRetries??2,signal:i,onRetry:s((p,g)=>n.emit({type:"retry",phase:"synthesize",attempt:p,error:g.message}),"onRetry")});return n.emit({type:"usage",phase:"synthesize",usage:c}),l.setAttribute(M.USAGE_TOTAL_TOKENS,c.totalTokens),a}),"synthesizeAnswer"),Qr=s(async(e,t,o,r,n,i)=>{let l=se(n.config,"synthesizer",Po({domain:n.config.systemPrompt,skills:n.skills,activeSkills:n.run?.activeSkills})),a=n.run?{summary:n.run.traceSummary,upTo:n.run.traceSummaryUpTo}:void 0,c=Me(n.config,"synthesizer"),p=streamText({model:n.synthesizerModel,...l,prompt:Mo(e,t,o,r,a,n.run?.userUpdates.map(f=>f.text)),abortSignal:V(i,n.config.llmTimeoutMs??0)});for await(let f of p.fullStream)if(f.type==="text-delta")f.text&&n.emit({type:"final.text-delta",delta:f.text});else if(f.type==="reasoning-delta")f.text&&c&&n.emit({type:"final.reasoning-delta",delta:f.text});else if(f.type==="error"){let S=f.error;throw S instanceof Error?S:new Error(String(S))}let[g,h]=await Promise.all([p.text,p.usage]);return {text:g,usage:G(h)}},"streamOnce");var zo=s(e=>{if(e.blocked)return true;let{toolCalls:t}=e;return t.some((o,r)=>!o.ok&&!t.slice(r+1).some(n=>n.ok&&n.name===o.name))},"shouldCallReplanner"),ns=s(async(e,t,o={})=>{if(e==="always")return true;if(typeof e!="function")return zo(t);let r=s(()=>zo(t),"fallback"),{signal:n}=o,i=o.timeoutMs??0;if(n?.aborted)return r();let l=(async()=>{try{return !!await e(t)}catch(c){return o.onError?.(c),r()}})(),a=Number.isFinite(i)&&i>0;return !a&&!n?l:new Promise(c=>{let p=false,g,h=s(S=>{p||(p=true,g!==void 0&&clearTimeout(g),n?.removeEventListener("abort",f),c(S));},"finish");function f(){h(r());}s(f,"onAbort"),a&&(g=setTimeout(()=>h(r()),i)),n?.addEventListener("abort",f,{once:true}),l.then(h,()=>h(r()));})},"replanTriggered"),We=s(e=>!!e&&typeof e=="object"&&e.name==="AbortError","isAbortError"),rs=s((e,t)=>{let o=e.config.sandboxRoot?.trim()||le.join(tmpdir(),"agent-sandbox");return le.join(o,t)},"resolveSandboxDir"),Go=/^[a-zA-Z0-9_-]{1,128}$/,xt=s((e,t)=>{if(!Go.test(e))throw new Error(`Unsafe runId from ${t}: must match ${Go}, got ${JSON.stringify(e)}`)},"assertSafeRunId"),ss=s(async(e,t)=>{if(!t.resumeFromRunId)return;if(xt(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(xt(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"),Ko=s(async(e,t)=>{let o=no(t.control),r=await ss(e,t),n=r?.runId??randomUUID();xt(n,"runId");let i=r?.startedAt??Date.now(),l=rs(e,n);return F.run({runId:n,startedAt:i,sandboxDir:l,...o?{control:o}:{}},async()=>B("agent.run",{[M.RUN_ID]:n,[M.PROVIDER]:e.config.providerType,[M.MODEL]:e.config.model},async a=>{try{let c=await as(e,t,r,o);return o&&(c.undelivered=o.detach()),a.setAttribute(M.ITERATIONS,c.iterations),a.setAttribute(M.USAGE_TOTAL_TOKENS,c.usage.totalTokens),a.setAttribute(M.USAGE_INPUT_TOKENS,c.usage.inputTokens),a.setAttribute(M.USAGE_OUTPUT_TOKENS,c.usage.outputTokens),c}finally{o?.detach(),e.config.keepSandbox||await rm(l,{recursive:true,force:true}).catch(()=>{});}}))},"runAgentLoop"),is=s(e=>{let t=ze(e.config,e.toolCatalog.length);return t==="search"&&!e.findTools?"all":t},"runToolStrategy"),as=s(async(e,t,o,r)=>{let{signal:n}=t,i=o?.input??t.input,l=o?.history?[...o.history]:t.history?[...t.history]:void 0,a=t.onEvent??(()=>{}),c=ge(e.config.compaction),p=re(e.config),g=e.config.maxToolCalls,h=G(o?.usage),f=F.getStore()?.startedAt??Date.now(),S=F.getStore()?.runId??"<unknown>",A={usage:h,toolCalls:o?.toolCallCount??0,strategy:is(e),discovered:[],activeSkills:[...o?.activeSkills??[]],traceSummary:o?.traceSummary,traceSummaryUpTo:o?.traceSummaryUpTo??0,userUpdates:(o?.userUpdates??[]).map(d=>({...d}))},w={...e,run:A,emit:s(d=>{d.type==="usage"&&Gt(h,d.usage);let O={...d,runId:F.getStore()?.runId};try{a(O);}catch{}try{e.emit(O);}catch{}},"emit")},R=F.getStore();R&&(R.emit=w.emit,R.state=A),r?.attach(w.emit);let j=s(d=>{if(!r)return [];let O=r.drain();for(let E of O)A.userUpdates.push({text:E.text,reconciled:false}),w.emit({type:"message.delivered",id:E.id,text:E.text,at:d});return O.map(E=>E.text)},"deliver");r&&(w.takeRoundUpdates=()=>j("round"));let y=s((d,O)=>{yt(e.skills??[],d,O,A,w.emit);},"activate"),b=e.config.persistence,x=s(async(d,O)=>{let E=b?.[d];if(E)try{await E(O);}catch(L){w.emit({type:"log",level:"warn",message:`[persistence] ${d} threw: ${L.message}`});}},"callPersistence"),N;if(!o&&l?.length&&c.auto){let d=await Ee(l,e.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:Ie(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,onUsage:s(O=>w.emit({type:"usage",phase:"compact",usage:O}),"onUsage")});d.compacted&&(l=d.history,N=d.history,w.emit({type:"context.compacted",scope:"history",beforeTokens:d.beforeTokens,afterTokens:d.afterTokens}));}let P=s(async d=>{if(!c.auto||n?.aborted)return;let O=s(()=>({summary:A.traceSummary,upTo:A.traceSummaryUpTo}),"view"),E=ae(he(d,O()));if(E<=c.thresholdTokens)return;let L=d.length-c.keepRecentSteps,q=A.traceSummary?A.traceSummaryUpTo:0;if(L<=q)return;let H=await Yt(d.slice(q,L),A.traceSummary,e.synthesizerModel,{summaryMaxTokens:Ie(e.config,c.summaryMaxTokens),signal:n,timeoutMs:e.config.llmTimeoutMs,render:Ge,offset:q});H&&(w.emit({type:"usage",phase:"compact",usage:H.usage}),A.traceSummary=H.summary,A.traceSummaryUpTo=L,w.emit({type:"context.compacted",scope:"trace",beforeTokens:E,afterTokens:ae(he(d,O()))}));},"maybeCompactTrace"),u=false,m=s(()=>{let d=Pe(h,p);if(d)return d;if(typeof g=="number"&&g>0&&A.toolCalls>=g)return {kind:"tool-calls",tokens:A.toolCalls,cap:g}},"budgetBreach"),k=s(()=>{let d=m();return d?(u||(u=true,w.emit({type:"budget.exceeded",...d})),true):false},"reportBudget"),v;if(o)v=o.plan,w.emit({type:"log",level:"info",message:`[resume] continuing run ${S} from step ${o.stepIndex}/${v.steps.length} (iterations=${o.iterations}, revisions=${o.revisions})`}),w.emit({type:"plan.created",plan:v});else {try{v=await _o(i,l,w,n);}catch(d){if(w.emit({type:"error",error:Re(d),phase:"plan"}),We(d)||n?.aborted)throw await x("onRunComplete",{runId:S,startedAt:f,status:"cancelled",input:i,history:l,trace:[],usage:h,stepIndex:0,iterations:0,revisions:0,error:d.message,completedAt:Date.now()}),d;v={thought:"Planner failed; answering directly without tool use.",steps:[{id:"fallback",description:"Answer the user directly using prior conversation and general knowledge.",expectedOutcome:"A direct answer to the user request."}]};}w.emit({type:"plan.created",plan:v});for(let d of v.skills??[])y(d,"plan");}let C=o?[...o.trace]:[],$=v,U=o?.stepIndex??0,K=o?.iterations??0,W=o?.revisions??0,I=e.config.maxRevisions??2,_=s((d,O={})=>({runId:S,startedAt:f,status:d,input:i,history:l,plan:$,trace:C,usage:h,stepIndex:U,iterations:K,revisions:W,...A.traceSummary?{traceSummary:A.traceSummary,traceSummaryUpTo:A.traceSummaryUpTo}:{},...A.activeSkills.length?{activeSkills:[...A.activeSkills]}:{},...A.toolCalls?{toolCallCount:A.toolCalls}:{},...A.userUpdates.length?{userUpdates:A.userUpdates.map(E=>({...E}))}:{},...O}),"buildSnapshot");o||await x("onRunStart",_("executing"));let z=s(async()=>{await x("onStepComplete",_("executing"));},"persistCheckpoint");for(;K<e.config.maxIterations;){if(n?.aborted)throw new DOMException("Aborted","AbortError");if(U>=$.steps.length||k())break;K++;let d=$.steps[U];R&&(R.currentStep=d),w.emit({type:"step.start",step:d,index:U});let O=new AbortController;if(t.onStepStart)try{t.onStepStart({step:d,index:U,abort:s(()=>O.abort(),"abort")});}catch(D){w.emit({type:"log",level:"warn",message:`[step] onStepStart callback threw: ${D.message}`});}let E=tt([n,O.signal]),L;try{await P(C),L=await No(i,$,d,C,l,w,E);}catch(D){if(n?.aborted)throw w.emit({type:"error",error:Re(D),phase:"execute"}),await x("onRunComplete",_("cancelled",{error:D.message,completedAt:Date.now()})),D;if(O.signal.aborted&&We(D))w.emit({type:"log",level:"info",message:"[step] aborted via onStepStart callback; replanner will decide what to do"}),L={step:d,summary:"[step aborted by caller]",toolCalls:[],durationMs:0,blocked:true};else throw w.emit({type:"error",error:Re(D),phase:"execute"}),await x("onRunComplete",_("failed",{error:D.message,completedAt:Date.now()})),D}if(C.push(L),w.emit({type:"step.complete",step:d,result:L}),k()){U++;break}j("step");let q=A.userUpdates.filter(D=>!D.reconciled).length,H=q>0&&K<e.config.maxIterations&&!n?.aborted,ue=$.steps[U+1]??null,$t=ue===null;if($t&&!H){w.emit({type:"replan.decision",mode:"finish",reason:"last planned step reached",cause:"last-step"});break}if(!(H||await ns(e.config.replanAfter,L,{signal:n,timeoutMs:e.config.llmTimeoutMs??0,onError:s(D=>w.emit({type:"log",level:"warn",message:`[runner] replanAfter predicate threw - using the failure rule: ${D.message}`}),"onError")}))){w.emit({type:"replan.decision",mode:"continue",reason:"replan trigger not met, skipping LLM replanner",cause:"clean-step"}),U++,await z();continue}let ce;try{await P(C),ce=await Uo(i,$,C,ue,w,n,q);}catch(D){throw w.emit({type:"error",error:Re(D),phase:"replan"}),await x("onRunComplete",_(We(D)||n?.aborted?"cancelled":"failed",{error:D.message,completedAt:Date.now()})),D}w.emit({type:"replan.decision",mode:ce.mode,reason:ce.reason,cause:H?"user-message":"llm-decision"});for(let D of A.userUpdates)D.reconciled=true;if(ce.mode==="finish")break;if(ce.mode==="revise"){if(!H&&W>=I){w.emit({type:"revisions.exceeded",cap:I});break}H||W++,$=ls(w,ce.newPlan),w.emit({type:"plan.revised",plan:$,reason:ce.reason});for(let D of $.skills??[])y(D,"plan");U=0,await z();continue}if($t)break;U++,await z();}let T;try{j("final"),await P(C),T=await Do(i,$,C,l,w,n);}catch(d){throw w.emit({type:"error",error:Re(d),phase:"synthesize"}),await x("onRunComplete",_(We(d)||n?.aborted?"cancelled":"failed",{error:d.message,completedAt:Date.now()})),d}return w.emit({type:"final",text:T}),await x("onRunComplete",_("complete",{text:T,completedAt:Date.now()})),{text:T,plan:$,trace:C,iterations:K,usage:h,...N?{compactedHistory:N}:{}}},"runAgentLoopInner"),ls=s((e,t)=>{let o=He(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 r=Et(e,t.skills),{skills:n,...i}=t;return {...i,steps:t.steps.slice(0,o),...r?{skills:r}:{}}},"reviseInto"),Re=s(e=>e instanceof Error?e:new Error(typeof e=="string"?e:JSON.stringify(e)),"asError");var Fo=Symbol.for("@dudko.dev/agent:wrapped-tool"),qe=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}},cs=s(e=>{let t=F.getStore()?.state;if(!t)return ()=>{};if(typeof e=="number"&&e>0&&t.toolCalls>=e)throw new qe(e);return t.toolCalls++,()=>{t.toolCalls--;}},"reserveToolCall"),ps=s(e=>Object.prototype.toString.call(e)==="[object AsyncGeneratorFunction]","isAsyncGeneratorFunction"),us=s((e,t,o,r={})=>{if(t[Fo])return t;let n=de(t),i=r.builtIn===true,l=t.execute,a=s(async(g,h)=>{let f=i?()=>{}:cs(o.maxToolCalls);try{await o.approval.gate(e,g,{readOnly:n,builtIn:i,signal:h?.abortSignal});}catch(S){throw f(),S}},"before"),c;l&&(c=ps(l)?async function*(g,h){await a(g,h),yield*l(g,h);}:async(g,h)=>(await a(g,h),l(g,h)));let p=lt({...t,...c?{execute:c}:{}},o.maxToolOutputChars);return Object.defineProperty(p,Fo,{value:true,enumerable:false}),p},"wrapTool"),Ce=s((e,t,o={})=>{let r={};for(let[n,i]of Object.entries(e))r[n]=us(n,i,t,o);return r},"wrapToolSet");var Be={none:0,error:1,warn:2,info:3,debug:4},Ve=s(async(e,t)=>{let o=Be[e.logLevel]>=Be.debug,r=s(T=>{if(t)try{t(T);}catch(d){o&&console.error("[agent] event handler threw:",d);}},"emit"),n=s((T,d)=>{Be[e.logLevel]>=Be[T]&&r({type:"log",level:T,message:d});},"log"),i=mo(e.skills),l=s(async(T,d)=>{if(!e.inputSanitizer)return d;try{return await e.inputSanitizer(T,d)}catch{return "[input redacted: sanitizer failed]"}},"sanitizeForApproval"),a=Dt(e.toolApproval,{sanitize:l,fallbackEmit:r}),c=ge(e.compaction),p={approval:a,maxToolCalls:e.maxToolCalls,maxToolOutputChars:c.maxToolOutputChars},g=Ce(fo(i),p,{builtIn:true}),h=e.toolSelectionStrategy??"auto",f=h==="search"||h==="auto",S=false,A=s(()=>[],"catalogRef"),w=f?Ce(ko(()=>A()),p,{builtIn:true}):void 0,R=s(T=>{for(let d of Object.keys(g))if(T[d])throw new Error(`Tool "${d}" collides with a built-in skill tool of the same name`);if(w&&T[te]){if(h==="search")throw new Error(`Tool "${te}" collides with the built-in tool-search tool of the same name`);S||(S=true,n("warn",`[tools] a tool named "${te}" shadows the built-in tool search; 'auto' stays on 'all'`));}},"assertNoBuiltinCollision"),j,y=s((T,d)=>{if(!e.tools)return T;let O=[];for(let[E,L]of Object.entries(e.tools)){if(T.tools[E]&&d(E),e.availableTools?.length&&!e.availableTools.includes(E)||!e.availableTools?.length&&e.excludedTools?.length&&e.excludedTools.includes(E))continue;T.tools[E]=L;let q=typeof L=="object"&&L&&"description"in L?L.description:"";O.push({name:E,description:typeof q=="string"?q:"",server:"<native>",readOnly:de(L)});}return {tools:T.tools,catalog:[...T.catalog,...O]}},"mergeNativeTools"),b=s(async()=>{let T=await to(e.mcpServers,n,e.clientName,e.outputSanitizer,E=>j?.(E),e.inputSanitizer,{connectTimeoutMs:e.mcpConnectTimeoutMs}),d=ut(T.tools,T.catalog,e.availableTools,e.excludedTools,n),O;try{O=y(d,E=>{throw new Error(`Native tool "${E}" collides with an MCP-registered tool of the same name`)}),R(O.tools);}catch(E){throw T.close().catch(()=>{}),E}return {connection:T,tools:Ce(O.tools,p),catalog:O.catalog}},"connect"),x;try{x=await b();}catch(T){throw r({type:"error",error:T instanceof Error?T:new Error(String(T)),phase:"init"}),T}let N=Object.keys(e.mcpServers).length;if(e.failOnNoTools&&N>0&&!x.connection.results.some(d=>d.connected)){let d=x.connection.results.filter(E=>!E.connected).map(E=>`${E.name}: ${E.error??"unknown"}`).join("; ");await x.connection.close().catch(()=>{});let O=new Error(`All ${N} configured MCP server(s) failed to connect [${d}]`);throw r({type:"error",error:O,phase:"init"}),O}let P,u,m;try{let T=Ne(e,void 0,void 0,"executor"),d=Ne(e,e.planner,e.plannerModel,"planner"),O=Ne(e,e.synthesizer,e.synthesizerModel,"synthesizer");[P,u,m]=await Promise.all([Ue(e.clientName,T),Ue(e.clientName,d),Ue(e.clientName,O)]);}catch(T){throw await x.connection.close().catch(()=>{}),r({type:"error",error:T instanceof Error?T:new Error(String(T)),phase:"init"}),T}let k=s(T=>T.map(d=>({name:d.name,description:d.description,server:d.server,readOnly:d.readOnly===true})),"toEntries"),v={config:e,executorModel:P,plannerModel:u,synthesizerModel:m,tools:x.tools,toolCatalog:k(x.catalog),emit:r,...Object.keys(g).length?{builtinTools:g}:{},...i.length?{skills:i}:{},approval:a};A=s(()=>v.toolCatalog,"catalogRef");let C=s(()=>{w&&!S?v.findTools=w:delete v.findTools;},"syncFindTools");C();let $=0,U=false,K=false,W=false,I=new Set,_=s(async T=>{await x.connection.refreshServer(T);let d=ut(x.connection.tools,x.connection.catalog,e.availableTools,e.excludedTools),O=y(d,L=>{throw new Error(`Native tool "${L}" collides with an MCP-registered tool of the same name`)});R(O.tools);let E=Ce(O.tools,p);for(let L of Object.keys(v.tools))delete v.tools[L];Object.assign(v.tools,E),v.toolCatalog=k(O.catalog),C(),n("info",`[mcp] ${T}: tool list refreshed (${O.catalog.length} tools total after filter)`);},"applyRefresh"),z=s(async()=>{if(!(W||U||K)&&!($>0||I.size===0)){W=true;try{for(;I.size>0&&$===0&&!U&&!K;){let T=I.values().next().value;I.delete(T);try{await _(T);}catch(d){n("warn",`[mcp] ${T}: refresh failed - ${d.message}`);}}}finally{W=false;}}},"drainPendingRefreshes");return j=s(T=>{I.add(T),z();},"onToolsChanged"),{run:s(async T=>{if(U)throw new Error("Agent is closed");if(K)throw new Error("Agent is reconnecting; retry shortly");if(W)throw new Error("Agent is refreshing tools; retry shortly");let d=e.maxConcurrentRuns;if(typeof d=="number"&&d>0&&$>=d)throw new Error(`maxConcurrentRuns reached (${$}/${d}); rate-limit on the caller side or raise the cap`);$++;try{return await Ko(v,T)}finally{$--,z();}},"run"),listTools:s(()=>v.toolCatalog.map(T=>({...T})),"listTools"),listSkills:s(()=>i.map(T=>({name:T.name,description:T.description})),"listSkills"),compact:s(async T=>{let d=await Ee(T.history,v.synthesizerModel,{thresholdTokens:c.thresholdTokens,keepRecentTurns:c.keepRecentTurns,summaryMaxTokens:Ie(e,c.summaryMaxTokens),force:T.force,signal:T.signal,timeoutMs:e.llmTimeoutMs,onUsage:s(O=>r({type:"usage",phase:"compact",usage:O}),"onUsage")});return d.compacted&&r({type:"context.compacted",scope:"history",beforeTokens:d.beforeTokens,afterTokens:d.afterTokens}),{history:d.history,...d.summary?{summary:d.summary}:{},beforeTokens:d.beforeTokens,afterTokens:d.afterTokens,compacted:d.compacted}},"compact"),setToolApprovalMode:s(T=>a.setMode(T),"setToolApprovalMode"),getToolApprovalMode:s(()=>a.getMode(),"getToolApprovalMode"),reconnect:s(async()=>{if(U)throw new Error("Agent is closed");if(K)throw new Error("Already reconnecting");if(W)throw new Error("Agent is refreshing tools; retry shortly");if($>0)throw new Error(`Cannot reconnect with ${$} active run(s)`);K=true;try{let T=x.connection;I.clear();let d=await b();for(let O of Object.keys(v.tools))delete v.tools[O];Object.assign(v.tools,d.tools),v.toolCatalog=k(d.catalog),C(),x=d,await T.close().catch(()=>{});}finally{K=false;}},"reconnect"),close:s(async T=>{U=true;let d=T?.waitForRuns??false,O=T?.timeoutMs??3e4,E=Date.now()+O;if(d&&$>0)for(;$>0&&Date.now()<E;)await new Promise(ue=>setTimeout(ue,50));$>0&&r({type:"log",level:"warn",message:`[agent] close called with ${$} active run(s); they will fail mid-flight`});let L=Math.max(E-Date.now(),0),q=false,H;await Promise.race([x.connection.close().catch(()=>{}),new Promise(ue=>{H=setTimeout(()=>{q=true,ue();},L),H.unref?.();})]),H&&clearTimeout(H),q&&r({type:"log",level:"warn",message:`[agent] MCP teardown exceeded ${L}ms; abandoning transport(s)`});},"close"),activeRuns:s(()=>$,"activeRuns")}},"createAgent");var Ye=["openai","anthropic","openai-compatible","google","xai","azure","amazon-bedrock","google-vertex","deepseek","gateway","cloudflare"],ds=new Set(["openai-compatible","azure"]),Ho=["none","error","warn","info","debug"],Wo=["all","plan-narrowed","search","auto"],qo=["provider-default","none","minimal","low","medium","high","xhigh"],Bo=["autopilot","ask-writes","ask-all","read-only"],Zo=s(()=>{let e=process.env.AGENT_PROVIDER_TYPE??"openai";if(!Ye.includes(e))throw new Error(`AGENT_PROVIDER_TYPE must be ${Ye.join(" | ")}, got: ${e}`);let t=process.env.AGENT_LOG_LEVEL??"info";if(!Ho.includes(t))throw new Error(`AGENT_LOG_LEVEL must be ${Ho.join(" | ")}, got: ${t}`);let o=ds.has(e)?Rt("AGENT_BASE_URL"):process.env.AGENT_BASE_URL?.trim()||void 0;return {clientName:process.env.AGENT_CLIENT_NAME??"vercel-mcp-test",providerType:e,baseURL:o,apiKey:Rt("AGENT_API_KEY"),model:Rt("AGENT_MODEL"),providerOptions:en("AGENT_PROVIDER_OPTIONS"),planner:Yo("AGENT_PLANNER"),synthesizer:Yo("AGENT_SYNTHESIZER"),plannerModel:process.env.AGENT_PLANNER_MODEL?.trim()||void 0,synthesizerModel:process.env.AGENT_SYNTHESIZER_MODEL?.trim()||void 0,mcpServers:ks(process.env.MCP_SERVERS),availableTools:Jo(process.env.AGENT_AVAILABLE_TOOLS),excludedTools:Jo(process.env.AGENT_EXCLUDED_TOOLS),maxIterations:Xo(process.env.AGENT_MAX_ITERATIONS,10),maxStepsPerTask:Xo(process.env.AGENT_MAX_STEPS_PER_TASK,8),maxRevisions:oe(process.env.AGENT_MAX_REVISIONS),maxTotalTokens:oe(process.env.AGENT_MAX_TOTAL_TOKENS),limits:gs(),maxToolCalls:oe(process.env.AGENT_MAX_TOOL_CALLS),thinking:ms(process.env.AGENT_THINKING),toolApproval:hs(process.env.AGENT_TOOL_APPROVAL,process.env.AGENT_TOOL_RULES),compaction:ys(),llmTimeoutMs:oe(process.env.AGENT_LLM_TIMEOUT_MS),llmMaxRetries:oe(process.env.AGENT_LLM_MAX_RETRIES),toolSelectionStrategy:Ts(process.env.AGENT_TOOL_SELECTION_STRATEGY),logLevel:t}},"loadConfig"),ms=s(e=>{let t=e?.trim().toLowerCase();if(!t)return;if(t==="off")return "none";if(qo.includes(t))return t;let o=Number(t);if(Number.isFinite(o)&&o>0)return {level:"medium",budgetTokens:Math.floor(o)};throw new Error(`AGENT_THINKING must be off | ${qo.join(" | ")} | <budget tokens>, got: ${e}`)},"parseThinking"),gs=s(()=>{let e={},t=oe(process.env.AGENT_MAX_INPUT_TOKENS),o=oe(process.env.AGENT_MAX_OUTPUT_TOKENS),r=oe(process.env.AGENT_MAX_REASONING_TOKENS);return t&&(e.maxInputTokens=t),o&&(e.maxOutputTokens=o),r&&(e.maxReasoningTokens=r),Object.keys(e).length?e:void 0},"parseLimits"),Vo=["allow","ask","deny"],fs=s(e=>{let t=e?.trim();if(!t)return;let o;try{o=JSON.parse(t);}catch{throw new Error('AGENT_TOOL_RULES must be a JSON object, e.g. {"github__delete_*":"deny"}')}if(!o||typeof o!="object"||Array.isArray(o))throw new Error('AGENT_TOOL_RULES must be a JSON object, e.g. {"github__delete_*":"deny"}');let r={};for(let[n,i]of Object.entries(o)){if(!n.trim())throw new Error("AGENT_TOOL_RULES: a rule needs a non-empty tool name or pattern");if(!Vo.includes(i))throw new Error(`AGENT_TOOL_RULES["${n}"] must be ${Vo.join(" | ")}, got: ${JSON.stringify(i)}`);r[n]=i;}return Object.keys(r).length?r:void 0},"parseToolRules"),hs=s((e,t)=>{let o=e?.trim();if(o&&!Bo.includes(o))throw new Error(`AGENT_TOOL_APPROVAL must be ${Bo.join(" | ")}, got: ${o}`);let r=fs(t);if(!(!o&&!r))return {...o?{mode:o}:{},...r?{rules:r}:{}}},"parseApproval"),ys=s(()=>{let e=process.env.AGENT_COMPACTION?.trim().toLowerCase(),t=oe(process.env.AGENT_CONTEXT_WINDOW_TOKENS),o={};if(e)if(["off","false","0","no"].includes(e))o.auto=false;else if(["on","auto","true","1","yes"].includes(e))o.auto=true;else throw new Error(`AGENT_COMPACTION must be on | off, got: ${process.env.AGENT_COMPACTION}`);return t&&(o.contextWindowTokens=t),Object.keys(o).length?o:void 0},"parseCompaction"),Qo=s(()=>process.env.AGENT_SKILLS_DIR?.trim()||void 0,"skillsDirFromEnv"),Yo=s(e=>{let t=process.env[`${e}_PROVIDER_TYPE`]?.trim(),o=process.env[`${e}_BASE_URL`]?.trim(),r=process.env[`${e}_API_KEY`]?.trim(),n=en(`${e}_PROVIDER_OPTIONS`);if(!(!t&&!o&&!r&&!n)){if(t&&!Ye.includes(t))throw new Error(`${e}_PROVIDER_TYPE must be ${Ye.join(" | ")}, got: ${t}`);return {providerType:t||void 0,baseURL:o||void 0,apiKey:r||void 0,providerOptions:n}}},"parseStageOverride"),en=s(e=>{let t=process.env[e]?.trim();if(!t)return;let o;try{o=JSON.parse(t);}catch(r){throw new Error(`${e} must be valid JSON: ${r.message}`)}if(!o||typeof o!="object"||Array.isArray(o))throw new Error(`${e} must be a JSON object (got ${typeof o})`);return o},"parseProviderOptions"),Ts=s(e=>{let t=e?.trim();if(t){if(!Wo.includes(t))throw new Error(`AGENT_TOOL_SELECTION_STRATEGY must be ${Wo.join(" | ")}, got: ${t}`);return t}},"parseToolStrategy"),oe=s(e=>{if(!e?.trim())return;let t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Expected non-negative number, got: ${e}`);return Math.floor(t)},"parseOptionalInt"),Rt=s(e=>{let t=process.env[e]?.trim();if(!t)throw new Error(`Missing required env var: ${e}`);return t},"required"),Jo=s(e=>{let t=e?.trim();if(t)return t.split(",").map(o=>o.trim()).filter(Boolean)},"parseList"),Xo=s((e,t)=>{if(!e?.trim())return t;let o=Number(e);if(!Number.isFinite(o)||o<=0)throw new Error(`Expected positive number, got: ${e}`);return Math.floor(o)},"parsePositiveInt"),ks=s(e=>{if(!e?.trim())return {};let t;try{t=JSON.parse(e);}catch(r){throw new Error(`MCP_SERVERS must be valid JSON: ${r.message}`)}if(!t||typeof t!="object"||Array.isArray(t))throw new Error("MCP_SERVERS must be a JSON object: Record<name, { url, headers? } | { command, args?, env?, cwd? }>");let o={};for(let[r,n]of Object.entries(t)){if(!n||typeof n!="object")throw new Error(`MCP_SERVERS.${r} must be an object`);let i=n,l=typeof i.url=="string"&&i.url.length>0,a=typeof i.command=="string"&&i.command.length>0;if(l&&a)throw new Error(`MCP_SERVERS.${r}: specify either "url" (HTTP) or "command" (stdio), not both`);if(!l&&!a)throw new Error(`MCP_SERVERS.${r}: must specify "url" (HTTP) or "command" (stdio)`);if(l){let c=i.headers&&typeof i.headers=="object"&&!Array.isArray(i.headers)?i.headers:void 0;o[r]={url:i.url,headers:c};continue}if(i.args!==void 0&&!Array.isArray(i.args))throw new Error(`MCP_SERVERS.${r}.args must be a string array`);if(i.env!==void 0&&(!i.env||typeof i.env!="object"||Array.isArray(i.env)))throw new Error(`MCP_SERVERS.${r}.env must be a string-to-string map`);if(i.cwd!==void 0&&typeof i.cwd!="string")throw new Error(`MCP_SERVERS.${r}.cwd must be a string`);o[r]={command:i.command,args:i.args,env:i.env,cwd:i.cwd};}return o},"parseMcpServers");var tn=s(e=>{let t=e.trim();return t?t==="/agents"?{kind:"agents"}:t==="/stop"||t.startsWith("/stop ")?{kind:"stop",target:t.slice(5).trim()}:/^\/[\w-]+(\s|$)/.test(t)?{kind:"hint"}:{kind:"say",text:t}:{kind:"ignore"}},"parseLiveLine"),pe=s(e=>e.slice(0,8),"shortId"),on=s((e,t)=>{if(e.length===0)return "no subagent is running";if(!t)return e.length===1?e[0]:`${e.length} subagents are running - say which: /stop <number> (see /agents)`;if(/^\d+$/.test(t))return e[Number(t)-1]??`there is no subagent number ${t} (${e.length} running)`;let o=e.filter(r=>r.id.startsWith(t));return o.length===1?o[0]:o.length===0?`no running subagent has an id starting with "${t}"`:`"${t}" matches ${o.length} subagents - give more of the id`},"resolveSubagent"),nn=s((e,t=Date.now())=>e.map((o,r)=>{let n=Math.max(0,Math.round((t-o.startedAt)/1e3)),i=o.task.replace(/\s+/g," ").trim();return ` ${r+1}. ${o.name}${o.profile?` [${o.profile}]`:""} ${pe(o.id)} (${n}s): ${i.length>100?`${i.slice(0,100)}...`:i}`}),"describeSubagents");var vs=16,rn=["autopilot","ask-writes","ask-all","read-only"],Ss=stdout.isTTY?"\x1B[2m":"",Is=stdout.isTTY?"\x1B[22m":"",J=s((e,t=240)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}...`:o},"truncate"),Je=s(e=>{try{return J(JSON.stringify(e))}catch{return String(e)}},"formatJson"),sn=s(e=>e===void 0||e===false?"provider default":e===true?"medium":typeof e=="string"?e:`${e.level??"medium"}${e.budgetTokens?` (budget ${e.budgetTokens})`:""}`,"describeThinking"),As=s(e=>{for(;e.length>vs;){let t=e.length&&Ae(e[0])?1:0;e.splice(t,1);}},"trimHistory"),an=s(async()=>{let e=Zo(),t=Qo();t&&(e.skills=await ft(t));let o=Object.keys(e.mcpServers),r=e.planner?.model??e.plannerModel??e.model,n=e.synthesizer?.model??e.synthesizerModel??e.model;console.log(`[session] model=${e.model} planner=${r} synth=${n} provider=${e.providerType}`),console.log(`[session] maxIterations=${e.maxIterations} maxStepsPerTask=${e.maxStepsPerTask} timeoutMs=${e.llmTimeoutMs??"none"} retries=${e.llmMaxRetries??2}`),console.log(`[session] thinking=${sn(e.thinking)} approval=${e.toolApproval?.mode??"autopilot"}${e.toolApproval?.rules?` rules=${Object.keys(e.toolApproval.rules).length}`:""} skills=${e.skills?.length??0}`),console.log(`[mcp] servers=${o.length?o.join(", "):"(none)"}`),console.log(`[hint] commands: /status, /tools, /history, /reset, /compact, /autopilot, /approval <mode>, /reconnect, /exit
|
|
185
|
+
`);let i="none",l=[],a=s(()=>{i!=="none"&&(process.stdout.write(i==="reasoning"?`${Is}
|
|
173
186
|
`:`
|
|
174
187
|
`),i="none");},"endLine"),c=s(u=>{switch(u.type){case "log":a(),console.log(`[${u.level}] ${u.message}`);break;case "plan.thought-delta":i!=="thought"&&(a(),process.stdout.write(`
|
|
175
188
|
[plan] `),i="thought"),process.stdout.write(u.delta);break;case "plan.step-added":a(),console.log(` ${u.index+1}. ${u.step.description}`);break;case "plan.created":i==="thought"?a():(a(),console.log(`
|
|
176
|
-
[plan] ${u.plan.thought}`));for(let[m,
|
|
177
|
-
[replan] reason=${u.reason}`);for(let[m,
|
|
178
|
-
[step ${u.index+1}] ${u.step.description}`);break;case "step.reasoning-delta":case "final.reasoning-delta":i!=="reasoning"&&(a(),process.stdout.write(`${
|
|
189
|
+
[plan] ${u.plan.thought}`));for(let[m,k]of u.plan.steps.entries()){let v=k.suggestedTools?.length?` (tools: ${k.suggestedTools.join(", ")})`:"";console.log(` ${m+1}. ${k.description}${v}`);}break;case "plan.revised":a(),console.log(`
|
|
190
|
+
[replan] reason=${u.reason}`);for(let[m,k]of u.plan.steps.entries())console.log(` ${m+1}. ${k.description}`);break;case "skill.activated":a(),console.log(`[skill] ${u.name} (by ${u.by})`);break;case "step.start":a(),console.log(`
|
|
191
|
+
[step ${u.index+1}] ${u.step.description}`);break;case "step.reasoning-delta":case "final.reasoning-delta":i!=="reasoning"&&(a(),process.stdout.write(`${Ss}[think] `),i="reasoning"),process.stdout.write(u.delta);break;case "step.tool-call":a(),console.log(` -> ${u.name} ${Je(u.input)}`);break;case "step.tool-result":{a();let m=u.ok?"ok":"fail";console.log(` <- ${u.name} ${m} ${Je(u.output)}`);break}case "tools.discovered":a(),console.log(` ?? find_tools "${u.query}" -> ${u.names.length?u.names.join(", "):"(nothing)"}`);break;case "tool.approval-resolved":u.automatic&&!u.approved&&(a(),console.log(` !! ${u.name} denied: ${u.reason??"no reason"}`));break;case "subagent.start":a(),console.log(` >> subagent ${u.name} ${pe(u.id)}${u.profile?` [${u.profile}]`:""}: ${J(u.task,160)}`);break;case "subagent.event":{let m=u.event,k=`${u.name} ${pe(u.id)}`;m.type==="step.start"?(a(),console.log(` [${k}] step ${m.index+1}: ${J(m.step.description,120)}`)):m.type==="step.tool-call"?(a(),console.log(` [${k}] -> ${m.name} ${Je(m.input)}`)):m.type==="step.tool-result"&&(a(),console.log(` [${k}] <- ${m.name} ${m.ok?"ok":"fail"}`));break}case "subagent.complete":a(),console.log(` << subagent ${u.name} done (${u.usage.totalTokens} tokens): ${J(u.text,160)}`);break;case "subagent.error":a(),console.log(u.stopped?` << subagent ${u.name} ${pe(u.id)} stopped by you`:` << subagent ${u.name} failed: ${u.error}`);break;case "message.queued":a(),console.log(`[you->agent] queued, the agent sees it at its next boundary: ${J(u.text,160)}`);break;case "message.delivered":a(),console.log(`[you->agent] delivered (${u.at}): ${J(u.text,160)}`),l.push(u.text);break;case "step.complete":a(),console.log(` = ${J(u.result.summary,400)} (${u.result.durationMs}ms, ${u.result.toolCalls.length} tool calls)`);break;case "replan.decision":(u.mode!=="continue"||u.cause==="user-message")&&(a(),console.log(`[replan] ${u.mode} (${u.cause}): ${u.reason}`));break;case "usage":break;case "retry":a(),console.log(`[retry] ${u.phase} attempt=${u.attempt}: ${u.error}`);break;case "budget.exceeded":a(),console.log(`[budget] ${u.kind} cap reached: ${u.tokens}/${u.cap} - finishing early`);break;case "revisions.exceeded":a(),console.log(`[budget] max ${u.cap} replan-revisions reached - finishing early`);break;case "context.compacted":a(),console.log(`[compact] ${u.scope}: ~${u.beforeTokens} -> ~${u.afterTokens} tokens`);break;case "final.text-delta":i!=="final"&&(a(),process.stdout.write(`
|
|
179
192
|
assistant> `),i="final"),process.stdout.write(u.delta);break;case "final":i==="final"?(process.stdout.write(`
|
|
180
193
|
|
|
181
194
|
`),i="none"):(a(),console.log(`
|
|
182
195
|
assistant> ${u.text}
|
|
183
|
-
`));break;case "error":a(),console.error(`[error] (${u.phase}) ${u.error.message}`);break}},"onEvent"),
|
|
184
|
-
allow? [y]es / [n]o / [a]lways: `,
|
|
185
|
-
[abort] forcing exit`),process.exit(130)),
|
|
186
|
-
[abort] cancelling current run...`),
|
|
187
|
-
you> `,{signal:d.signal})).trim(),D=0;}catch(m){if(m?.name==="AbortError")break;break}finally{d=null;}if(u){if(u==="/exit"||u==="/quit")break;if(u==="/tools"){if(A.length===0)console.log("[tools] (none)");else for(let m of A)console.log(` - ${m.name}${m.readOnly?" (read-only)":""}: ${ge(m.description,200)}`);continue}if(u==="/status"){let m=e.limits??{},x=[m.maxInputTokens?`in=${m.maxInputTokens}`:"",m.maxOutputTokens?`out=${m.maxOutputTokens}`:"",m.maxReasoningTokens?`reasoning=${m.maxReasoningTokens}`:"",m.maxTotalTokens??e.maxTotalTokens?`total=${m.maxTotalTokens??e.maxTotalTokens}`:"",e.maxToolCalls?`toolCalls=${e.maxToolCalls}`:""].filter(Boolean);console.log(`[status] model=${e.model} planner=${n} synth=${r}`),console.log(`[status] tools=${A.length} strategy=${e.toolSelectionStrategy??"auto"} mcp=${o.join(", ")||"(none)"} historyTurns=${$.length}`),console.log(`[status] thinking=${Wo(e.thinking)} approval=${y.getToolApprovalMode()} limits=${x.length?x.join(" "):"(none)"}`),console.log(`[status] compaction=${e.compaction?.auto===!1?"manual":"auto"} window=${e.compaction?.contextWindowTokens??128e3} skills=${y.listSkills().map(R=>R.name).join(", ")||"(none)"}`);continue}if(u==="/history"){if($.length===0)console.log("[history] (empty)");else for(let m of $)console.log(` ${m.role}: ${ge(m.content,200)}`);continue}if(u==="/reset"){$.length=0,console.log("[history] cleared");continue}if(u==="/compact"){let m=await y.compact({history:$,force:!0});m.compacted?($.splice(0,$.length,...m.history),console.log(`[compact] history: ~${m.beforeTokens} -> ~${m.afterTokens} tokens`)):console.log("[compact] nothing to compact");continue}if(u==="/autopilot"){let m=y.getToolApprovalMode();m==="autopilot"?y.setToolApprovalMode(k):(k=m,y.setToolApprovalMode("autopilot")),console.log(`[approval] mode=${y.getToolApprovalMode()}`);continue}if(u==="/approval"||u.startsWith("/approval ")){let m=u.slice(9).trim();m?Ho.includes(m)?(y.setToolApprovalMode(m),m!=="autopilot"&&(k=m),console.log(`[approval] mode=${m}`)):console.log(`[approval] unknown mode "${m}"; use ${Ho.join(" | ")}`):console.log(`[approval] mode=${y.getToolApprovalMode()}`);continue}if(u==="/reconnect"){try{await y.reconnect();let m=y.listTools();A.length=0;for(let x of m)A.push(x);console.log(`[mcp] reconnected, ${A.length} tools available`);}catch(m){console.error("[error] reconnect failed:",m.message);}continue}i="none",p=new AbortController;try{let m=await y.run({input:u,history:$,signal:p.signal});D=0,m.compactedHistory&&$.splice(0,$.length,...m.compactedHistory),$.push({role:"user",content:u}),$.push({role:"assistant",content:m.text}),ls($);let x=m.usage;console.log(`[meta] iterations=${m.iterations} steps=${m.trace.length} tokens=${x.totalTokens} (in=${x.inputTokens} out=${x.outputTokens}${x.reasoningTokens?` reasoning=${x.reasoningTokens}`:""}${x.cachedInputTokens?` cached=${x.cachedInputTokens}`:""})`);}catch(m){a(),m?.name==="AbortError"?(console.log("[abort] run cancelled"),D=0):console.error("[error]",m.message);}finally{p=null;}}}}finally{process.off("SIGINT",h),l.off("SIGINT",h),l.close(),await y.close({timeoutMs:5e3}).catch(u=>console.error("[cleanup] agent",u));}},"runRepl");var cs=s(async()=>{let e;try{e=Ot(process.argv.slice(2));}catch(t){console.error(t.message),console.error("\nRun `dd-agent --help` for usage."),process.exit(2);}if(e.help){process.stdout.write(Et);return}if(e.envFile)try{process.loadEnvFile(e.envFile);}catch(t){console.error(`Failed to load env file ${e.envFile}: ${t.message}`),process.exit(2);}for(let[t,o]of Object.entries(e.overrides))process.env[t]=o;try{await qo();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
|
|
196
|
+
`));break;case "error":a(),console.error(`[error] (${u.phase}) ${u.error.message}`);break}},"onEvent"),p=createInterface({input:stdin,output:stdout}),g=null,h=null,f=null,S,A=Promise.resolve(),w=s(u=>{let m=s(async()=>{a();let v=(await p.question(`[approve] ${u.toolName} ${Je(u.input)}${u.readOnly?" (read-only)":""}
|
|
197
|
+
allow? [y]es / [n]o / [a]lways: `,g?{signal:g.signal}:{})).trim().toLowerCase();return v==="a"||v==="always"?{approved:true,remember:true}:v==="y"||v==="yes"?true:{approved:false,reason:"denied at the prompt"}},"ask"),k=A.then(m,m);return A=k.catch(()=>{}),k},"askApproval");e.toolApproval={...e.toolApproval,onRequest:w};let R=await Ve(e,c),j=R.getToolApprovalMode()==="autopilot"?"ask-writes":R.getToolApprovalMode(),y=R.listTools();console.log(`[tools] available=${y.length}${y.length?`: ${y.map(u=>u.name).join(", ")}`:""}`);let b=[],x=0,N=s(()=>{if(x++,x>=2&&(console.log(`
|
|
198
|
+
[abort] forcing exit`),process.exit(130)),g){console.log(`
|
|
199
|
+
[abort] cancelling current run...`),g.abort();return}if(h){h.abort();return}},"onSigInt");process.on("SIGINT",N),p.on("SIGINT",N);let P=s(u=>{let m=tn(u);switch(m.kind){case "ignore":return;case "hint":a(),console.log("[hint] commands work between runs. During a run: type text to tell the agent something, /agents, /stop <n>, Ctrl-C to cancel");return;case "agents":{a();let k=f?.subagents()??[];console.log(k.length?"[agents]":"[agents] (none running)");for(let v of nn(k))console.log(v);return}case "stop":{a();let k=on(f?.subagents()??[],m.target);typeof k=="string"?console.log(`[stop] ${k}`):f?.stopSubagent(k.id)?console.log(`[stop] stopping ${k.name} ${pe(k.id)}...`):console.log(`[stop] ${k.name} ${pe(k.id)} already finished`);return}case "say":f?.send(m.text)||(S=S?`${S}
|
|
188
200
|
|
|
189
|
-
|
|
201
|
+
${m.text}`:m.text);return}},"onLiveLine");try{for(;;){let u;if(S!==void 0)u=S,S=void 0,console.log(`
|
|
202
|
+
[follow-up] sending what the last run never showed the agent: ${J(u,200)}`);else {h=new AbortController;try{u=(await p.question(`
|
|
203
|
+
you> `,{signal:h.signal})).trim(),x=0;}catch(m){if(m?.name==="AbortError")break;break}finally{h=null;}}if(u){if(u==="/exit"||u==="/quit")break;if(u==="/tools"){if(y.length===0)console.log("[tools] (none)");else for(let m of y)console.log(` - ${m.name}${m.readOnly?" (read-only)":""}: ${J(m.description,200)}`);continue}if(u==="/status"){let m=e.limits??{},k=[m.maxInputTokens?`in=${m.maxInputTokens}`:"",m.maxOutputTokens?`out=${m.maxOutputTokens}`:"",m.maxReasoningTokens?`reasoning=${m.maxReasoningTokens}`:"",m.maxTotalTokens??e.maxTotalTokens?`total=${m.maxTotalTokens??e.maxTotalTokens}`:"",e.maxToolCalls?`toolCalls=${e.maxToolCalls}`:""].filter(Boolean);console.log(`[status] model=${e.model} planner=${r} synth=${n}`),console.log(`[status] tools=${y.length} strategy=${e.toolSelectionStrategy??"auto"} mcp=${o.join(", ")||"(none)"} historyTurns=${b.length}`),console.log(`[status] thinking=${sn(e.thinking)} approval=${R.getToolApprovalMode()} limits=${k.length?k.join(" "):"(none)"}`),console.log(`[status] compaction=${e.compaction?.auto===!1?"manual":"auto"} window=${e.compaction?.contextWindowTokens??128e3} skills=${R.listSkills().map(v=>v.name).join(", ")||"(none)"}`);continue}if(u==="/history"){if(b.length===0)console.log("[history] (empty)");else for(let m of b)console.log(` ${m.role}: ${J(m.content,200)}`);continue}if(u==="/reset"){b.length=0,console.log("[history] cleared");continue}if(u==="/compact"){let m=await R.compact({history:b,force:!0});m.compacted?(b.splice(0,b.length,...m.history),console.log(`[compact] history: ~${m.beforeTokens} -> ~${m.afterTokens} tokens`)):console.log("[compact] nothing to compact");continue}if(u==="/autopilot"){let m=R.getToolApprovalMode();m==="autopilot"?R.setToolApprovalMode(j):(j=m,R.setToolApprovalMode("autopilot")),console.log(`[approval] mode=${R.getToolApprovalMode()}`);continue}if(u==="/approval"||u.startsWith("/approval ")){let m=u.slice(9).trim();m?rn.includes(m)?(R.setToolApprovalMode(m),m!=="autopilot"&&(j=m),console.log(`[approval] mode=${m}`)):console.log(`[approval] unknown mode "${m}"; use ${rn.join(" | ")}`):console.log(`[approval] mode=${R.getToolApprovalMode()}`);continue}if(u==="/agents"){console.log("[agents] (none running - subagents show here while a run goes)");continue}if(u==="/reconnect"){try{await R.reconnect();let m=R.listTools();y.length=0;for(let k of m)y.push(k);console.log(`[mcp] reconnected, ${y.length} tools available`);}catch(m){console.error("[error] reconnect failed:",m.message);}continue}i="none",g=new AbortController,f=dt(),l.length=0,p.on("line",P);try{let m=await R.run({input:u,history:b,signal:g.signal,control:f});x=0,m.undelivered?.length&&(S=S?`${S}
|
|
204
|
+
|
|
205
|
+
${m.undelivered.join(`
|
|
206
|
+
|
|
207
|
+
`)}`:m.undelivered.join(`
|
|
208
|
+
|
|
209
|
+
`)),m.compactedHistory&&b.splice(0,b.length,...m.compactedHistory),b.push({role:"user",content:u});for(let v of l)b.push({role:"user",content:v});b.push({role:"assistant",content:m.text}),As(b);let k=m.usage;console.log(`[meta] iterations=${m.iterations} steps=${m.trace.length} tokens=${k.totalTokens} (in=${k.inputTokens} out=${k.outputTokens}${k.reasoningTokens?` reasoning=${k.reasoningTokens}`:""}${k.cachedInputTokens?` cached=${k.cachedInputTokens}`:""})`);}catch(m){a(),m?.name==="AbortError"?(console.log("[abort] run cancelled"),x=0):console.error("[error]",m.message);let k=f?.pending()??[];if(k.length){console.log(`[not delivered] ${k.length} message(s) the agent never saw:`);for(let v of k)console.log(` - ${J(v,200)}`);}}finally{p.off("line",P),f=null,g=null;}}}}finally{process.off("SIGINT",N),p.off("SIGINT",N),p.close(),await R.close({timeoutMs:5e3}).catch(u=>console.error("[cleanup] agent",u));}},"runRepl");var Es=s(async()=>{let e;try{e=Mt(process.argv.slice(2));}catch(t){console.error(t.message),console.error("\nRun `dd-agent --help` for usage."),process.exit(2);}if(e.help){process.stdout.write(Pt);return}if(e.envFile)try{process.loadEnvFile(e.envFile);}catch(t){console.error(`Failed to load env file ${e.envFile}: ${t.message}`),process.exit(2);}for(let[t,o]of Object.entries(e.overrides))process.env[t]=o;try{await an();}catch(t){let o=t instanceof Error?t.message:String(t);throw o.startsWith("Missing required env var")&&(console.error(`${o}
|
|
210
|
+
|
|
211
|
+
Run \`dd-agent --help\` to see required env vars, or pass --env-file=<path>.`),process.exit(2)),t}},"main");Es().catch(e=>{console.error(e),process.exit(1);});
|