@dudko.dev/agent 0.0.35 → 0.0.36

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/dist/cli.js CHANGED
@@ -55,7 +55,7 @@ ${T}`},...e.slice(c)];return {history:f,summary:T,beforeTokens:n,afterTokens:se(
55
55
  ${t}
56
56
  `:"",`Steps to summarize:
57
57
  ${n.render(e,n.offset)}`].filter(Boolean).join(`
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(`
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.36"};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
59
  `);let r=t?.sandboxDir,i=t?.toolName??"tool",a,c=s(()=>r?(a||(a=mkdir(r,{recursive:true}).then(()=>{})),a):Promise.resolve(),"ensureDir"),l=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){l.push(p.text);continue}if(r&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let d=await Bt(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,i,r,c);l.push(d);continue}if(r&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let d=p.resource;if(typeof d.blob=="string"){let T=await Bt(d.blob,typeof d.mimeType=="string"?d.mimeType:void 0,"resource",i,r,c);typeof d.uri=="string"&&(T.uri=d.uri),l.push(T);continue}if(typeof d.text=="string"){l.push(d.text);continue}}l.push(p);}return l},"flattenContent"),at=s((e,t,o,n,r)=>{let i=o?.length?new Set(o.map(Ie)):null,a=n?.length?new Set(n.map(Ie)):null,c=new Set,l={},p=[];for(let d of t){if((i?.has(d.name)||a?.has(d.name))&&c.add(d.name),i&&!i.has(d.name)||!i&&a?.has(d.name))continue;let T=e[d.name];T&&(l[d.name]=T,p.push(d));}if(r)for(let[d,T]of [["availableTools",o],["excludedTools",n]])for(let f of T??[])c.has(Ie(f))||r("warn",`[mcp] ${d}: "${f}" matches no discovered tool`);return {tools:l,catalog:p}},"filterTools");var _e=s((e,t,o,n)=>{let r=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,a=t?.baseURL??e.baseURL,c=t?.model??o??e.model,l=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(Hn.has(r)&&!a)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:a,apiKey:i,model:c,providerOptions:l}},"resolveStage"),Hn=new Set(["openai-compatible","azure"]),Y={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"},J=s(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),$e=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await J(Y.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await J(Y.anthropic);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await J(Y["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await J(Y.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await J(Y.xai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await J(Y.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await J(Y["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await J(Y["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await J(Y.deepseek);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let r=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...a}=o;if(!r&&!("binding"in a))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await J(Y.cloudflare),l="binding"in a?a:{accountId:r,apiKey:t.apiKey,...a};return c(l)(t.model)}}},"buildModelFromStage");var Wn=s(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,r)=>n.type==="tool-result"?[`${o}:${r}`]:[]):[]),"positionsOf"),qn=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Jt=s(e=>{try{return se(JSON.stringify(e))}catch{return 0}},"estimate"),lt=s((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,r=s(i=>n.size===0?i:i.map((a,c)=>a.role==="tool"&&Array.isArray(a.content)?{...a,content:a.content.map((l,p)=>l.type==="tool-result"&&n.has(`${c}:${p}`)?{...l,output:{type:"text",value:qn(l.toolName)}}:l)}:a),"apply");return i=>{let a=r(i),c=Jt(a);if(c<=e.triggerTokens)return a;let l=Wn(i),p=0;for(let T of l.slice(0,Math.max(0,l.length-o)))n.has(T)||(n.add(T),p+=1);if(p===0)return a;let d=r(i);return t?.({cleared:p,beforeTokens:c,afterTokens:Jt(d)}),d}},"createToolResultClearer");var Zt=/^[a-z0-9-]{1,64}$/,Vn="load_skill",Yn="read_skill_file",Jn=24e3,to=s(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=ie.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"),ct=s(e=>{if(!e||typeof e!="object")throw new Error("skill must be an object { name, description, content, files? }");let{name:t,description:o,content:n,files:r}=e;if(typeof t!="string"||!Zt.test(t))throw new Error(`skill name must match ${Zt} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof n!="string")throw new Error(`skill "${t}": content must be a string`);if(r!==void 0&&!Array.isArray(r))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,a=(r??[]).map(c=>{if(!c||typeof c.path!="string"||typeof c.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let l;try{l=to(c.path);}catch(p){throw new Error(`skill "${t}": ${p.message}`)}if(i.has(l))throw new Error(`skill "${t}": duplicate file "${l}"`);return i.add(l),{path:l,content:c.content}});return {name:t,description:o.trim(),content:n,...a.length?{files:a}:{}}},"defineSkill"),Xn=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"),Zn=s(e=>{let t={},o=e.split(`
60
60
  `);for(let n=0;n<o.length;n++){let r=o[n],i=/^([A-Za-z0-9_-]+)\s*:(.*)$/.exec(r);if(!i)continue;let a=i[1],c=i[2].trim(),l=/^([>|])([+-]?)\s*(#.*)?$/.exec(c);if(l){let p=[];for(;n+1<o.length&&(/^\s/.test(o[n+1])||o[n+1].trim()==="");)p.push(o[++n]);for(;p.length&&p[p.length-1].trim()==="";)p.pop();let d=Math.min(...p.filter(f=>f.trim()).map(f=>/^\s*/.exec(f)[0].length)),T=p.map(f=>f.slice(Number.isFinite(d)?d:0));t[a]=l[1]==="|"?T.join(`
61
61
  `):T.join(`
package/dist/index.cjs CHANGED
@@ -9,7 +9,7 @@ ${f}`},...e.slice(c)];return {history:u,summary:f,beforeTokens:n,afterTokens:se(
9
9
  ${t}
10
10
  `:"",`Steps to summarize:
11
11
  ${n.render(e,n.offset)}`].filter(Boolean).join(`
12
- `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:G(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:z(r.usage)}:void 0}catch{return}},"summarizeTrace"),Kt=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:ce(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:ce(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:ce(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Xo=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),rt=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Kt(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Re={version:"0.0.35"};var an=ie__default.default.join(sn__default.default.homedir(),".agent","mcp-oauth.json"),Ee=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await promises.readFile(this.filePath,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}async writeAll(t){let o=`${this.filePath}.${process.pid}.tmp`;await promises.writeFile(o,JSON.stringify(t,null,2),{mode:384}),await promises.chmod(o,384).catch(()=>{}),await promises.rename(o,this.filePath);}enqueue(t){let o=this.queue.then(t,t);return this.queue=o.catch(()=>{}),o}async get(t){return this.enqueue(async()=>(await this.readAll())[t])}async set(t,o){await this.enqueue(async()=>{let n=await this.readAll();n[t]=o,await promises.mkdir(ie__default.default.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(t){await this.enqueue(async()=>{let o=await this.readAll();t in o&&(delete o[t],await this.writeAll(o));});}},st=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(t){return this.map.get(t)}async set(t,o){this.map.set(t,o);}async delete(t){this.map.delete(t);}},ln=30,cn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),pn=new Set(["localhost","127.0.0.1","[::1]","::1"]),it=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||pn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Pe=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Ee,this.ns=cn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??ln)*1e3,this.onAuthorizationUrl=t.onAuthorizationUrl,this._clientMetadata={client_name:t.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...t.scope?{scope:t.scope}:{},...t.clientMetadata},it(t.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(t){return `${this.ns}:${t}`}async readJSON(t){let o=await this.store.get(this.key(t));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(t));return}}async state(){let t=crypto.randomBytes(32).toString("hex");return await this.store.set(this.key("state"),t),t}async verifyState(t){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&t!==void 0&&o===t}async clientInformation(){return this.readJSON("client")}async saveClientInformation(t){await this.store.set(this.key("client"),JSON.stringify(t));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(t){let o={tokens:t,expiresAt:typeof t.expires_in=="number"?Date.now()+t.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(t){await this.store.set(this.key("verifier"),t);}async codeVerifier(){let t=await this.store.get(this.key("verifier"));if(!t)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return t}async redirectToAuthorization(t){this.authorizationUrl=t,await this.onAuthorizationUrl?.(t);}async invalidateCredentials(t){let o=t==="all"?["tokens","client","verifier","state"]:[t];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let t=await this.readJSON("tokens");return t?.tokens?.access_token?t.expiresAt===void 0?false:Date.now()+this.skewMs>=t.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},un=s(e=>new Pe(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth_js.auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),mn=s(async(e,t,o={})=>{if(!await e.verifyState(t.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth_js.auth(e,{serverUrl:e.serverUrl,authorizationCode:t.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var hn="@dudko.dev/agent",yn=Re.version,at,Tn=s(()=>(at||(at=api.trace.getTracer(hn,yn)),at),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},J=s(async(e,t,o)=>Tn().startActiveSpan(e,async n=>{for(let[r,i]of Object.entries(t))i!==void 0&&n.setAttribute(r,i);try{let r=await o(n);return n.end(),r}catch(r){let i=r instanceof Error?r:new Error(String(r));throw n.recordException(i),n.setStatus({code:api.SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Ln=s(e=>"command"in e&&!!e.command,"isStdioConfig"),$n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Un=Re.version,lt=64,ve=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),_n=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,lt-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Me=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Jt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Jt;i++){let l=await e.listTools(n?{cursor:n}:void 0);o.push(...l.tools);let c=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!c||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),de=class extends Error{static{s(this,"RefreshOnlyAbort");}},zn=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new de},"state"),saveCodeVerifier:s(()=>{throw new de},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new de},"redirectToAuthorization")}),"refreshOnly"),jn=s(async(e,t,o,n,r)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth_js.auth(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof de?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Gt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,O)=>{let H=`${ve(g)}__`;for(let I of f.get(g)??[])delete a[I];for(let I=p.length-1;I>=0;I--)p[I].server===g&&p.splice(I,1);let $=[],_=0,R=0;for(let I of O){let v=H+ve(I.name);if(v.length>lt){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${lt}-char limit enforced by major LLM providers; skipping`),R++;continue}let C=_n(v,a);if(!C){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}C!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${C}"`);let U=I.description??"",W=I.annotations?.readOnlyHint===true;a[C]=ai.dynamicTool({description:U,inputSchema:ai.jsonSchema(I.inputSchema),execute:s(async(q,k)=>J("agent.tool_call",{[E.TOOL_NAME]:C},async P=>{let D=q??{};if(i)try{let S=await i(C,D);D=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${C}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),D={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:D},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let m=w.isError===true,y=w.content;if(n)try{y=await n(C,y);}catch(S){if(t("warn",`[mcp] ${C}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Me("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:C,sandboxDir:m?void 0:qe()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Me(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&V(a[C]),p.push({name:C,description:U,server:g,readOnly:W}),$.push(C),_++;}f.set(g,$),R>0?t("info",`[mcp] ${g}: ${_} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${_} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Jt} pages; the rest is ignored`)),"listServerTools"),T=s(async(g,b)=>{u(g,b,await h(g,b));},"registerServerTools"),x=s(async(g,b)=>{let O=b.connectTimeoutMs??l.connectTimeoutMs,H=typeof O=="number"&&Number.isFinite(O)&&O>=0?O:Nn,$,_=false,R=K(g,b,I=>{$=I;},()=>_);try{return await(H>0?Fn(R,H,()=>{_=!0;}):R)}catch(I){$&&await $.close().catch(()=>{});let v=_?`connect timed out after ${H}ms`:I.message,C=!_&&I instanceof auth_js.UnauthorizedError;return t("error",C?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:C}}},"openConnection"),K=s(async(g,b,O,H)=>{let $,_=s(async()=>{if(H())throw await $?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(b)){let v=b.env?{...stdio_js.getDefaultEnvironment(),...b.env}:void 0;R=new stdio_js.StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if($n(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),it(b.url,`MCP server "${g}"`),await jn(b.authProvider,b.url,b.fetch,t,g)),R=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await _(),$=new index_js.Client({name:o,version:Un}),O($),await $.connect(R),await _(),r&&$.setNotificationHandler(types_js.ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,$);return await _(),{name:g,client:$,listed:I}}catch(R){throw $&&await $.close().catch(()=>{}),R}},"connectOnce"),L=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of L){if(!g.client||!g.listed){d.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),u(g.name,g.client,g.listed),d.push({name:g.name,connected:true});}return {tools:a,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:s(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await T(g,b);},"refreshServer")}},"connectMcpServers"),Fn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),n(l);},l=>{clearTimeout(i),r(l);});}),"withConnectTimeout"),qt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return qt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?qt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Hn=/[^a-zA-Z0-9_-]/g,Bt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=crypto.randomUUID().slice(0,8),p=ie__default.default.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await promises.writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Wn=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
12
+ `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:G(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:z(r.usage)}:void 0}catch{return}},"summarizeTrace"),Kt=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:ce(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:ce(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:ce(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Xo=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),rt=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Kt(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Re={version:"0.0.36"};var an=ie__default.default.join(sn__default.default.homedir(),".agent","mcp-oauth.json"),Ee=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await promises.readFile(this.filePath,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}async writeAll(t){let o=`${this.filePath}.${process.pid}.tmp`;await promises.writeFile(o,JSON.stringify(t,null,2),{mode:384}),await promises.chmod(o,384).catch(()=>{}),await promises.rename(o,this.filePath);}enqueue(t){let o=this.queue.then(t,t);return this.queue=o.catch(()=>{}),o}async get(t){return this.enqueue(async()=>(await this.readAll())[t])}async set(t,o){await this.enqueue(async()=>{let n=await this.readAll();n[t]=o,await promises.mkdir(ie__default.default.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(t){await this.enqueue(async()=>{let o=await this.readAll();t in o&&(delete o[t],await this.writeAll(o));});}},st=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(t){return this.map.get(t)}async set(t,o){this.map.set(t,o);}async delete(t){this.map.delete(t);}},ln=30,cn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),pn=new Set(["localhost","127.0.0.1","[::1]","::1"]),it=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||pn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Pe=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Ee,this.ns=cn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??ln)*1e3,this.onAuthorizationUrl=t.onAuthorizationUrl,this._clientMetadata={client_name:t.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...t.scope?{scope:t.scope}:{},...t.clientMetadata},it(t.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(t){return `${this.ns}:${t}`}async readJSON(t){let o=await this.store.get(this.key(t));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(t));return}}async state(){let t=crypto.randomBytes(32).toString("hex");return await this.store.set(this.key("state"),t),t}async verifyState(t){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&t!==void 0&&o===t}async clientInformation(){return this.readJSON("client")}async saveClientInformation(t){await this.store.set(this.key("client"),JSON.stringify(t));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(t){let o={tokens:t,expiresAt:typeof t.expires_in=="number"?Date.now()+t.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(t){await this.store.set(this.key("verifier"),t);}async codeVerifier(){let t=await this.store.get(this.key("verifier"));if(!t)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return t}async redirectToAuthorization(t){this.authorizationUrl=t,await this.onAuthorizationUrl?.(t);}async invalidateCredentials(t){let o=t==="all"?["tokens","client","verifier","state"]:[t];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let t=await this.readJSON("tokens");return t?.tokens?.access_token?t.expiresAt===void 0?false:Date.now()+this.skewMs>=t.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},un=s(e=>new Pe(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth_js.auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),mn=s(async(e,t,o={})=>{if(!await e.verifyState(t.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth_js.auth(e,{serverUrl:e.serverUrl,authorizationCode:t.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var hn="@dudko.dev/agent",yn=Re.version,at,Tn=s(()=>(at||(at=api.trace.getTracer(hn,yn)),at),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},J=s(async(e,t,o)=>Tn().startActiveSpan(e,async n=>{for(let[r,i]of Object.entries(t))i!==void 0&&n.setAttribute(r,i);try{let r=await o(n);return n.end(),r}catch(r){let i=r instanceof Error?r:new Error(String(r));throw n.recordException(i),n.setStatus({code:api.SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Ln=s(e=>"command"in e&&!!e.command,"isStdioConfig"),$n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Un=Re.version,lt=64,ve=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),_n=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,lt-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Me=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Jt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Jt;i++){let l=await e.listTools(n?{cursor:n}:void 0);o.push(...l.tools);let c=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!c||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),de=class extends Error{static{s(this,"RefreshOnlyAbort");}},zn=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new de},"state"),saveCodeVerifier:s(()=>{throw new de},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new de},"redirectToAuthorization")}),"refreshOnly"),jn=s(async(e,t,o,n,r)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth_js.auth(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof de?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Gt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,O)=>{let H=`${ve(g)}__`;for(let I of f.get(g)??[])delete a[I];for(let I=p.length-1;I>=0;I--)p[I].server===g&&p.splice(I,1);let $=[],_=0,R=0;for(let I of O){let v=H+ve(I.name);if(v.length>lt){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${lt}-char limit enforced by major LLM providers; skipping`),R++;continue}let C=_n(v,a);if(!C){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}C!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${C}"`);let U=I.description??"",W=I.annotations?.readOnlyHint===true;a[C]=ai.dynamicTool({description:U,inputSchema:ai.jsonSchema(I.inputSchema),execute:s(async(q,k)=>J("agent.tool_call",{[E.TOOL_NAME]:C},async P=>{let D=q??{};if(i)try{let S=await i(C,D);D=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${C}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),D={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:D},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let m=w.isError===true,y=w.content;if(n)try{y=await n(C,y);}catch(S){if(t("warn",`[mcp] ${C}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Me("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:C,sandboxDir:m?void 0:qe()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Me(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&V(a[C]),p.push({name:C,description:U,server:g,readOnly:W}),$.push(C),_++;}f.set(g,$),R>0?t("info",`[mcp] ${g}: ${_} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${_} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Jt} pages; the rest is ignored`)),"listServerTools"),T=s(async(g,b)=>{u(g,b,await h(g,b));},"registerServerTools"),x=s(async(g,b)=>{let O=b.connectTimeoutMs??l.connectTimeoutMs,H=typeof O=="number"&&Number.isFinite(O)&&O>=0?O:Nn,$,_=false,R=K(g,b,I=>{$=I;},()=>_);try{return await(H>0?Fn(R,H,()=>{_=!0;}):R)}catch(I){$&&await $.close().catch(()=>{});let v=_?`connect timed out after ${H}ms`:I.message,C=!_&&I instanceof auth_js.UnauthorizedError;return t("error",C?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:C}}},"openConnection"),K=s(async(g,b,O,H)=>{let $,_=s(async()=>{if(H())throw await $?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(b)){let v=b.env?{...stdio_js.getDefaultEnvironment(),...b.env}:void 0;R=new stdio_js.StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if($n(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),it(b.url,`MCP server "${g}"`),await jn(b.authProvider,b.url,b.fetch,t,g)),R=new streamableHttp_js.StreamableHTTPClientTransport(new url.URL(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await _(),$=new index_js.Client({name:o,version:Un}),O($),await $.connect(R),await _(),r&&$.setNotificationHandler(types_js.ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,$);return await _(),{name:g,client:$,listed:I}}catch(R){throw $&&await $.close().catch(()=>{}),R}},"connectOnce"),L=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of L){if(!g.client||!g.listed){d.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),u(g.name,g.client,g.listed),d.push({name:g.name,connected:true});}return {tools:a,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:s(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await T(g,b);},"refreshServer")}},"connectMcpServers"),Fn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),n(l);},l=>{clearTimeout(i),r(l);});}),"withConnectTimeout"),qt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return qt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?qt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Hn=/[^a-zA-Z0-9_-]/g,Bt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=crypto.randomUUID().slice(0,8),p=ie__default.default.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await promises.writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Wn=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
13
13
  `);let r=t?.sandboxDir,i=t?.toolName??"tool",l,c=s(()=>r?(l||(l=promises.mkdir(r,{recursive:true}).then(()=>{})),l):Promise.resolve(),"ensureDir"),a=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){a.push(p.text);continue}if(r&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let d=await Bt(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,i,r,c);a.push(d);continue}if(r&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let d=p.resource;if(typeof d.blob=="string"){let f=await Bt(d.blob,typeof d.mimeType=="string"?d.mimeType:void 0,"resource",i,r,c);typeof d.uri=="string"&&(f.uri=d.uri),a.push(f);continue}if(typeof d.text=="string"){a.push(d.text);continue}}a.push(p);}return a},"flattenContent"),ct=s((e,t,o,n,r)=>{let i=o?.length?new Set(o.map(ve)):null,l=n?.length?new Set(n.map(ve)):null,c=new Set,a={},p=[];for(let d of t){if((i?.has(d.name)||l?.has(d.name))&&c.add(d.name),i&&!i.has(d.name)||!i&&l?.has(d.name))continue;let f=e[d.name];f&&(a[d.name]=f,p.push(d));}if(r)for(let[d,f]of [["availableTools",o],["excludedTools",n]])for(let u of f??[])c.has(ve(u))||r("warn",`[mcp] ${d}: "${u}" matches no discovered tool`);return {tools:a,catalog:p}},"filterTools");var Le=s((e,t,o,n)=>{let r=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,l=t?.baseURL??e.baseURL,c=t?.model??o??e.model,a=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(qn.has(r)&&!l)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:l,apiKey:i,model:c,providerOptions:a}},"resolveStage"),qn=new Set(["openai-compatible","azure"]),X={openai:"@ai-sdk/openai",anthropic:"@ai-sdk/anthropic",google:"@ai-sdk/google","openai-compatible":"@ai-sdk/openai-compatible",xai:"@ai-sdk/xai",azure:"@ai-sdk/azure","amazon-bedrock":"@ai-sdk/amazon-bedrock","google-vertex":"@ai-sdk/google-vertex",deepseek:"@ai-sdk/deepseek",cloudflare:"workers-ai-provider"},Z=s(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),$e=s(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await Z(X.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await Z(X.anthropic);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await Z(X["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await Z(X.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await Z(X.xai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await Z(X.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await Z(X["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await Z(X["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await Z(X.deepseek);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let r=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...l}=o;if(!r&&!("binding"in l))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await Z(X.cloudflare),a="binding"in l?l:{accountId:r,apiKey:t.apiKey,...l};return c(a)(t.model)}}},"buildModelFromStage");var Bn=s(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,r)=>n.type==="tool-result"?[`${o}:${r}`]:[]):[]),"positionsOf"),Jn=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Yt=s(e=>{try{return se(JSON.stringify(e))}catch{return 0}},"estimate"),pt=s((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,r=s(i=>n.size===0?i:i.map((l,c)=>l.role==="tool"&&Array.isArray(l.content)?{...l,content:l.content.map((a,p)=>a.type==="tool-result"&&n.has(`${c}:${p}`)?{...a,output:{type:"text",value:Jn(a.toolName)}}:a)}:l),"apply");return i=>{let l=r(i),c=Yt(l);if(c<=e.triggerTokens)return l;let a=Bn(i),p=0;for(let f of a.slice(0,Math.max(0,a.length-o)))n.has(f)||(n.add(f),p+=1);if(p===0)return l;let d=r(i);return t?.({cleared:p,beforeTokens:c,afterTokens:Yt(d)}),d}},"createToolResultClearer");var Xt=/^[a-z0-9-]{1,64}$/,Yn="load_skill",Vn="read_skill_file",Xn=24e3,eo=s(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=ie__default.default.posix.normalize(t);if(!o||o==="."||o.startsWith("/")||o===".."||o.startsWith("../"))throw new Error(`skill file path must be relative and stay inside the skill: "${e}"`);return o},"normalizeSkillPath"),ut=s(e=>{if(!e||typeof e!="object")throw new Error("skill must be an object { name, description, content, files? }");let{name:t,description:o,content:n,files:r}=e;if(typeof t!="string"||!Xt.test(t))throw new Error(`skill name must match ${Xt} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof n!="string")throw new Error(`skill "${t}": content must be a string`);if(r!==void 0&&!Array.isArray(r))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,l=(r??[]).map(c=>{if(!c||typeof c.path!="string"||typeof c.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let a;try{a=eo(c.path);}catch(p){throw new Error(`skill "${t}": ${p.message}`)}if(i.has(a))throw new Error(`skill "${t}": duplicate file "${a}"`);return i.add(a),{path:a,content:c.content}});return {name:t,description:o.trim(),content:n,...l.length?{files:l}:{}}},"defineSkill"),Zn=s(e=>{let t=e.trim();if(t.length>=2&&t.startsWith('"')&&t.endsWith('"'))try{return JSON.parse(t)}catch{return t.slice(1,-1)}return t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/''/g,"'"):t.replace(/\s+#.*$/,"")},"unquote"),Qn=s(e=>{let t={},o=e.split(`
14
14
  `);for(let n=0;n<o.length;n++){let r=o[n],i=/^([A-Za-z0-9_-]+)\s*:(.*)$/.exec(r);if(!i)continue;let l=i[1],c=i[2].trim(),a=/^([>|])([+-]?)\s*(#.*)?$/.exec(c);if(a){let p=[];for(;n+1<o.length&&(/^\s/.test(o[n+1])||o[n+1].trim()==="");)p.push(o[++n]);for(;p.length&&p[p.length-1].trim()==="";)p.pop();let d=Math.min(...p.filter(u=>u.trim()).map(u=>/^\s*/.exec(u)[0].length)),f=p.map(u=>u.slice(Number.isFinite(d)?d:0));t[l]=a[1]==="|"?f.join(`
15
15
  `):f.join(`
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ ${f}`},...e.slice(c)];return {history:u,summary:f,beforeTokens:n,afterTokens:ie(
9
9
  ${t}
10
10
  `:"",`Steps to summarize:
11
11
  ${n.render(e,n.offset)}`].filter(Boolean).join(`
12
- `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:Y(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:j(r.usage)}:void 0}catch{return}},"summarizeTrace"),Ht=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:pe(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:pe(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:pe(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Xo=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),st=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Ht(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Ee={version:"0.0.35"};var an=ae.join(sn.homedir(),".agent","mcp-oauth.json"),Pe=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await readFile(this.filePath,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}async writeAll(t){let o=`${this.filePath}.${process.pid}.tmp`;await writeFile(o,JSON.stringify(t,null,2),{mode:384}),await chmod(o,384).catch(()=>{}),await rename(o,this.filePath);}enqueue(t){let o=this.queue.then(t,t);return this.queue=o.catch(()=>{}),o}async get(t){return this.enqueue(async()=>(await this.readAll())[t])}async set(t,o){await this.enqueue(async()=>{let n=await this.readAll();n[t]=o,await mkdir(ae.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(t){await this.enqueue(async()=>{let o=await this.readAll();t in o&&(delete o[t],await this.writeAll(o));});}},it=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(t){return this.map.get(t)}async set(t,o){this.map.set(t,o);}async delete(t){this.map.delete(t);}},ln=30,cn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),pn=new Set(["localhost","127.0.0.1","[::1]","::1"]),at=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||pn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Me=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Pe,this.ns=cn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??ln)*1e3,this.onAuthorizationUrl=t.onAuthorizationUrl,this._clientMetadata={client_name:t.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...t.scope?{scope:t.scope}:{},...t.clientMetadata},at(t.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(t){return `${this.ns}:${t}`}async readJSON(t){let o=await this.store.get(this.key(t));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(t));return}}async state(){let t=randomBytes(32).toString("hex");return await this.store.set(this.key("state"),t),t}async verifyState(t){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&t!==void 0&&o===t}async clientInformation(){return this.readJSON("client")}async saveClientInformation(t){await this.store.set(this.key("client"),JSON.stringify(t));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(t){let o={tokens:t,expiresAt:typeof t.expires_in=="number"?Date.now()+t.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(t){await this.store.set(this.key("verifier"),t);}async codeVerifier(){let t=await this.store.get(this.key("verifier"));if(!t)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return t}async redirectToAuthorization(t){this.authorizationUrl=t,await this.onAuthorizationUrl?.(t);}async invalidateCredentials(t){let o=t==="all"?["tokens","client","verifier","state"]:[t];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let t=await this.readJSON("tokens");return t?.tokens?.access_token?t.expiresAt===void 0?false:Date.now()+this.skewMs>=t.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},un=s(e=>new Me(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),mn=s(async(e,t,o={})=>{if(!await e.verifyState(t.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth(e,{serverUrl:e.serverUrl,authorizationCode:t.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var hn="@dudko.dev/agent",yn=Ee.version,lt,Tn=s(()=>(lt||(lt=trace.getTracer(hn,yn)),lt),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},G=s(async(e,t,o)=>Tn().startActiveSpan(e,async n=>{for(let[r,i]of Object.entries(t))i!==void 0&&n.setAttribute(r,i);try{let r=await o(n);return n.end(),r}catch(r){let i=r instanceof Error?r:new Error(String(r));throw n.recordException(i),n.setStatus({code:SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Ln=s(e=>"command"in e&&!!e.command,"isStdioConfig"),$n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Un=Ee.version,ct=64,Se=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),_n=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,ct-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Le=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Gt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Gt;i++){let l=await e.listTools(n?{cursor:n}:void 0);o.push(...l.tools);let c=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!c||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),me=class extends Error{static{s(this,"RefreshOnlyAbort");}},zn=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new me},"state"),saveCodeVerifier:s(()=>{throw new me},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new me},"redirectToAuthorization")}),"refreshOnly"),jn=s(async(e,t,o,n,r)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof me?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Yt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,C)=>{let W=`${Se(g)}__`;for(let I of f.get(g)??[])delete a[I];for(let I=p.length-1;I>=0;I--)p[I].server===g&&p.splice(I,1);let L=[],N=0,R=0;for(let I of C){let v=W+Se(I.name);if(v.length>ct){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${ct}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=_n(v,a);if(!O){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}O!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${O}"`);let $=I.description??"",q=I.annotations?.readOnlyHint===true;a[O]=dynamicTool({description:$,inputSchema:jsonSchema(I.inputSchema),execute:s(async(B,k)=>G("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let z=B??{};if(i)try{let S=await i(O,z);z=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),z={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:z},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let m=w.isError===true,y=w.content;if(n)try{y=await n(O,y);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Le("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:O,sandboxDir:m?void 0:Be()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Le(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),q&&X(a[O]),p.push({name:O,description:$,server:g,readOnly:q}),L.push(O),N++;}f.set(g,L),R>0?t("info",`[mcp] ${g}: ${N} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${N} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Gt} pages; the rest is ignored`)),"listServerTools"),T=s(async(g,b)=>{u(g,b,await h(g,b));},"registerServerTools"),x=s(async(g,b)=>{let C=b.connectTimeoutMs??l.connectTimeoutMs,W=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:Nn,L,N=false,R=H(g,b,I=>{L=I;},()=>N);try{return await(W>0?Fn(R,W,()=>{N=!0;}):R)}catch(I){L&&await L.close().catch(()=>{});let v=N?`connect timed out after ${W}ms`:I.message,O=!N&&I instanceof UnauthorizedError;return t("error",O?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:O}}},"openConnection"),H=s(async(g,b,C,W)=>{let L,N=s(async()=>{if(W())throw await L?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;R=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if($n(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),at(b.url,`MCP server "${g}"`),await jn(b.authProvider,b.url,b.fetch,t,g)),R=new StreamableHTTPClientTransport(new URL$1(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await N(),L=new Client({name:o,version:Un}),C(L),await L.connect(R),await N(),r&&L.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,L);return await N(),{name:g,client:L,listed:I}}catch(R){throw L&&await L.close().catch(()=>{}),R}},"connectOnce"),M=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of M){if(!g.client||!g.listed){d.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),u(g.name,g.client,g.listed),d.push({name:g.name,connected:true});}return {tools:a,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:s(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await T(g,b);},"refreshServer")}},"connectMcpServers"),Fn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),n(l);},l=>{clearTimeout(i),r(l);});}),"withConnectTimeout"),Bt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return Bt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?Bt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Hn=/[^a-zA-Z0-9_-]/g,Jt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=randomUUID().slice(0,8),p=ae.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Wn=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
12
+ `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:Y(n.signal,n.timeoutMs??0),maxRetries:0}),i=r.text.trim();return i?{summary:i,usage:j(r.usage)}:void 0}catch{return}},"summarizeTrace"),Ht=s((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:pe(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:pe(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:pe(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Xo=s(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),st=s((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:s(async r=>Ht(o?await o(r):Xo(r.output),t),"toModelOutput")}},"withToolOutputLimit");var Ee={version:"0.0.36"};var an=ae.join(sn.homedir(),".agent","mcp-oauth.json"),Pe=class{static{s(this,"FileOAuthStore");}filePath;queue=Promise.resolve();constructor(t=an){this.filePath=t;}async readAll(){try{let t=JSON.parse(await readFile(this.filePath,"utf8"));return !t||typeof t!="object"||Array.isArray(t)?{}:t}catch{return {}}}async writeAll(t){let o=`${this.filePath}.${process.pid}.tmp`;await writeFile(o,JSON.stringify(t,null,2),{mode:384}),await chmod(o,384).catch(()=>{}),await rename(o,this.filePath);}enqueue(t){let o=this.queue.then(t,t);return this.queue=o.catch(()=>{}),o}async get(t){return this.enqueue(async()=>(await this.readAll())[t])}async set(t,o){await this.enqueue(async()=>{let n=await this.readAll();n[t]=o,await mkdir(ae.dirname(this.filePath),{recursive:true,mode:448}),await this.writeAll(n);});}async delete(t){await this.enqueue(async()=>{let o=await this.readAll();t in o&&(delete o[t],await this.writeAll(o));});}},it=class{static{s(this,"MemoryOAuthStore");}map=new Map;async get(t){return this.map.get(t)}async set(t,o){this.map.set(t,o);}async delete(t){this.map.delete(t);}},ln=30,cn=s(e=>{let t=new URL(e);return `mcp-oauth:${t.origin}${t.pathname.replace(/\/+$/,"")}${t.search}`},"namespaceFor"),pn=new Set(["localhost","127.0.0.1","[::1]","::1"]),at=s((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||pn.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl"),Me=class{static{s(this,"NodeOAuthProvider");}authorizationUrl;serverUrl;store;ns;_redirectUrl;_clientMetadata;skewMs;onAuthorizationUrl;constructor(t){this.serverUrl=t.serverUrl,this.store=t.store??new Pe,this.ns=cn(t.serverUrl),this._redirectUrl=t.redirectUrl,this.skewMs=(t.expirySkewSeconds??ln)*1e3,this.onAuthorizationUrl=t.onAuthorizationUrl,this._clientMetadata={client_name:t.clientName??"agent",redirect_uris:[this._redirectUrl],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none",...t.scope?{scope:t.scope}:{},...t.clientMetadata},at(t.serverUrl);}get redirectUrl(){return this._redirectUrl}get clientMetadata(){return this._clientMetadata}key(t){return `${this.ns}:${t}`}async readJSON(t){let o=await this.store.get(this.key(t));if(o!==void 0)try{return JSON.parse(o)}catch{await this.store.delete(this.key(t));return}}async state(){let t=randomBytes(32).toString("hex");return await this.store.set(this.key("state"),t),t}async verifyState(t){let o=await this.store.get(this.key("state"));return await this.store.delete(this.key("state")),o!==void 0&&t!==void 0&&o===t}async clientInformation(){return this.readJSON("client")}async saveClientInformation(t){await this.store.set(this.key("client"),JSON.stringify(t));}async tokens(){return (await this.readJSON("tokens"))?.tokens}async saveTokens(t){let o={tokens:t,expiresAt:typeof t.expires_in=="number"?Date.now()+t.expires_in*1e3:void 0};await this.store.set(this.key("tokens"),JSON.stringify(o));}async saveCodeVerifier(t){await this.store.set(this.key("verifier"),t);}async codeVerifier(){let t=await this.store.get(this.key("verifier"));if(!t)throw new Error("No PKCE code verifier stored: the authorization was started by another process, or the store was cleared mid-flow");return t}async redirectToAuthorization(t){this.authorizationUrl=t,await this.onAuthorizationUrl?.(t);}async invalidateCredentials(t){let o=t==="all"?["tokens","client","verifier","state"]:[t];await Promise.all(o.map(n=>this.store.delete(this.key(n))));}async isAccessTokenExpired(){let t=await this.readJSON("tokens");return t?.tokens?.access_token?t.expiresAt===void 0?false:Date.now()+this.skewMs>=t.expiresAt:true}async isAuthorized(){return await this.tokens()!==void 0}async reset(){this.authorizationUrl=void 0,await this.invalidateCredentials("all");}},un=s(e=>new Me(e),"createNodeOAuthProvider"),dn=s(async(e,t={})=>(e.authorizationUrl=void 0,auth(e,{serverUrl:e.serverUrl,fetchFn:t.fetch})),"beginMcpOAuth"),mn=s(async(e,t,o={})=>{if(!await e.verifyState(t.state))throw new Error("Authorization state mismatch; refusing to exchange the code (possible CSRF)");let n=await auth(e,{serverUrl:e.serverUrl,authorizationCode:t.code,fetchFn:o.fetch});if(n!=="AUTHORIZED")throw new Error(`Token exchange did not complete (SDK returned "${n}")`)},"finishMcpOAuth");var hn="@dudko.dev/agent",yn=Ee.version,lt,Tn=s(()=>(lt||(lt=trace.getTracer(hn,yn)),lt),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},G=s(async(e,t,o)=>Tn().startActiveSpan(e,async n=>{for(let[r,i]of Object.entries(t))i!==void 0&&n.setAttribute(r,i);try{let r=await o(n);return n.end(),r}catch(r){let i=r instanceof Error?r:new Error(String(r));throw n.recordException(i),n.setStatus({code:SpanStatusCode.ERROR,message:i.message}),n.end(),r}}),"withSpan");var Ln=s(e=>"command"in e&&!!e.command,"isStdioConfig"),$n=s(e=>"url"in e&&!!e.url,"isHttpConfig"),Un=Ee.version,ct=64,Se=s(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),_n=s((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,r=e.slice(0,ct-n.length)+n;if(!t[r])return r}return ""},"uniqueKey"),Le=class extends Error{static{s(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},Nn=3e4,Gt=100,Dn=s(async(e,t)=>{let o=[],n,r=new Set;for(let i=0;i<Gt;i++){let l=await e.listTools(n?{cursor:n}:void 0);o.push(...l.tools);let c=typeof l.nextCursor=="string"&&l.nextCursor?l.nextCursor:void 0;if(!c||r.has(c))return o;r.add(c),n=c;}return t?.(),o},"listAllTools"),me=class extends Error{static{s(this,"RefreshOnlyAbort");}},zn=s(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:s(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:s(()=>e.tokens(),"tokens"),saveTokens:s(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:s(()=>e.codeVerifier(),"codeVerifier"),state:s(()=>{throw new me},"state"),saveCodeVerifier:s(()=>{throw new me},"saveCodeVerifier"),redirectToAuthorization:s(()=>{throw new me},"redirectToAuthorization")}),"refreshOnly"),jn=s(async(e,t,o,n,r)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(zn(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof me?`[mcp] ${r}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${r}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),Yt=s(async(e,t,o,n,r,i,l={})=>{let c=new Map,a={},p=[],d=[],f=new Map,u=s((g,b,C)=>{let W=`${Se(g)}__`;for(let I of f.get(g)??[])delete a[I];for(let I=p.length-1;I>=0;I--)p[I].server===g&&p.splice(I,1);let L=[],N=0,R=0;for(let I of C){let v=W+Se(I.name);if(v.length>ct){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${ct}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=_n(v,a);if(!O){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}O!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${O}"`);let $=I.description??"",q=I.annotations?.readOnlyHint===true;a[O]=dynamicTool({description:$,inputSchema:jsonSchema(I.inputSchema),execute:s(async(B,k)=>G("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let z=B??{};if(i)try{let S=await i(O,z);z=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),z={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:z},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let m=w.isError===true,y=w.content;if(n)try{y=await n(O,y);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),m)throw new Le("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await Wn(y,{toolName:O,sandboxDir:m?void 0:Be()});if(m){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Le(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),q&&X(a[O]),p.push({name:O,description:$,server:g,readOnly:q}),L.push(O),N++;}f.set(g,L),R>0?t("info",`[mcp] ${g}: ${N} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${N} tools mounted`);},"mountServerTools"),h=s((g,b)=>Dn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Gt} pages; the rest is ignored`)),"listServerTools"),T=s(async(g,b)=>{u(g,b,await h(g,b));},"registerServerTools"),x=s(async(g,b)=>{let C=b.connectTimeoutMs??l.connectTimeoutMs,W=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:Nn,L,N=false,R=H(g,b,I=>{L=I;},()=>N);try{return await(W>0?Fn(R,W,()=>{N=!0;}):R)}catch(I){L&&await L.close().catch(()=>{});let v=N?`connect timed out after ${W}ms`:I.message,O=!N&&I instanceof UnauthorizedError;return t("error",O?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:O}}},"openConnection"),H=s(async(g,b,C,W)=>{let L,N=s(async()=>{if(W())throw await L?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(Ln(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;R=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if($n(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),at(b.url,`MCP server "${g}"`),await jn(b.authProvider,b.url,b.fetch,t,g)),R=new StreamableHTTPClientTransport(new URL$1(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await N(),L=new Client({name:o,version:Un}),C(L),await L.connect(R),await N(),r&&L.setNotificationHandler(ToolListChangedNotificationSchema,()=>{r(g);});let I=await h(g,L);return await N(),{name:g,client:L,listed:I}}catch(R){throw L&&await L.close().catch(()=>{}),R}},"connectOnce"),M=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of M){if(!g.client||!g.listed){d.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),u(g.name,g.client,g.listed),d.push({name:g.name,connected:true});}return {tools:a,catalog:p,results:d,close:s(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:s(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await T(g,b);},"refreshServer")}},"connectMcpServers"),Fn=s((e,t,o)=>new Promise((n,r)=>{let i=setTimeout(()=>{o(),r(new Error(`connect timed out after ${t}ms`));},t);e.then(l=>{clearTimeout(i),n(l);},l=>{clearTimeout(i),r(l);});}),"withConnectTimeout"),Bt={image:".bin",audio:".bin",resource:".bin"},Kn=s((e,t)=>{if(!e)return Bt[t];let o=e.indexOf("/"),r=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !r||/[^a-z0-9.+-]/.test(r)?Bt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[r]??`.${r.replace(/\+/g,"-")}`},"extFromMime"),Hn=/[^a-zA-Z0-9_-]/g,Jt=s(async(e,t,o,n,r,i)=>{await i();let l=Kn(t,o),c=n.replace(Hn,"_").slice(0,32)||"tool",a=randomUUID().slice(0,8),p=ae.join(r,`${o}-${c}-${a}${l}`),d=Buffer.from(e,"base64");return await writeFile(p,d),{type:"file",kind:o,path:p,mimeType:t,bytes:d.byteLength}},"spillBase64"),Wn=s(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(p=>p?.type==="text"&&typeof p.text=="string"))return o.map(p=>p.text).join(`
13
13
  `);let r=t?.sandboxDir,i=t?.toolName??"tool",l,c=s(()=>r?(l||(l=mkdir(r,{recursive:true}).then(()=>{})),l):Promise.resolve(),"ensureDir"),a=[];for(let p of o){if(p?.type==="text"&&typeof p.text=="string"){a.push(p.text);continue}if(r&&(p?.type==="image"||p?.type==="audio")&&typeof p.data=="string"){let d=await Jt(p.data,typeof p.mimeType=="string"?p.mimeType:void 0,p.type,i,r,c);a.push(d);continue}if(r&&p?.type==="resource"&&p.resource&&typeof p.resource=="object"){let d=p.resource;if(typeof d.blob=="string"){let f=await Jt(d.blob,typeof d.mimeType=="string"?d.mimeType:void 0,"resource",i,r,c);typeof d.uri=="string"&&(f.uri=d.uri),a.push(f);continue}if(typeof d.text=="string"){a.push(d.text);continue}}a.push(p);}return a},"flattenContent"),pt=s((e,t,o,n,r)=>{let i=o?.length?new Set(o.map(Se)):null,l=n?.length?new Set(n.map(Se)):null,c=new Set,a={},p=[];for(let d of t){if((i?.has(d.name)||l?.has(d.name))&&c.add(d.name),i&&!i.has(d.name)||!i&&l?.has(d.name))continue;let f=e[d.name];f&&(a[d.name]=f,p.push(d));}if(r)for(let[d,f]of [["availableTools",o],["excludedTools",n]])for(let u of f??[])c.has(Se(u))||r("warn",`[mcp] ${d}: "${u}" matches no discovered tool`);return {tools:a,catalog:p}},"filterTools");var $e=s((e,t,o,n)=>{let r=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,l=t?.baseURL??e.baseURL,c=t?.model??o??e.model,a=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(qn.has(r)&&!l)throw new Error(`${n}: provider "${r}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:r,baseURL:l,apiKey:i,model:c,providerOptions:a}},"resolveStage"),qn=new Set(["openai-compatible","azure"]),Z={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"},Q=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:n}=await Q(Z.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await Q(Z.anthropic);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await Q(Z["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await Q(Z.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await Q(Z.xai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await Q(Z.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await Q(Z["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await Q(Z["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await Q(Z.deepseek);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let r=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...l}=o;if(!r&&!("binding"in l))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await Q(Z.cloudflare),a="binding"in l?l:{accountId:r,apiKey:t.apiKey,...l};return c(a)(t.model)}}},"buildModelFromStage");var Bn=s(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,r)=>n.type==="tool-result"?[`${o}:${r}`]:[]):[]),"positionsOf"),Jn=s(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Vt=s(e=>{try{return ie(JSON.stringify(e))}catch{return 0}},"estimate"),ut=s((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,r=s(i=>n.size===0?i:i.map((l,c)=>l.role==="tool"&&Array.isArray(l.content)?{...l,content:l.content.map((a,p)=>a.type==="tool-result"&&n.has(`${c}:${p}`)?{...a,output:{type:"text",value:Jn(a.toolName)}}:a)}:l),"apply");return i=>{let l=r(i),c=Vt(l);if(c<=e.triggerTokens)return l;let a=Bn(i),p=0;for(let f of a.slice(0,Math.max(0,a.length-o)))n.has(f)||(n.add(f),p+=1);if(p===0)return l;let d=r(i);return t?.({cleared:p,beforeTokens:c,afterTokens:Vt(d)}),d}},"createToolResultClearer");var Zt=/^[a-z0-9-]{1,64}$/,Yn="load_skill",Vn="read_skill_file",Xn=24e3,to=s(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=ae.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"),dt=s(e=>{if(!e||typeof e!="object")throw new Error("skill must be an object { name, description, content, files? }");let{name:t,description:o,content:n,files:r}=e;if(typeof t!="string"||!Zt.test(t))throw new Error(`skill name must match ${Zt} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof n!="string")throw new Error(`skill "${t}": content must be a string`);if(r!==void 0&&!Array.isArray(r))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,l=(r??[]).map(c=>{if(!c||typeof c.path!="string"||typeof c.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let a;try{a=to(c.path);}catch(p){throw new Error(`skill "${t}": ${p.message}`)}if(i.has(a))throw new Error(`skill "${t}": duplicate file "${a}"`);return i.add(a),{path:a,content:c.content}});return {name:t,description:o.trim(),content:n,...l.length?{files:l}:{}}},"defineSkill"),Zn=s(e=>{let t=e.trim();if(t.length>=2&&t.startsWith('"')&&t.endsWith('"'))try{return JSON.parse(t)}catch{return t.slice(1,-1)}return t.length>=2&&t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1).replace(/''/g,"'"):t.replace(/\s+#.*$/,"")},"unquote"),Qn=s(e=>{let t={},o=e.split(`
14
14
  `);for(let n=0;n<o.length;n++){let r=o[n],i=/^([A-Za-z0-9_-]+)\s*:(.*)$/.exec(r);if(!i)continue;let l=i[1],c=i[2].trim(),a=/^([>|])([+-]?)\s*(#.*)?$/.exec(c);if(a){let p=[];for(;n+1<o.length&&(/^\s/.test(o[n+1])||o[n+1].trim()==="");)p.push(o[++n]);for(;p.length&&p[p.length-1].trim()==="";)p.pop();let d=Math.min(...p.filter(u=>u.trim()).map(u=>/^\s*/.exec(u)[0].length)),f=p.map(u=>u.slice(Number.isFinite(d)?d:0));t[l]=a[1]==="|"?f.join(`
15
15
  `):f.join(`
@@ -9,7 +9,7 @@ ${f}`},...e.slice(c)];return {history:m,summary:f,beforeTokens:n,afterTokens:re(
9
9
  ${t}
10
10
  `:"",`Steps to summarize:
11
11
  ${n.render(e,n.offset)}`].filter(Boolean).join(`
12
- `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:J(n.signal,n.timeoutMs??0),maxRetries:0}),i=s.text.trim();return i?{summary:i,usage:K(s.usage)}:void 0}catch{return}},"summarizeTrace"),Mo=r((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:me(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:me(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:me(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Lo=r(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),Pt=r((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:r(async s=>Mo(o?await o(s):Lo(s.output),t),"toModelOutput")}},"withToolOutputLimit");var Oe={version:"0.0.35"};po.join(Uo.homedir(),".agent","mcp-oauth.json");var No=new Set(["localhost","127.0.0.1","[::1]","::1"]),Mt=r((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||No.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var jo="@dudko.dev/agent",Fo=Oe.version,Ge,Ko=r(()=>(Ge||(Ge=trace.getTracer(jo,Fo)),Ge),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},B=r(async(e,t,o)=>Ko().startActiveSpan(e,async n=>{for(let[s,i]of Object.entries(t))i!==void 0&&n.setAttribute(s,i);try{let s=await o(n);return n.end(),s}catch(s){let i=s instanceof Error?s:new Error(String(s));throw n.recordException(i),n.setStatus({code:SpanStatusCode.ERROR,message:i.message}),n.end(),s}}),"withSpan");var nn=r(e=>"command"in e&&!!e.command,"isStdioConfig"),rn=r(e=>"url"in e&&!!e.url,"isHttpConfig"),sn=Oe.version,Ye=64,he=r(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),an=r((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,s=e.slice(0,Ye-n.length)+n;if(!t[s])return s}return ""},"uniqueKey"),Ce=class extends Error{static{r(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},ln=3e4,Ut=100,cn=r(async(e,t)=>{let o=[],n,s=new Set;for(let i=0;i<Ut;i++){let a=await e.listTools(n?{cursor:n}:void 0);o.push(...a.tools);let c=typeof a.nextCursor=="string"&&a.nextCursor?a.nextCursor:void 0;if(!c||s.has(c))return o;s.add(c),n=c;}return t?.(),o},"listAllTools"),le=class extends Error{static{r(this,"RefreshOnlyAbort");}},un=r(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:r(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:r(()=>e.tokens(),"tokens"),saveTokens:r(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:r(()=>e.codeVerifier(),"codeVerifier"),state:r(()=>{throw new le},"state"),saveCodeVerifier:r(()=>{throw new le},"saveCodeVerifier"),redirectToAuthorization:r(()=>{throw new le},"redirectToAuthorization")}),"refreshOnly"),pn=r(async(e,t,o,n,s)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(un(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof le?`[mcp] ${s}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${s}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),_t=r(async(e,t,o,n,s,i,a={})=>{let c=new Map,l={},u=[],p=[],f=new Map,m=r((g,b,C)=>{let j=`${he(g)}__`;for(let I of f.get(g)??[])delete l[I];for(let I=u.length-1;I>=0;I--)u[I].server===g&&u.splice(I,1);let M=[],$=0,R=0;for(let I of C){let v=j+he(I.name);if(v.length>Ye){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${Ye}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=an(v,l);if(!O){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}O!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${O}"`);let L=I.description??"",W=I.annotations?.readOnlyHint===true;l[O]=dynamicTool({description:L,inputSchema:jsonSchema(I.inputSchema),execute:r(async(H,k)=>B("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let N=H??{};if(i)try{let S=await i(O,N);N=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),N={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:N},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let d=w.isError===true,T=w.content;if(n)try{T=await n(O,T);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),d)throw new Ce("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await fn(T,{toolName:O,sandboxDir:d?void 0:pt()});if(d){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Ce(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&Y(l[O]),u.push({name:O,description:L,server:g,readOnly:W}),M.push(O),$++;}f.set(g,M),R>0?t("info",`[mcp] ${g}: ${$} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${$} tools mounted`);},"mountServerTools"),h=r((g,b)=>cn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Ut} pages; the rest is ignored`)),"listServerTools"),y=r(async(g,b)=>{m(g,b,await h(g,b));},"registerServerTools"),x=r(async(g,b)=>{let C=b.connectTimeoutMs??a.connectTimeoutMs,j=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:ln,M,$=false,R=D(g,b,I=>{M=I;},()=>$);try{return await(j>0?dn(R,j,()=>{$=!0;}):R)}catch(I){M&&await M.close().catch(()=>{});let v=$?`connect timed out after ${j}ms`:I.message,O=!$&&I instanceof UnauthorizedError;return t("error",O?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:O}}},"openConnection"),D=r(async(g,b,C,j)=>{let M,$=r(async()=>{if(j())throw await M?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(nn(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;R=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if(rn(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),Mt(b.url,`MCP server "${g}"`),await pn(b.authProvider,b.url,b.fetch,t,g)),R=new StreamableHTTPClientTransport(new URL$1(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await $(),M=new Client({name:o,version:sn}),C(M),await M.connect(R),await $(),s&&M.setNotificationHandler(ToolListChangedNotificationSchema,()=>{s(g);});let I=await h(g,M);return await $(),{name:g,client:M,listed:I}}catch(R){throw M&&await M.close().catch(()=>{}),R}},"connectOnce"),_=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of _){if(!g.client||!g.listed){p.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),m(g.name,g.client,g.listed),p.push({name:g.name,connected:true});}return {tools:l,catalog:u,results:p,close:r(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:r(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await y(g,b);},"refreshServer")}},"connectMcpServers"),dn=r((e,t,o)=>new Promise((n,s)=>{let i=setTimeout(()=>{o(),s(new Error(`connect timed out after ${t}ms`));},t);e.then(a=>{clearTimeout(i),n(a);},a=>{clearTimeout(i),s(a);});}),"withConnectTimeout"),Lt={image:".bin",audio:".bin",resource:".bin"},mn=r((e,t)=>{if(!e)return Lt[t];let o=e.indexOf("/"),s=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !s||/[^a-z0-9.+-]/.test(s)?Lt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[s]??`.${s.replace(/\+/g,"-")}`},"extFromMime"),gn=/[^a-zA-Z0-9_-]/g,$t=r(async(e,t,o,n,s,i)=>{await i();let a=mn(t,o),c=n.replace(gn,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),u=po.join(s,`${o}-${c}-${l}${a}`),p=Buffer.from(e,"base64");return await writeFile(u,p),{type:"file",kind:o,path:u,mimeType:t,bytes:p.byteLength}},"spillBase64"),fn=r(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(u=>u?.type==="text"&&typeof u.text=="string"))return o.map(u=>u.text).join(`
12
+ `),maxOutputTokens:n.summaryMaxTokens??1024,abortSignal:J(n.signal,n.timeoutMs??0),maxRetries:0}),i=s.text.trim();return i?{summary:i,usage:K(s.usage)}:void 0}catch{return}},"summarizeTrace"),Mo=r((e,t)=>{if(!(t>0))return e;switch(e.type){case "text":return e.value.length>t?{...e,value:me(e.value,t)}:e;case "json":{let o;try{o=JSON.stringify(e.value);}catch{return e}return o!==void 0&&o.length>t?{type:"text",value:me(o,t),...e.providerOptions?{providerOptions:e.providerOptions}:{}}:e}case "content":return {...e,value:e.value.map(o=>o.type==="text"&&o.text.length>t?{...o,text:me(o.text,t)}:o)};default:return e}},"truncateToolModelOutput"),Lo=r(e=>{if(typeof e=="string")return {type:"text",value:e};if(e===void 0)return {type:"json",value:null};try{let t=JSON.stringify(e);return {type:"json",value:t===void 0?null:JSON.parse(t)}}catch{return {type:"text",value:String(e)}}},"defaultModelOutput"),Pt=r((e,t)=>{if(!(t>0))return e;let o=e.toModelOutput;return {...e,toModelOutput:r(async s=>Mo(o?await o(s):Lo(s.output),t),"toModelOutput")}},"withToolOutputLimit");var Oe={version:"0.0.36"};po.join(Uo.homedir(),".agent","mcp-oauth.json");var No=new Set(["localhost","127.0.0.1","[::1]","::1"]),Mt=r((e,t="MCP OAuth")=>{let o;try{o=new URL(e);}catch{throw new Error(`${t}: "${e}" is not a valid URL`)}if(!(o.protocol==="https:"||No.has(o.hostname)))throw new Error(`${t}: requires https (or a loopback host) - refusing to send tokens to "${e}"`)},"assertSecureOAuthUrl");var jo="@dudko.dev/agent",Fo=Oe.version,Ge,Ko=r(()=>(Ge||(Ge=trace.getTracer(jo,Fo)),Ge),"tracer"),E={RUN_ID:"agent.run_id",PHASE:"agent.phase",PROVIDER:"agent.provider",MODEL:"agent.model",STEP_ID:"agent.step.id",STEP_BLOCKED:"agent.step.blocked",REPLAN_MODE:"agent.replan.mode",TOOL_NAME:"agent.tool.name",TOOL_OK:"agent.tool.ok",USAGE_INPUT_TOKENS:"agent.usage.input_tokens",USAGE_OUTPUT_TOKENS:"agent.usage.output_tokens",USAGE_TOTAL_TOKENS:"agent.usage.total_tokens",ITERATIONS:"agent.iterations",TOOL_COUNT:"agent.tool_count"},B=r(async(e,t,o)=>Ko().startActiveSpan(e,async n=>{for(let[s,i]of Object.entries(t))i!==void 0&&n.setAttribute(s,i);try{let s=await o(n);return n.end(),s}catch(s){let i=s instanceof Error?s:new Error(String(s));throw n.recordException(i),n.setStatus({code:SpanStatusCode.ERROR,message:i.message}),n.end(),s}}),"withSpan");var nn=r(e=>"command"in e&&!!e.command,"isStdioConfig"),rn=r(e=>"url"in e&&!!e.url,"isHttpConfig"),sn=Oe.version,Ye=64,he=r(e=>e.replace(/[^a-zA-Z0-9_-]/g,"_"),"sanitizeName"),an=r((e,t)=>{if(!t[e])return e;for(let o=2;o<100;o++){let n=`_${o}`,s=e.slice(0,Ye-n.length)+n;if(!t[s])return s}return ""},"uniqueKey"),Ce=class extends Error{static{r(this,"McpToolError");}constructor(t){super(t),this.name="McpToolError";}toJSON(){return this.message}},ln=3e4,Ut=100,cn=r(async(e,t)=>{let o=[],n,s=new Set;for(let i=0;i<Ut;i++){let a=await e.listTools(n?{cursor:n}:void 0);o.push(...a.tools);let c=typeof a.nextCursor=="string"&&a.nextCursor?a.nextCursor:void 0;if(!c||s.has(c))return o;s.add(c),n=c;}return t?.(),o},"listAllTools"),le=class extends Error{static{r(this,"RefreshOnlyAbort");}},un=r(e=>({get redirectUrl(){return e.redirectUrl},get clientMetadata(){return e.clientMetadata},clientInformation:r(()=>e.clientInformation(),"clientInformation"),saveClientInformation:e.saveClientInformation?.bind(e),tokens:r(()=>e.tokens(),"tokens"),saveTokens:r(t=>e.saveTokens(t),"saveTokens"),invalidateCredentials:e.invalidateCredentials?.bind(e),addClientAuthentication:e.addClientAuthentication?.bind(e),validateResourceURL:e.validateResourceURL?.bind(e),codeVerifier:r(()=>e.codeVerifier(),"codeVerifier"),state:r(()=>{throw new le},"state"),saveCodeVerifier:r(()=>{throw new le},"saveCodeVerifier"),redirectToAuthorization:r(()=>{throw new le},"redirectToAuthorization")}),"refreshOnly"),pn=r(async(e,t,o,n,s)=>{let i=e.isAccessTokenExpired;if(!(typeof i!="function"||!await i.call(e)||!(await e.tokens())?.refresh_token))try{await auth(un(e),{serverUrl:t,fetchFn:o});}catch(c){n("info",c instanceof le?`[mcp] ${s}: the stored token could not be refreshed; a new authorization is needed`:`[mcp] ${s}: proactive token refresh failed (${c.message}); continuing`);}},"refreshIfExpired"),_t=r(async(e,t,o,n,s,i,a={})=>{let c=new Map,l={},u=[],p=[],f=new Map,m=r((g,b,C)=>{let j=`${he(g)}__`;for(let I of f.get(g)??[])delete l[I];for(let I=u.length-1;I>=0;I--)u[I].server===g&&u.splice(I,1);let M=[],$=0,R=0;for(let I of C){let v=j+he(I.name);if(v.length>Ye){t("warn",`[mcp] ${g}: tool "${I.name}" prefixed name (${v.length} chars) exceeds the ${Ye}-char limit enforced by major LLM providers; skipping`),R++;continue}let O=an(v,l);if(!O){t("warn",`[mcp] ${g}: no free name left for tool "${I.name}"; skipping`),R++;continue}O!==v&&t("warn",`[mcp] ${g}: tool name "${v}" already taken; mounted as "${O}"`);let L=I.description??"",W=I.annotations?.readOnlyHint===true;l[O]=dynamicTool({description:L,inputSchema:jsonSchema(I.inputSchema),execute:r(async(H,k)=>B("agent.tool_call",{[E.TOOL_NAME]:O},async P=>{let N=H??{};if(i)try{let S=await i(O,N);N=S&&typeof S=="object"&&!Array.isArray(S)?S:{value:S};}catch(S){t("warn",`[mcp] ${O}: inputSanitizer threw - ${S.message}; input replaced with placeholder`),N={_redacted:"inputSanitizer failed"};}let w;try{w=await b.callTool({name:I.name,arguments:N},void 0,k?.abortSignal?{signal:k.abortSignal}:void 0);}catch(S){throw P.setAttribute(E.TOOL_OK,false),S}let d=w.isError===true,T=w.content;if(n)try{T=await n(O,T);}catch(S){if(t("warn",`[mcp] ${O}: outputSanitizer threw - ${S.message}; output replaced with placeholder`),P.setAttribute(E.TOOL_OK,false),d)throw new Ce("[output redacted: sanitizer failed]");return "[output redacted: sanitizer failed]"}let A=await fn(T,{toolName:O,sandboxDir:d?void 0:pt()});if(d){P.setAttribute(E.TOOL_OK,false);let S=typeof A=="string"?A:JSON.stringify(A);throw new Ce(S&&S!=="[]"?S:`MCP tool "${I.name}" reported an error with no content`)}return P.setAttribute(E.TOOL_OK,true),A}),"execute")}),W&&Y(l[O]),u.push({name:O,description:L,server:g,readOnly:W}),M.push(O),$++;}f.set(g,M),R>0?t("info",`[mcp] ${g}: ${$} tools mounted, ${R} skipped (length cap)`):t("info",`[mcp] ${g}: ${$} tools mounted`);},"mountServerTools"),h=r((g,b)=>cn(b,()=>t("warn",`[mcp] ${g}: tools/list still paginating after ${Ut} pages; the rest is ignored`)),"listServerTools"),y=r(async(g,b)=>{m(g,b,await h(g,b));},"registerServerTools"),x=r(async(g,b)=>{let C=b.connectTimeoutMs??a.connectTimeoutMs,j=typeof C=="number"&&Number.isFinite(C)&&C>=0?C:ln,M,$=false,R=D(g,b,I=>{M=I;},()=>$);try{return await(j>0?dn(R,j,()=>{$=!0;}):R)}catch(I){M&&await M.close().catch(()=>{});let v=$?`connect timed out after ${j}ms`:I.message,O=!$&&I instanceof UnauthorizedError;return t("error",O?`[mcp] ${g}: authorization required - complete the OAuth flow and reconnect`:`[mcp] ${g}: failed to connect - ${v}`),{name:g,error:v,needsAuthorization:O}}},"openConnection"),D=r(async(g,b,C,j)=>{let M,$=r(async()=>{if(j())throw await M?.close().catch(()=>{}),new Error("connect timed out")},"bail");try{let R;if(nn(b)){let v=b.env?{...getDefaultEnvironment(),...b.env}:void 0;R=new StdioClientTransport({command:b.command,args:b.args,env:v,cwd:b.cwd});}else if(rn(b)){if(b.headers&&b.getHeaders)throw new Error(`MCP server "${g}": specify either headers or getHeaders, not both`);let v=b.getHeaders?await b.getHeaders():b.headers;b.authProvider&&(v&&"Authorization"in v&&t("warn",`[mcp] ${g}: an explicit Authorization header shadows the OAuth token from authProvider`),Mt(b.url,`MCP server "${g}"`),await pn(b.authProvider,b.url,b.fetch,t,g)),R=new StreamableHTTPClientTransport(new URL$1(b.url),{requestInit:v?{headers:v}:void 0,authProvider:b.authProvider,fetch:b.fetch,reconnectionOptions:{maxReconnectionDelay:3e4,initialReconnectionDelay:1e3,reconnectionDelayGrowFactor:1.5,maxRetries:5}});}else throw new Error(`MCP server "${g}": config must specify either { url } (HTTP) or { command } (stdio)`);R.onerror=v=>t("warn",`[mcp] ${g}: transport error - ${v.message}`),R.onclose=()=>t("warn",`[mcp] ${g}: transport closed`),await $(),M=new Client({name:o,version:sn}),C(M),await M.connect(R),await $(),s&&M.setNotificationHandler(ToolListChangedNotificationSchema,()=>{s(g);});let I=await h(g,M);return await $(),{name:g,client:M,listed:I}}catch(R){throw M&&await M.close().catch(()=>{}),R}},"connectOnce"),_=await Promise.all(Object.entries(e).map(([g,b])=>x(g,b)));for(let g of _){if(!g.client||!g.listed){p.push({name:g.name,connected:false,error:g.error,...g.needsAuthorization?{needsAuthorization:true}:{}});continue}c.set(g.name,g.client),m(g.name,g.client,g.listed),p.push({name:g.name,connected:true});}return {tools:l,catalog:u,results:p,close:r(async()=>{await Promise.allSettled([...c.values()].map(g=>g.close()));},"close"),refreshServer:r(async g=>{let b=c.get(g);if(!b)throw new Error(`MCP server "${g}" is not connected`);await y(g,b);},"refreshServer")}},"connectMcpServers"),dn=r((e,t,o)=>new Promise((n,s)=>{let i=setTimeout(()=>{o(),s(new Error(`connect timed out after ${t}ms`));},t);e.then(a=>{clearTimeout(i),n(a);},a=>{clearTimeout(i),s(a);});}),"withConnectTimeout"),Lt={image:".bin",audio:".bin",resource:".bin"},mn=r((e,t)=>{if(!e)return Lt[t];let o=e.indexOf("/"),s=(o>=0?e.slice(o+1):e).split(";")[0].trim().toLowerCase();return !s||/[^a-z0-9.+-]/.test(s)?Lt[t]:{jpeg:".jpg",jpg:".jpg",png:".png",gif:".gif",webp:".webp",svg:".svg","svg+xml":".svg",mp3:".mp3",mpeg:".mp3",wav:".wav","x-wav":".wav",ogg:".ogg",pdf:".pdf",json:".json",plain:".txt",html:".html",csv:".csv"}[s]??`.${s.replace(/\+/g,"-")}`},"extFromMime"),gn=/[^a-zA-Z0-9_-]/g,$t=r(async(e,t,o,n,s,i)=>{await i();let a=mn(t,o),c=n.replace(gn,"_").slice(0,32)||"tool",l=randomUUID().slice(0,8),u=po.join(s,`${o}-${c}-${l}${a}`),p=Buffer.from(e,"base64");return await writeFile(u,p),{type:"file",kind:o,path:u,mimeType:t,bytes:p.byteLength}},"spillBase64"),fn=r(async(e,t)=>{if(!Array.isArray(e))return e;let o=e;if(o.length>0&&o.every(u=>u?.type==="text"&&typeof u.text=="string"))return o.map(u=>u.text).join(`
13
13
  `);let s=t?.sandboxDir,i=t?.toolName??"tool",a,c=r(()=>s?(a||(a=mkdir(s,{recursive:true}).then(()=>{})),a):Promise.resolve(),"ensureDir"),l=[];for(let u of o){if(u?.type==="text"&&typeof u.text=="string"){l.push(u.text);continue}if(s&&(u?.type==="image"||u?.type==="audio")&&typeof u.data=="string"){let p=await $t(u.data,typeof u.mimeType=="string"?u.mimeType:void 0,u.type,i,s,c);l.push(p);continue}if(s&&u?.type==="resource"&&u.resource&&typeof u.resource=="object"){let p=u.resource;if(typeof p.blob=="string"){let f=await $t(p.blob,typeof p.mimeType=="string"?p.mimeType:void 0,"resource",i,s,c);typeof p.uri=="string"&&(f.uri=p.uri),l.push(f);continue}if(typeof p.text=="string"){l.push(p.text);continue}}l.push(u);}return l},"flattenContent"),Ve=r((e,t,o,n,s)=>{let i=o?.length?new Set(o.map(he)):null,a=n?.length?new Set(n.map(he)):null,c=new Set,l={},u=[];for(let p of t){if((i?.has(p.name)||a?.has(p.name))&&c.add(p.name),i&&!i.has(p.name)||!i&&a?.has(p.name))continue;let f=e[p.name];f&&(l[p.name]=f,u.push(p));}if(s)for(let[p,f]of [["availableTools",o],["excludedTools",n]])for(let m of f??[])c.has(he(m))||s("warn",`[mcp] ${p}: "${m}" matches no discovered tool`);return {tools:l,catalog:u}},"filterTools");var Re=r((e,t,o,n)=>{let s=t?.providerType??e.providerType,i=t?.apiKey??e.apiKey,a=t?.baseURL??e.baseURL,c=t?.model??o??e.model,l=t?.providerOptions??e.providerOptions??{};if(t?.providerType&&t.providerType!==e.providerType&&!t.apiKey)throw new Error(`${n}: providerType "${t.providerType}" differs from the default "${e.providerType}" - you must also set ${n}.apiKey (cross-provider key inheritance is unsafe)`);if(hn.has(s)&&!a)throw new Error(`${n}: provider "${s}" requires a baseURL (set ${n}.baseURL or the top-level baseURL)`);return {providerType:s,baseURL:a,apiKey:i,model:c,providerOptions:l}},"resolveStage"),hn=new Set(["openai-compatible","azure"]),V={openai:"@ai-sdk/openai",anthropic:"@ai-sdk/anthropic",google:"@ai-sdk/google","openai-compatible":"@ai-sdk/openai-compatible",xai:"@ai-sdk/xai",azure:"@ai-sdk/azure","amazon-bedrock":"@ai-sdk/amazon-bedrock","google-vertex":"@ai-sdk/google-vertex",deepseek:"@ai-sdk/deepseek",cloudflare:"workers-ai-provider"},X=r(async e=>{try{return await import(e)}catch(t){let o=t;throw o?.code==="ERR_MODULE_NOT_FOUND"||o?.code==="MODULE_NOT_FOUND"?new Error(`Provider package "${e}" is not installed. Add it to your project: npm install ${e}`):t}},"loadProvider"),Ee=r(async(e,t)=>{let o=t.providerOptions??{};switch(t.providerType){case "openai":{let{createOpenAI:n}=await X(V.openai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "anthropic":{let{createAnthropic:n}=await X(V.anthropic);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "openai-compatible":{if(!t.baseURL)throw new Error("openai-compatible provider requires baseURL");let{createOpenAICompatible:n}=await X(V["openai-compatible"]);return n({name:e,baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "google":{let{createGoogleGenerativeAI:n}=await X(V.google);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "xai":{let{createXai:n}=await X(V.xai);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "azure":{if(!t.baseURL)throw new Error("azure provider requires baseURL (Azure OpenAI deployment URL)");let{createAzure:n}=await X(V.azure);return n({baseURL:t.baseURL,apiKey:t.apiKey,...o})(t.model)}case "amazon-bedrock":{let{createAmazonBedrock:n}=await X(V["amazon-bedrock"]);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "google-vertex":{let{createVertex:n}=await X(V["google-vertex"]);return n({baseURL:t.baseURL||void 0,...o})(t.model)}case "deepseek":{let{createDeepSeek:n}=await X(V.deepseek);return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "gateway":{let{createGateway:n}=await import('ai');return n({baseURL:t.baseURL||void 0,apiKey:t.apiKey,...o})(t.model)}case "cloudflare":{let s=(typeof o.accountId=="string"?o.accountId:void 0)??process.env.CLOUDFLARE_ACCOUNT_ID?.trim(),{accountId:i,...a}=o;if(!s&&!("binding"in a))throw new Error("cloudflare provider requires accountId (set providerOptions.accountId, CLOUDFLARE_ACCOUNT_ID, or providerOptions.binding for a Worker runtime)");let{createWorkersAI:c}=await X(V.cloudflare),l="binding"in a?a:{accountId:s,apiKey:t.apiKey,...a};return c(l)(t.model)}}},"buildModelFromStage");var yn=r(e=>e.flatMap((t,o)=>t.role==="tool"&&Array.isArray(t.content)?t.content.flatMap((n,s)=>n.type==="tool-result"?[`${o}:${s}`]:[]):[]),"positionsOf"),Tn=r(e=>`[${e} result cleared to save context \u2014 call the tool again if you still need it]`,"stub"),Nt=r(e=>{try{return re(JSON.stringify(e))}catch{return 0}},"estimate"),Dt=r((e,t)=>{let o=Math.max(0,e.keep??3),n=new Set,s=r(i=>n.size===0?i:i.map((a,c)=>a.role==="tool"&&Array.isArray(a.content)?{...a,content:a.content.map((l,u)=>l.type==="tool-result"&&n.has(`${c}:${u}`)?{...l,output:{type:"text",value:Tn(l.toolName)}}:l)}:a),"apply");return i=>{let a=s(i),c=Nt(a);if(c<=e.triggerTokens)return a;let l=yn(i),u=0;for(let f of l.slice(0,Math.max(0,l.length-o)))n.has(f)||(n.add(f),u+=1);if(u===0)return a;let p=s(i);return t?.({cleared:u,beforeTokens:c,afterTokens:Nt(p)}),p}},"createToolResultClearer");var jt=/^[a-z0-9-]{1,64}$/,wn="load_skill",bn="read_skill_file",vn=24e3,Ft=r(e=>{let t=e.replace(/\\/g,"/").replace(/^\.\/+/,""),o=po.posix.normalize(t);if(!o||o==="."||o.startsWith("/")||o===".."||o.startsWith("../"))throw new Error(`skill file path must be relative and stay inside the skill: "${e}"`);return o},"normalizeSkillPath"),Sn=r(e=>{if(!e||typeof e!="object")throw new Error("skill must be an object { name, description, content, files? }");let{name:t,description:o,content:n,files:s}=e;if(typeof t!="string"||!jt.test(t))throw new Error(`skill name must match ${jt} (got ${JSON.stringify(t)})`);if(typeof o!="string"||!o.trim())throw new Error(`skill "${t}": description is required`);if(typeof n!="string")throw new Error(`skill "${t}": content must be a string`);if(s!==void 0&&!Array.isArray(s))throw new Error(`skill "${t}": files must be an array of { path, content }`);let i=new Set,a=(s??[]).map(c=>{if(!c||typeof c.path!="string"||typeof c.content!="string")throw new Error(`skill "${t}": every file needs a string path and content`);let l;try{l=Ft(c.path);}catch(u){throw new Error(`skill "${t}": ${u.message}`)}if(i.has(l))throw new Error(`skill "${t}": duplicate file "${l}"`);return i.add(l),{path:l,content:c.content}});return {name:t,description:o.trim(),content:n,...a.length?{files:a}:{}}},"defineSkill");var Kt=r(e=>{let t=[],o=new Set;for(let n of e??[]){let s=Sn(n);if(o.has(s.name))throw new Error(`duplicate skill name "${s.name}"`);o.add(s.name),t.push(s);}return t},"validateSkills"),In=r((e,t)=>{let o=e.replace(/\s+/g," ").trim();return o.length>t?`${o.slice(0,t)}\u2026`:o},"oneLine"),Xe=r(e=>e.map(t=>`- ${t.name}: ${In(t.description,300)}`).join(`
14
14
  `),"renderSkillsIndex"),Wt=r((e,t,o=vn)=>{let n=new Map(e.map(a=>[a.name,a])),s=[],i=0;for(let a of t){let c=n.get(a);if(!c)continue;let l=`### Skill: ${c.name}
15
15
  ${c.content.trim()}`,u=o-i;if(u<=0){s.push(`### Skill: ${c.name}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dudko.dev/agent",
3
- "version": "0.0.35",
3
+ "version": "0.0.36",
4
4
  "type": "module",
5
5
  "description": "Tool-using planning agent over MCP servers, built on the Vercel AI SDK.",
6
6
  "keywords": [
@@ -91,7 +91,7 @@
91
91
  "dependencies": {
92
92
  "@modelcontextprotocol/sdk": "^1.32.2",
93
93
  "@opentelemetry/api": "^1.10.0",
94
- "ai": "^7.0.159",
94
+ "ai": "^7.0.164",
95
95
  "zod": "^4.6.7"
96
96
  },
97
97
  "peerDependencies": {
@@ -139,15 +139,15 @@
139
139
  }
140
140
  },
141
141
  "devDependencies": {
142
- "@ai-sdk/amazon-bedrock": "^5.0.130",
143
- "@ai-sdk/anthropic": "^4.0.94",
144
- "@ai-sdk/azure": "^4.0.114",
145
- "@ai-sdk/deepseek": "^3.0.77",
146
- "@ai-sdk/google": "^4.0.109",
147
- "@ai-sdk/google-vertex": "^5.0.129",
148
- "@ai-sdk/openai": "^4.0.106",
149
- "@ai-sdk/openai-compatible": "^3.0.82",
150
- "@ai-sdk/xai": "^5.0.35",
142
+ "@ai-sdk/amazon-bedrock": "^5.0.134",
143
+ "@ai-sdk/anthropic": "^4.0.98",
144
+ "@ai-sdk/azure": "^4.0.118",
145
+ "@ai-sdk/deepseek": "^3.0.80",
146
+ "@ai-sdk/google": "^4.0.113",
147
+ "@ai-sdk/google-vertex": "^5.0.133",
148
+ "@ai-sdk/openai": "^4.0.110",
149
+ "@ai-sdk/openai-compatible": "^3.0.86",
150
+ "@ai-sdk/xai": "^5.0.39",
151
151
  "@types/node": "^22.9.0",
152
152
  "prettier": "^3.9.10",
153
153
  "tsup": "^9.0.0",