@netlify/agent-runner-cli 2.3.3 → 2.4.0

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.
@@ -77,7 +77,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
77
77
  `))};function bc(e){return{log:(...t)=>{hi()&&console.log(`[AR]-[${e}]${mi()}`,...t)},error:(...t)=>{hi()&&Ax(console.error,`[AR]-[ERROR]-[${e}]${mi()}`,t,"error")},warn:(...t)=>{hi()&&Ax(console.warn,`[AR]-[WARN]-[${e}]${mi()}`,t,"warn")},info:(...t)=>{hi()&&console.info(`[AR]-[${e}]${mi()}`,...t)},debug:(...t)=>{hi()&&console.debug(`[AR]-[DEBUG]-[${e}]${mi()}`,...t)}}}import{AsyncLocalStorage as oR}from"async_hooks";import iR from"dgram";import Cn from"process";var aR="buildbot.agent_runner.",sR=8125,cR=e=>{let t=Object.keys(e);return t.length===0?"":"|#"+t.map(n=>`${n}:${e[n]}`).join(",")},gi=(e,t,n,o={})=>`${aR}${e}:${t}|${n}${cR(o)}`,uR={service:"buildbot"},lR={},dR=new oR;var vi=e=>({...lR,...dR.getStore()??{},...e,...uR}),pR=(e,t)=>{let n=!1,o=iR.createSocket("udp4");return o.unref(),o.once("error",r=>{if(!n){let i=r.code??r.message;Cn.stderr.write(`[metrics] UDP error: ${i}
78
78
  `),n=!0}}),r=>{n||(Qh++,o.send(r,t,e,i=>{if(Qh--,Qh===0)for(let a of fR)a();if(i&&!n){let a=i.code??i.message;Cn.stderr.write(`[metrics] UDP send to ${e}:${t} failed: ${a}
79
79
  `),n=!0}}))}},Qh=0,fR=new Set;var eg=()=>{},mR=()=>!!Cn.env.VITEST;var hR=()=>{if(mR())return eg;let e=Cn.env.HOST_NODE_IP;if(!e)return eg;let t=Cn.env.DD_AGENT_PORT,n=t===void 0?sR:Number(t);return!Number.isInteger(n)||n<=0||n>65535?(Cn.stderr.write(`[metrics] DD_AGENT_PORT="${t}" is not a valid port; metrics disabled
80
- `),eg):pR(e,n)},gR=(e=hR())=>({inc(t,n=1,o={}){e(gi(t,n,"c",vi(o)))},gauge(t,n,o={}){e(gi(t,n,"g",vi(o)))},histogram(t,n,o={}){e(gi(t,n,"h",vi(o)))},timing(t,n,o={}){e(gi(t,n,"ms",vi(o)))},distribution(t,n,o={}){e(gi(t,n,"d",vi(o)))}}),_i=gR();import{spawn as nL}from"child_process";import{existsSync as iL,mkdirSync as aL,writeFileSync as sL}from"fs";import{connect as uL}from"net";import vR from"path";import pL from"process";var mL=bc("step-preview"),hL=vR.join("apps","netlify-react-ui","public","agent-run-preview.json"),_R=9001,yR="components-agentrunners-rendersteps--live",gL=`http://localhost:${_R}/?path=/story/${yR}`;var xc=class extends Error{constructor(n,o,r){super(n);this.statusCode=o;this.userMessage=r;this.name="CreditLimitExceededError"}},wc=class extends Error{constructor(n,o,r){super(n);this.statusCode=o;this.userMessage=r;this.name="ApiResourceNotFoundError"}},yi=class extends Error{constructor(n,o){super(n);this.statusCode=o;this.name="ApiRequestError"}};var tg=$i.env.NETLIFY_API_URL,rg=$i.env.NETLIFY_API_TOKEN,Sr=bc("api"),$R=()=>$i.env.NETLIFY_LOCAL_MODE==="true",bR=new Set(["agent_runners","sessions","sites","accounts","branch"]),xR=new Set(["api","v1","agent_runners","sessions","sites","accounts","classify","diff","result","upload_urls","native_session","upload","update_usage","connections","tokens","ai-gateway","providers","agent-runners","token","database","branch","setup_requests"]),wR=e=>e.split("/").map((t,n,o)=>t===""?t:bR.has(o[n-1])?":id":xR.has(t)?t:":id").join("/"),kR=async(e,t={})=>{if(!tg||!rg)throw new Error("No API URL or token");let n=new URL(e,tg),o={...t,headers:{...t.headers,Authorization:`Bearer ${rg}`}};$i.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let r=t.method??"GET",i=wR(n.pathname),a=Date.now(),s;try{s=await fetch(n,o)}catch(d){throw Sr.error(fi({event:"api.request",method:r,path:n.pathname,resource:i,outcome:"network_error",error:d.message,duration_ms:Date.now()-a})),_i.inc("api.request",1,{method:r,resource:i}),_i.inc("api.request_failed",1,{status:"network_error",method:r,resource:i}),d}let c=s.ok&&s.status<=299;$i.env.AGENT_RUNNERS_DEBUG==="true"&&(Sr.log(`Response headers for ${n}:`),s.headers.forEach((d,f)=>{Sr.log(` ${f}: ${d}`)}));let u=fi({event:"api.request",method:r,path:n.pathname,resource:i,status:s.status,request_id:s.headers.get("x-request-id")||s.headers.get("x-nf-request-id"),duration_ms:Date.now()-a});if(_i.inc("api.request",1,{method:r,resource:i}),c?Sr.log(u):(Sr.error(u),_i.inc("api.request_failed",1,{status:s.status,method:r,resource:i})),t.raw){if(!c)throw new yi(`API request failed: ${s.status} ${s.statusText}`,s.status);return s}let l=await(s.headers.get("content-type")?.includes("application/json")?s.json():s.text());if(!c){let d=typeof l=="string"?l:JSON.stringify(l);throw s.status===404?new wc(`API request failed: 404 - ${d}`,404,"The site associated with this agent run no longer exists."):s.status===503&&t.gracefulOn503&&d.toLowerCase().includes("usage exceeded")?new xc(`API request failed: 503 - ${d}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners."):new yi(`API request failed: ${s.status} - ${d}`,s.status)}return l},Zx=e=>{Sr.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(tg=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(rg=e.constants.NETLIFY_API_TOKEN)};var Lx=async(e,t)=>$R()?(Sr.log("Mock API: getAgentConnectionTokens called",{runnerId:e,sessionId:t}),{connections:[]}):kR(`/api/v1/agent_runners/${e}/sessions/${t}/connections/tokens`,{method:"POST"});var qx=e=>e.type!=="actionkit",ng=e=>({mcp:e.filter(qx),actionkit:e.filter(t=>!qx(t))});var Mx=["user","project","team"],og=(e="project")=>{let t=Mx.indexOf(e);return t===-1?Mx.length:t};var SR={service:xt.string().min(1).describe('Service slug, e.g. "linear", "stripe", "slack".'),reason:xt.string().min(1).describe("One sentence on why the task needs it. Shown to the user on the consent prompt.")},ig=xt.object(SR),Fx="Request access to a third-party service that is not yet connected. Pauses the run so the user can authorize it in their browser; the run resumes automatically with that service available. Use this only when the task genuinely needs the service and none of its tools appear in your tool list, and say why in `reason`. Do NOT use it when you already have the service's tools and a call to one of them failed: a rejected argument, a schema error, or an unknown tool is a broken or misused tool, not missing authorization, and pausing will strand the run.";import vN from"process";var kc=class{constructor(t){this._client=t}async*callToolStream(t,n=Kt,o){let r=this._client,i={...o,task:o?.task??(r.isToolTask(t.name)?{}:void 0)},a=r.requestStream({method:"tools/call",params:t},n,i),s=r.getToolOutputValidator(t.name);for await(let c of a){if(c.type==="result"&&s){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new R(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new R(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof R){yield{type:"error",error:l};return}yield{type:"error",error:new R(C.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(t,n){return this._client.getTask({taskId:t},n)}async getTaskResult(t,n,o){return this._client.getTaskResult({taskId:t},n,o)}async listTasks(t,n){return this._client.listTasks(t?{cursor:t}:void 0,n)}async cancelTask(t,n){return this._client.cancelTask({taskId:t},n)}requestStream(t,n,o){return this._client.requestStream(t,n,o)}};function Sc(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let n=t,o=e.properties;for(let r of Object.keys(o)){let i=o[r];n[r]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(n[r]=i.default),n[r]!==void 0&&Sc(i,n[r])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!="boolean"&&Sc(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!="boolean"&&Sc(n,t)}}function zR(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var zc=class extends vn{constructor(t,n){super(n),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=n?.capabilities??{},this._jsonSchemaValidator=n?.jsonSchemaValidator??new Dn,n?.listChanged&&(this._pendingListChangedConfig=n.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Yf,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Wf,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Mf,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new kc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ns(this._capabilities,t)}setRequestHandler(t,n){let r=nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=on(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let s=async(c,u)=>{let l=Ue(tm,c);if(!l.success){let E=l.error instanceof Error?l.error.message:String(l.error);throw new R(C.InvalidParams,`Invalid elicitation request: ${E}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=zR(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new R(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new R(C.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(n(c,u));if(d.task){let E=Ue(kt,h);if(!E.success){let j=E.error instanceof Error?E.error.message:String(E.error);throw new R(C.InvalidParams,`Invalid task creation result: ${j}`)}return E.data}let v=Ue(Ht,h);if(!v.success){let E=v.error instanceof Error?v.error.message:String(v.error);throw new R(C.InvalidParams,`Invalid elicitation result: ${E}`)}let y=v.data,k=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&k&&this._capabilities.elicitation?.form?.applyDefaults)try{Sc(k,y.content)}catch{}return y};return super.setRequestHandler(t,s)}if(a==="sampling/createMessage"){let s=async(c,u)=>{let l=Ue(em,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new R(C.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let y=Ue(kt,f);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new R(C.InvalidParams,`Invalid task creation result: ${k}`)}return y.data}let h=d.tools||d.toolChoice?Do:fr,v=Ue(h,f);if(!v.success){let y=v.error instanceof Error?v.error.message:String(v.error);throw new R(C.InvalidParams,`Invalid sampling result: ${y}`)}return v.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,n)}assertCapability(t,n){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${n})`)}async connect(t,n){if(await super.connect(t),t.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:Vt,capabilities:this._capabilities,clientInfo:this._clientInfo}},Df,n);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!bs.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){gc(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&vc(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},wt,t)}async complete(t,n){return this.request({method:"completion/complete",params:t},rm,n)}async setLoggingLevel(t,n){return this.request({method:"logging/setLevel",params:{level:t}},wt,n)}async getPrompt(t,n){return this.request({method:"prompts/get",params:t},Gf,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},Ff,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Af,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Zf,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},qf,n)}async subscribeResource(t,n){return this.request({method:"resources/subscribe",params:t},wt,n)}async unsubscribeResource(t,n){return this.request({method:"resources/unsubscribe",params:t},wt,n)}async callTool(t,n=Kt,o){if(this.isToolTaskRequired(t.name))throw new R(C.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:"tools/call",params:t},n,o),i=this.getToolOutputValidator(t.name);if(i){if(!r.structuredContent&&!r.isError)throw new R(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let a=i(r.structuredContent);if(!a.valid)throw new R(C.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof R?a:new R(C.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return r}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let n of t){if(n.outputSchema){let r=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,r)}let o=n.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(n.name),o==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,n){let o=await this.request({method:"tools/list",params:t},Xf,n);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(t,n,o,r){let i=Ly.safeParse(o);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:s}=i.data,{onChanged:c}=o,u=async()=>{if(!a){c(null,null);return}try{let d=await r();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},l=()=>{if(s){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(u,s);this._listChangedDebounceTimers.set(t,f)}else u()};this.setNotificationHandler(n,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Gx=Uc(Hx(),1);function Wx(e){if(e)try{return Gx.default.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Ic(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Bx(e=fetch,t){return t?async(n,o)=>{let r={...t,...o,headers:o?.headers?{...Ic(t.headers),...Ic(o.headers)}:t.headers};return e(n,r)}:e}var UR=5,DR=[301,302,303,307,308];function CR(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port?!0:e.hostname===t.hostname&&e.protocol==="http:"&&e.port===""&&t.protocol==="https:"&&t.port===""}function Xx(e,t){let n=DR.includes(e.status)?e.headers.get("location"):null;try{return n?new URL(n,t):void 0}catch{return}}function Pc(e,t,n,o,r=0){let i=Xx(o,t),a=o.status===307||o.status===308||(n?.method??"GET").toUpperCase()==="GET";if(!i||r===UR||!a)return;let s=new URL(t);if(!((i.username||i.password)&&(i.username!==s.username||i.password!==s.password)||!CR(s,i)))return Promise.resolve(o.body?.cancel()).then(()=>e(i,{...n,redirect:"manual"})).then(u=>Pc(e,i,n,u,r+1)??u)}var Yx=new WeakSet;function sg(e){let t=(n,o)=>(e??fetch)(n,o);return Yx.add(t),t}function zr(e=fetch){return Yx.has(e)?e:(t,n)=>n?.redirect==="error"||n?.redirect==="manual"?e(t,n):Promise.resolve(e(t,{...n,redirect:"manual"})).then(o=>Pc(e,t,n,o)??o)}function Tc(e,t){if(e.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let n=e.url||t,o=Xx(e,n);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(n).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var cg;cg=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(e=>e.webcrypto);async function AR(e){return(await cg).getRandomValues(new Uint8Array(e))}async function ZR(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let r=await AR(e-o.length);for(let i of r)i<n&&(o+=t[i%t.length])}return o}async function LR(e){return await ZR(e)}async function qR(e){let t=await(await cg).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function ug(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await LR(e),n=await qR(t);return{code_verifier:t,code_challenge:n}}var ze=Xa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ef.custom,message:"URL must be parseable",fatal:!0}),qn}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ew=me({resource:m().url(),authorization_servers:z(ze).optional(),jwks_uri:m().url().optional(),scopes_supported:z(m()).optional(),bearer_methods_supported:z(m()).optional(),resource_signing_alg_values_supported:z(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:ee().optional(),authorization_details_types_supported:z(m()).optional(),dpop_signing_alg_values_supported:z(m()).optional(),dpop_bound_access_tokens_required:ee().optional()}),lg=me({issuer:m(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.optional(),scopes_supported:z(m()).optional(),response_types_supported:z(m()),response_modes_supported:z(m()).optional(),grant_types_supported:z(m()).optional(),token_endpoint_auth_methods_supported:z(m()).optional(),token_endpoint_auth_signing_alg_values_supported:z(m()).optional(),service_documentation:ze.optional(),revocation_endpoint:ze.optional(),revocation_endpoint_auth_methods_supported:z(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:z(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(m()).optional(),code_challenge_methods_supported:z(m()).optional(),client_id_metadata_document_supported:ee().optional()}),MR=me({issuer:m(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.optional(),scopes_supported:z(m()).optional(),response_types_supported:z(m()),response_modes_supported:z(m()).optional(),grant_types_supported:z(m()).optional(),acr_values_supported:z(m()).optional(),subject_types_supported:z(m()),id_token_signing_alg_values_supported:z(m()),id_token_encryption_alg_values_supported:z(m()).optional(),id_token_encryption_enc_values_supported:z(m()).optional(),userinfo_signing_alg_values_supported:z(m()).optional(),userinfo_encryption_alg_values_supported:z(m()).optional(),userinfo_encryption_enc_values_supported:z(m()).optional(),request_object_signing_alg_values_supported:z(m()).optional(),request_object_encryption_alg_values_supported:z(m()).optional(),request_object_encryption_enc_values_supported:z(m()).optional(),token_endpoint_auth_methods_supported:z(m()).optional(),token_endpoint_auth_signing_alg_values_supported:z(m()).optional(),display_values_supported:z(m()).optional(),claim_types_supported:z(m()).optional(),claims_supported:z(m()).optional(),service_documentation:m().optional(),claims_locales_supported:z(m()).optional(),ui_locales_supported:z(m()).optional(),claims_parameter_supported:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:ee().optional()}),tw=P({...MR.shape,...lg.pick({code_challenge_methods_supported:!0}).shape}),rw=P({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:So.number().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:m().optional().catch(void 0)}).strip(),nw=P({error:m(),error_description:m().optional(),error_uri:m().optional()}),Qx=ze.optional().or(N("").transform(()=>{})),FR=P({redirect_uris:z(ze),token_endpoint_auth_method:m().optional(),grant_types:z(m()).optional(),response_types:z(m()).optional(),client_name:m().optional(),client_uri:ze.optional(),logo_uri:Qx,scope:m().optional(),contacts:z(m()).optional(),tos_uri:Qx,policy_uri:m().optional(),jwks_uri:ze.optional(),jwks:ms().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),VR=P({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional(),issuer:m().optional().catch(void 0)}).strip(),ow=FR.merge(VR),eq=P({error:m(),error_description:m().optional()}).strip(),tq=P({token:m(),token_type_hint:m().optional()}).strip();function iw(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function aw({requestedResource:e,configuredResource:t}){let n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;let r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return r.startsWith(i)}var ge=class extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},bi=class extends ge{};bi.errorCode="invalid_request";var Ir=class extends ge{};Ir.errorCode="invalid_client";var Pr=class extends ge{};Pr.errorCode="invalid_grant";var Tr=class extends ge{};Tr.errorCode="unauthorized_client";var xi=class extends ge{};xi.errorCode="unsupported_grant_type";var wi=class extends ge{};wi.errorCode="invalid_scope";var ki=class extends ge{};ki.errorCode="access_denied";var Et=class extends ge{};Et.errorCode="server_error";var Si=class extends ge{};Si.errorCode="temporarily_unavailable";var zi=class extends ge{};zi.errorCode="unsupported_response_type";var Ii=class extends ge{};Ii.errorCode="unsupported_token_type";var Pi=class extends ge{};Pi.errorCode="invalid_token";var Ti=class extends ge{};Ti.errorCode="method_not_allowed";var Ei=class extends ge{};Ei.errorCode="too_many_requests";var Er=class extends ge{};Er.errorCode="invalid_client_metadata";var Oi=class extends ge{};Oi.errorCode="insufficient_scope";var ji=class extends ge{};ji.errorCode="invalid_target";var sw={[bi.errorCode]:bi,[Ir.errorCode]:Ir,[Pr.errorCode]:Pr,[Tr.errorCode]:Tr,[xi.errorCode]:xi,[wi.errorCode]:wi,[ki.errorCode]:ki,[Et.errorCode]:Et,[Si.errorCode]:Si,[zi.errorCode]:zi,[Ii.errorCode]:Ii,[Pi.errorCode]:Pi,[Ti.errorCode]:Ti,[Ei.errorCode]:Ei,[Er.errorCode]:Er,[Oi.errorCode]:Oi,[ji.errorCode]:ji};var Ot=class extends Error{constructor(t){super(t??"Unauthorized")}};function JR(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var dg="code",pg="S256";function KR(e,t){let n=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&JR(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?"client_secret_basic":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function HR(e,t,n,o){let{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":GR(r,i,n);return;case"client_secret_post":WR(r,i,o);return;case"none":BR(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function GR(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${o}`)}function WR(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function BR(e,t){t.set("client_id",e)}async function uw(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let o=nw.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=sw[r]||Et;return new s(i||"",a)}catch(o){let r=e instanceof Response?Tc(e,e.url):void 0,i=`${t?`HTTP ${t}: `:""}${r??`Invalid OAuth error response: ${o}. Raw body: ${n}`}`;return new Et(i)}}function XR(e,t){let[n,o]=[e,t];try{[n,o]=[new URL(e).href,new URL(t).href]}catch{}return n===o||n.endsWith("/")&&n.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===n}function hg(e,t){if(e)return typeof e.issuer!="string"?e.issuer==null?e:{...e,issuer:void 0}:XR(e.issuer,t)?e:void 0}var YR=rw.omit({issuer:!0}),QR=ow.omit({issuer:!0});function lw(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function Ri(e,t){try{return await fg(e,t)}catch(n){if(n instanceof Ir||n instanceof Tr)return await e.invalidateCredentials?.("all"),await fg(e,t);if(n instanceof Pr)return await e.invalidateCredentials?.("tokens"),await fg(e,t);throw n}}async function fg(e,{serverUrl:t,authorizationCode:n,scope:o,resourceMetadataUrl:r,fetchFn:i}){let a=await e.discoveryState?.(),s,c,u,l=r;if(!l&&a?.resourceMetadataUrl&&(l=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(c=a.authorizationServerUrl,s=a.resourceMetadata,u=a.authorizationServerMetadata??await pw(c,{fetchFn:i}),!s)try{s=await dw(t,{resourceMetadataUrl:l},i)}catch{}(u!==a.authorizationServerMetadata||s!==a.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}else{let G=await aN(t,{resourceMetadataUrl:l,fetchFn:i});c=G.authorizationServerUrl,u=G.authorizationServerMetadata,s=G.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}let d=String(c),f=await tN(t,e,s),p=f&&s&&!e.validateResourceURL?s.resource:f,h=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,v=await Promise.resolve(e.clientInformation()),y=hg(v,d),k=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(v&&!y&&!k)throw lw(v,d);let E=y?.issuer==null?y:void 0,j=async()=>{try{E&&await e.saveClientInformation?.({...E,issuer:d})}catch{}};if(!y){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let G=u?.client_id_metadata_document_supported===!0,ve=e.clientMetadataUrl;if(ve&&!eN(ve))throw new Er(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ve}`);if(G&&ve)y={client_id:ve,issuer:d},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");y={...await dN(c,{metadata:u,clientMetadata:e.clientMetadata,scope:h,fetchFn:i}),issuer:d},await e.saveClientInformation(y)}}let U=!e.redirectUrl;if(n!==void 0||U){let G=await lN(e,c,{metadata:u,resource:p,authorizationCode:n,fetchFn:i});return await j(),await e.saveTokens({...G,issuer:d}),"AUTHORIZED"}let $=hg(await e.tokens(),d);if($?.refresh_token&&$.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),$?.refresh_token)try{let G=await uN(c,{metadata:u,clientInformation:y,refreshToken:$.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await j(),await e.saveTokens({...G,issuer:d}),"AUTHORIZED"}catch(G){if(!(!(G instanceof ge)||G instanceof Et))throw G}let I=e.state?await e.state():void 0,{authorizationUrl:A,codeVerifier:le}=await sN(c,{metadata:u,clientInformation:y,state:I,redirectUrl:e.redirectUrl,scope:h,resource:p});return await e.saveCodeVerifier(le),await e.redirectToAuthorization(A),"REDIRECT"}function eN(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function tN(e,t,n){let o=iw(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!aw({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}function gg(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[n,o]=t.split(" ");if(n.toLowerCase()!=="bearer"||!o)return{};let r=mg(e,"resource_metadata")||void 0,i;if(r)try{i=new URL(r)}catch{}let a=mg(e,"scope")||void 0,s=mg(e,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function mg(e,t){let n=e.headers.get("WWW-Authenticate");if(!n)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),r=n.match(o);return r?r[1]||r[2]:null}async function dw(e,t,n=fetch){let o=await oN(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ew.parse(await o.json())}async function vg(e,t,n=fetch){try{return await zr(n)(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?vg(e,void 0,n):void 0;throw o}}function rN(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function cw(e,t,n=fetch){return await vg(e,{"MCP-Protocol-Version":t},n)}function nN(e,t){return!e||!e.ok&&e.status<500&&t!=="/"}async function oN(e,t,n,o){let r=new URL(e),i=o?.protocolVersion??Vt,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let c=rN(t,r.pathname);a=new URL(c,o?.metadataServerUrl??r),a.search=r.search}let s=await cw(a,i,n);if(!o?.metadataUrl&&nN(s,r.pathname)){let c=new URL(`/.well-known/${t}`,r);s=await cw(c,i,n)}return s}function iN(e){let t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),o.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function pw(e,{fetchFn:t=fetch,protocolVersion:n=Vt}={}){let o={"MCP-Protocol-Version":n,Accept:"application/json"},r=iN(e);for(let{url:i,type:a}of r){let s=await vg(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?lg.parse(await s.json()):tw.parse(await s.json())}}}async function aN(e,t){let n,o;try{n=await dw(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(o=n.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let r=await pw(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:r,resourceMetadata:n}}function fw(e){return typeof e=="string"?e:e.href}async function sN(e,{metadata:t,clientInformation:n,redirectUrl:o,scope:r,state:i,resource:a}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(dg))throw new Error(`Incompatible auth server: does not support response type ${dg}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(pg))throw new Error(`Incompatible auth server: does not support code challenge method ${pg}`)}else s=new URL("/authorize",e);let c=await ug(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",dg),s.searchParams.set("client_id",n.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",pg),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),r&&s.searchParams.set("scope",r),r?.includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",fw(a)),{authorizationUrl:s,codeVerifier:u}}function cN(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}async function mw(e,{metadata:t,tokenRequestParams:n,clientInformation:o,addClientAuthentication:r,resource:i,fetchFn:a}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&n.set("resource",fw(i)),r)await r(c,n,s,t);else if(o){let l=t?.token_endpoint_auth_methods_supported??[],d=KR(o,l);HR(d,o,c,n)}let u=await zr(a??fetch)(s,{method:"POST",headers:c,body:n});if(!u.ok)throw await uw(u);return YR.parse(await u.json())}async function uN(e,{metadata:t,clientInformation:n,refreshToken:o,resource:r,addClientAuthentication:i,fetchFn:a}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await mw(e,{metadata:t,tokenRequestParams:s,clientInformation:n,addClientAuthentication:i,resource:r,fetchFn:a});return{refresh_token:o,...c}}async function lN(e,t,{metadata:n,resource:o,authorizationCode:r,fetchFn:i}={}){let a=async()=>{let l=await e.clientInformation(),d=hg(l,String(t));if(l&&!d)throw lw(l,String(t));return d},s=await a(),c=e.clientMetadata.scope,u;if(e.prepareTokenRequest&&(u=await e.prepareTokenRequest(c)),!u){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await e.codeVerifier();u=cN(r,l,e.redirectUrl)}return s??(s=await a()),mw(t,{metadata:n,tokenRequestParams:u,clientInformation:s,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function dN(e,{metadata:t,clientMetadata:n,scope:o,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a=await zr(r??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await uw(a);return QR.parse(await a.json())}var Ni=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}},hw=10,pN=13,Or=32;function _g(e){}function _w(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=_g,onError:n=_g,onRetry:o=_g,onComment:r,maxBufferSize:i}=e,a=[],s=0,c=!0,u,l="",d=0,f,p=!1;function h($){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,$.charCodeAt(0)===239&&$.charCodeAt(1)===187&&$.charCodeAt(2)===191&&($=$.slice(3))),a.length===0){let le=y($);le!==""&&(a.push(le),s=le.length),v();return}if($.indexOf(`
80
+ `),eg):pR(e,n)},gR=(e=hR())=>({inc(t,n=1,o={}){e(gi(t,n,"c",vi(o)))},gauge(t,n,o={}){e(gi(t,n,"g",vi(o)))},histogram(t,n,o={}){e(gi(t,n,"h",vi(o)))},timing(t,n,o={}){e(gi(t,n,"ms",vi(o)))},distribution(t,n,o={}){e(gi(t,n,"d",vi(o)))}}),_i=gR();import{spawn as nL}from"child_process";import{existsSync as iL,mkdirSync as aL,writeFileSync as sL}from"fs";import{connect as uL}from"net";import vR from"path";import pL from"process";var mL=bc("step-preview"),hL=vR.join("apps","netlify-react-ui","public","agent-run-preview.json"),_R=9001,yR="components-agentrunners-rendersteps--live",gL=`http://localhost:${_R}/?path=/story/${yR}`;var xc=class extends Error{constructor(n,o,r){super(n);this.statusCode=o;this.userMessage=r;this.name="CreditLimitExceededError"}},wc=class extends Error{constructor(n,o,r){super(n);this.statusCode=o;this.userMessage=r;this.name="ApiResourceNotFoundError"}},yi=class extends Error{constructor(n,o){super(n);this.statusCode=o;this.name="ApiRequestError"}};var tg=$i.env.NETLIFY_API_URL,rg=$i.env.NETLIFY_API_TOKEN,Sr=bc("api"),$R=()=>$i.env.NETLIFY_LOCAL_MODE==="true",bR=new Set(["agent_runners","sessions","sites","accounts","branch","dev_servers"]),xR=new Set(["api","v1","agent_runners","sessions","sites","accounts","classify","diff","result","upload_urls","native_session","upload","update_usage","connections","tokens","ai-gateway","providers","agent-runners","token","database","branch","dev_servers","config","setup_requests"]),wR=e=>e.split("/").map((t,n,o)=>t===""?t:bR.has(o[n-1])?":id":xR.has(t)?t:":id").join("/"),kR=async(e,t={})=>{if(!tg||!rg)throw new Error("No API URL or token");let n=new URL(e,tg),o={...t,headers:{...t.headers,Authorization:`Bearer ${rg}`}};$i.env.AGENT_RUNNERS_DEBUG==="true"&&(o.headers["x-nf-debug-logging"]="true"),t.json&&(o.headers||={},o.headers["Content-Type"]="application/json",o.body=JSON.stringify(t.json));let r=t.method??"GET",i=wR(n.pathname),a=Date.now(),s;try{s=await fetch(n,o)}catch(d){throw Sr.error(fi({event:"api.request",method:r,path:n.pathname,resource:i,outcome:"network_error",error:d.message,duration_ms:Date.now()-a})),_i.inc("api.request",1,{method:r,resource:i}),_i.inc("api.request_failed",1,{status:"network_error",method:r,resource:i}),d}let c=s.ok&&s.status<=299;$i.env.AGENT_RUNNERS_DEBUG==="true"&&(Sr.log(`Response headers for ${n}:`),s.headers.forEach((d,f)=>{Sr.log(` ${f}: ${d}`)}));let u=fi({event:"api.request",method:r,path:n.pathname,resource:i,status:s.status,request_id:s.headers.get("x-request-id")||s.headers.get("x-nf-request-id"),duration_ms:Date.now()-a});if(_i.inc("api.request",1,{method:r,resource:i}),c?Sr.log(u):(Sr.error(u),_i.inc("api.request_failed",1,{status:s.status,method:r,resource:i})),t.raw){if(!c)throw new yi(`API request failed: ${s.status} ${s.statusText}`,s.status);return s}let l=await(s.headers.get("content-type")?.includes("application/json")?s.json():s.text());if(!c){let d=typeof l=="string"?l:JSON.stringify(l);throw s.status===404?new wc(`API request failed: 404 - ${d}`,404,"The site associated with this agent run no longer exists."):s.status===503&&t.gracefulOn503&&d.toLowerCase().includes("usage exceeded")?new xc(`API request failed: 503 - ${d}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners."):new yi(`API request failed: ${s.status} - ${d}`,s.status)}return l},Zx=e=>{Sr.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(tg=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(rg=e.constants.NETLIFY_API_TOKEN)};var Lx=async(e,t)=>$R()?(Sr.log("Mock API: getAgentConnectionTokens called",{runnerId:e,sessionId:t}),{connections:[]}):kR(`/api/v1/agent_runners/${e}/sessions/${t}/connections/tokens`,{method:"POST"});var qx=e=>e.type!=="actionkit",ng=e=>({mcp:e.filter(qx),actionkit:e.filter(t=>!qx(t))});var Mx=["user","project","team"],og=(e="project")=>{let t=Mx.indexOf(e);return t===-1?Mx.length:t};var SR={service:xt.string().min(1).describe('Service slug, e.g. "linear", "stripe", "slack".'),reason:xt.string().min(1).describe("One sentence on why the task needs it. Shown to the user on the consent prompt.")},ig=xt.object(SR),Fx="Request access to a third-party service that is not yet connected. Pauses the run so the user can authorize it in their browser; the run resumes automatically with that service available. Use this only when the task genuinely needs the service and none of its tools appear in your tool list, and say why in `reason`. Do NOT use it when you already have the service's tools and a call to one of them failed: a rejected argument, a schema error, or an unknown tool is a broken or misused tool, not missing authorization, and pausing will strand the run.";import vN from"process";var kc=class{constructor(t){this._client=t}async*callToolStream(t,n=Kt,o){let r=this._client,i={...o,task:o?.task??(r.isToolTask(t.name)?{}:void 0)},a=r.requestStream({method:"tools/call",params:t},n,i),s=r.getToolOutputValidator(t.name);for await(let c of a){if(c.type==="result"&&s){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new R(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let l=s(u.structuredContent);if(!l.valid){yield{type:"error",error:new R(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof R){yield{type:"error",error:l};return}yield{type:"error",error:new R(C.InvalidParams,`Failed to validate structured content: ${l instanceof Error?l.message:String(l)}`)};return}}yield c}}async getTask(t,n){return this._client.getTask({taskId:t},n)}async getTaskResult(t,n,o){return this._client.getTaskResult({taskId:t},n,o)}async listTasks(t,n){return this._client.listTasks(t?{cursor:t}:void 0,n)}async cancelTask(t,n){return this._client.cancelTask({taskId:t},n)}requestStream(t,n,o){return this._client.requestStream(t,n,o)}};function Sc(e,t){if(!(!e||t===null||typeof t!="object")){if(e.type==="object"&&e.properties&&typeof e.properties=="object"){let n=t,o=e.properties;for(let r of Object.keys(o)){let i=o[r];n[r]===void 0&&Object.prototype.hasOwnProperty.call(i,"default")&&(n[r]=i.default),n[r]!==void 0&&Sc(i,n[r])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!="boolean"&&Sc(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!="boolean"&&Sc(n,t)}}function zR(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}var zc=class extends vn{constructor(t,n){super(n),this._clientInfo=t,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=n?.capabilities??{},this._jsonSchemaValidator=n?.jsonSchemaValidator??new Dn,n?.listChanged&&(this._pendingListChangedConfig=n.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Yf,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Wf,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",Mf,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new kc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ns(this._capabilities,t)}setRequestHandler(t,n){let r=nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i=on(r);if(typeof i!="string")throw new Error("Schema method literal must be a string");let a=i;if(a==="elicitation/create"){let s=async(c,u)=>{let l=Ue(tm,c);if(!l.success){let E=l.error instanceof Error?l.error.message:String(l.error);throw new R(C.InvalidParams,`Invalid elicitation request: ${E}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=zR(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new R(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new R(C.InvalidParams,"Client does not support URL-mode elicitation requests");let h=await Promise.resolve(n(c,u));if(d.task){let E=Ue(kt,h);if(!E.success){let j=E.error instanceof Error?E.error.message:String(E.error);throw new R(C.InvalidParams,`Invalid task creation result: ${j}`)}return E.data}let v=Ue(Ht,h);if(!v.success){let E=v.error instanceof Error?v.error.message:String(v.error);throw new R(C.InvalidParams,`Invalid elicitation result: ${E}`)}let y=v.data,k=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&k&&this._capabilities.elicitation?.form?.applyDefaults)try{Sc(k,y.content)}catch{}return y};return super.setRequestHandler(t,s)}if(a==="sampling/createMessage"){let s=async(c,u)=>{let l=Ue(em,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new R(C.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let y=Ue(kt,f);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new R(C.InvalidParams,`Invalid task creation result: ${k}`)}return y.data}let h=d.tools||d.toolChoice?Do:fr,v=Ue(h,f);if(!v.success){let y=v.error instanceof Error?v.error.message:String(v.error);throw new R(C.InvalidParams,`Invalid sampling result: ${y}`)}return v.data};return super.setRequestHandler(t,s)}return super.setRequestHandler(t,n)}assertCapability(t,n){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${n})`)}async connect(t,n){if(await super.connect(t),t.sessionId===void 0)try{let o=await this.request({method:"initialize",params:{protocolVersion:Vt,capabilities:this._capabilities,clientInfo:this._clientInfo}},Df,n);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!bs.includes(o.protocolVersion))throw new Error(`Server's protocol version is not supported: ${o.protocolVersion}`);this._serverCapabilities=o.capabilities,this._serverVersion=o.serverInfo,t.setProtocolVersion&&t.setProtocolVersion(o.protocolVersion),this._instructions=o.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(o){throw this.close(),o}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(t){switch(t){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${t})`);if(t==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${t})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${t})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${t})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${t})`);break;case"ping":break}}assertTaskCapability(t){gc(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&vc(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},wt,t)}async complete(t,n){return this.request({method:"completion/complete",params:t},rm,n)}async setLoggingLevel(t,n){return this.request({method:"logging/setLevel",params:{level:t}},wt,n)}async getPrompt(t,n){return this.request({method:"prompts/get",params:t},Gf,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},Ff,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Af,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Zf,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},qf,n)}async subscribeResource(t,n){return this.request({method:"resources/subscribe",params:t},wt,n)}async unsubscribeResource(t,n){return this.request({method:"resources/unsubscribe",params:t},wt,n)}async callTool(t,n=Kt,o){if(this.isToolTaskRequired(t.name))throw new R(C.InvalidRequest,`Tool "${t.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let r=await this.request({method:"tools/call",params:t},n,o),i=this.getToolOutputValidator(t.name);if(i){if(!r.structuredContent&&!r.isError)throw new R(C.InvalidRequest,`Tool ${t.name} has an output schema but did not return structured content`);if(r.structuredContent)try{let a=i(r.structuredContent);if(!a.valid)throw new R(C.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof R?a:new R(C.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return r}isToolTask(t){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(t):!1}isToolTaskRequired(t){return this._cachedRequiredTaskTools.has(t)}cacheToolMetadata(t){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let n of t){if(n.outputSchema){let r=this._jsonSchemaValidator.getValidator(n.outputSchema);this._cachedToolOutputValidators.set(n.name,r)}let o=n.execution?.taskSupport;(o==="required"||o==="optional")&&this._cachedKnownTaskTools.add(n.name),o==="required"&&this._cachedRequiredTaskTools.add(n.name)}}getToolOutputValidator(t){return this._cachedToolOutputValidators.get(t)}async listTools(t,n){let o=await this.request({method:"tools/list",params:t},Xf,n);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(t,n,o,r){let i=Ly.safeParse(o);if(!i.success)throw new Error(`Invalid ${t} listChanged options: ${i.error.message}`);if(typeof o.onChanged!="function")throw new Error(`Invalid ${t} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:s}=i.data,{onChanged:c}=o,u=async()=>{if(!a){c(null,null);return}try{let d=await r();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},l=()=>{if(s){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let f=setTimeout(u,s);this._listChangedDebounceTimers.set(t,f)}else u()};this.setNotificationHandler(n,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var Gx=Uc(Hx(),1);function Wx(e){if(e)try{return Gx.default.parse(e).type}catch{let t=(e.split(";",1)[0]??"").trim().toLowerCase();return t===""||e.slice(t.length).includes(",")?void 0:t}}function Ic(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Bx(e=fetch,t){return t?async(n,o)=>{let r={...t,...o,headers:o?.headers?{...Ic(t.headers),...Ic(o.headers)}:t.headers};return e(n,r)}:e}var UR=5,DR=[301,302,303,307,308];function CR(e,t){return e.protocol===t.protocol&&e.hostname===t.hostname&&e.port===t.port?!0:e.hostname===t.hostname&&e.protocol==="http:"&&e.port===""&&t.protocol==="https:"&&t.port===""}function Xx(e,t){let n=DR.includes(e.status)?e.headers.get("location"):null;try{return n?new URL(n,t):void 0}catch{return}}function Pc(e,t,n,o,r=0){let i=Xx(o,t),a=o.status===307||o.status===308||(n?.method??"GET").toUpperCase()==="GET";if(!i||r===UR||!a)return;let s=new URL(t);if(!((i.username||i.password)&&(i.username!==s.username||i.password!==s.password)||!CR(s,i)))return Promise.resolve(o.body?.cancel()).then(()=>e(i,{...n,redirect:"manual"})).then(u=>Pc(e,i,n,u,r+1)??u)}var Yx=new WeakSet;function sg(e){let t=(n,o)=>(e??fetch)(n,o);return Yx.add(t),t}function zr(e=fetch){return Yx.has(e)?e:(t,n)=>n?.redirect==="error"||n?.redirect==="manual"?e(t,n):Promise.resolve(e(t,{...n,redirect:"manual"})).then(o=>Pc(e,t,n,o)??o)}function Tc(e,t){if(e.type==="opaqueredirect")return"Redirect not followed: this runtime does not expose the redirect target";let n=e.url||t,o=Xx(e,n);if(o)return o.username=o.password=o.search=o.hash="",o.protocol==="http:"&&new URL(n).protocol==="https:"?(o.protocol="https:",`Redirect to plain http not followed; try ${o.href} instead`):`Redirect to ${o.href} not followed`}var cg;cg=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(e=>e.webcrypto);async function AR(e){return(await cg).getRandomValues(new Uint8Array(e))}async function ZR(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let r=await AR(e-o.length);for(let i of r)i<n&&(o+=t[i%t.length])}return o}async function LR(e){return await ZR(e)}async function qR(e){let t=await(await cg).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function ug(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await LR(e),n=await qR(t);return{code_verifier:t,code_challenge:n}}var ze=Xa().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:Ef.custom,message:"URL must be parseable",fatal:!0}),qn}).refine(e=>{let t=new URL(e);return t.protocol!=="javascript:"&&t.protocol!=="data:"&&t.protocol!=="vbscript:"},{message:"URL cannot use javascript:, data:, or vbscript: scheme"}),ew=me({resource:m().url(),authorization_servers:z(ze).optional(),jwks_uri:m().url().optional(),scopes_supported:z(m()).optional(),bearer_methods_supported:z(m()).optional(),resource_signing_alg_values_supported:z(m()).optional(),resource_name:m().optional(),resource_documentation:m().optional(),resource_policy_uri:m().url().optional(),resource_tos_uri:m().url().optional(),tls_client_certificate_bound_access_tokens:ee().optional(),authorization_details_types_supported:z(m()).optional(),dpop_signing_alg_values_supported:z(m()).optional(),dpop_bound_access_tokens_required:ee().optional()}),lg=me({issuer:m(),authorization_endpoint:ze,token_endpoint:ze,registration_endpoint:ze.optional(),scopes_supported:z(m()).optional(),response_types_supported:z(m()),response_modes_supported:z(m()).optional(),grant_types_supported:z(m()).optional(),token_endpoint_auth_methods_supported:z(m()).optional(),token_endpoint_auth_signing_alg_values_supported:z(m()).optional(),service_documentation:ze.optional(),revocation_endpoint:ze.optional(),revocation_endpoint_auth_methods_supported:z(m()).optional(),revocation_endpoint_auth_signing_alg_values_supported:z(m()).optional(),introspection_endpoint:m().optional(),introspection_endpoint_auth_methods_supported:z(m()).optional(),introspection_endpoint_auth_signing_alg_values_supported:z(m()).optional(),code_challenge_methods_supported:z(m()).optional(),client_id_metadata_document_supported:ee().optional()}),MR=me({issuer:m(),authorization_endpoint:ze,token_endpoint:ze,userinfo_endpoint:ze.optional(),jwks_uri:ze,registration_endpoint:ze.optional(),scopes_supported:z(m()).optional(),response_types_supported:z(m()),response_modes_supported:z(m()).optional(),grant_types_supported:z(m()).optional(),acr_values_supported:z(m()).optional(),subject_types_supported:z(m()),id_token_signing_alg_values_supported:z(m()),id_token_encryption_alg_values_supported:z(m()).optional(),id_token_encryption_enc_values_supported:z(m()).optional(),userinfo_signing_alg_values_supported:z(m()).optional(),userinfo_encryption_alg_values_supported:z(m()).optional(),userinfo_encryption_enc_values_supported:z(m()).optional(),request_object_signing_alg_values_supported:z(m()).optional(),request_object_encryption_alg_values_supported:z(m()).optional(),request_object_encryption_enc_values_supported:z(m()).optional(),token_endpoint_auth_methods_supported:z(m()).optional(),token_endpoint_auth_signing_alg_values_supported:z(m()).optional(),display_values_supported:z(m()).optional(),claim_types_supported:z(m()).optional(),claims_supported:z(m()).optional(),service_documentation:m().optional(),claims_locales_supported:z(m()).optional(),ui_locales_supported:z(m()).optional(),claims_parameter_supported:ee().optional(),request_parameter_supported:ee().optional(),request_uri_parameter_supported:ee().optional(),require_request_uri_registration:ee().optional(),op_policy_uri:ze.optional(),op_tos_uri:ze.optional(),client_id_metadata_document_supported:ee().optional()}),tw=P({...MR.shape,...lg.pick({code_challenge_methods_supported:!0}).shape}),rw=P({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:So.number().optional(),scope:m().optional(),refresh_token:m().optional(),issuer:m().optional().catch(void 0)}).strip(),nw=P({error:m(),error_description:m().optional(),error_uri:m().optional()}),Qx=ze.optional().or(N("").transform(()=>{})),FR=P({redirect_uris:z(ze),token_endpoint_auth_method:m().optional(),grant_types:z(m()).optional(),response_types:z(m()).optional(),client_name:m().optional(),client_uri:ze.optional(),logo_uri:Qx,scope:m().optional(),contacts:z(m()).optional(),tos_uri:Qx,policy_uri:m().optional(),jwks_uri:ze.optional(),jwks:ms().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),VR=P({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional(),issuer:m().optional().catch(void 0)}).strip(),ow=FR.merge(VR),eq=P({error:m(),error_description:m().optional()}).strip(),tq=P({token:m(),token_type_hint:m().optional()}).strip();function iw(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function aw({requestedResource:e,configuredResource:t}){let n=typeof e=="string"?new URL(e):new URL(e.href),o=typeof t=="string"?new URL(t):new URL(t.href);if(n.origin!==o.origin||n.pathname.length<o.pathname.length)return!1;let r=n.pathname.endsWith("/")?n.pathname:n.pathname+"/",i=o.pathname.endsWith("/")?o.pathname:o.pathname+"/";return r.startsWith(i)}var ge=class extends Error{constructor(t,n){super(t),this.errorUri=n,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},bi=class extends ge{};bi.errorCode="invalid_request";var Ir=class extends ge{};Ir.errorCode="invalid_client";var Pr=class extends ge{};Pr.errorCode="invalid_grant";var Tr=class extends ge{};Tr.errorCode="unauthorized_client";var xi=class extends ge{};xi.errorCode="unsupported_grant_type";var wi=class extends ge{};wi.errorCode="invalid_scope";var ki=class extends ge{};ki.errorCode="access_denied";var Et=class extends ge{};Et.errorCode="server_error";var Si=class extends ge{};Si.errorCode="temporarily_unavailable";var zi=class extends ge{};zi.errorCode="unsupported_response_type";var Ii=class extends ge{};Ii.errorCode="unsupported_token_type";var Pi=class extends ge{};Pi.errorCode="invalid_token";var Ti=class extends ge{};Ti.errorCode="method_not_allowed";var Ei=class extends ge{};Ei.errorCode="too_many_requests";var Er=class extends ge{};Er.errorCode="invalid_client_metadata";var Oi=class extends ge{};Oi.errorCode="insufficient_scope";var ji=class extends ge{};ji.errorCode="invalid_target";var sw={[bi.errorCode]:bi,[Ir.errorCode]:Ir,[Pr.errorCode]:Pr,[Tr.errorCode]:Tr,[xi.errorCode]:xi,[wi.errorCode]:wi,[ki.errorCode]:ki,[Et.errorCode]:Et,[Si.errorCode]:Si,[zi.errorCode]:zi,[Ii.errorCode]:Ii,[Pi.errorCode]:Pi,[Ti.errorCode]:Ti,[Ei.errorCode]:Ei,[Er.errorCode]:Er,[Oi.errorCode]:Oi,[ji.errorCode]:ji};var Ot=class extends Error{constructor(t){super(t??"Unauthorized")}};function JR(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var dg="code",pg="S256";function KR(e,t){let n=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&JR(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?"client_secret_basic":"none":n&&t.includes("client_secret_basic")?"client_secret_basic":n&&t.includes("client_secret_post")?"client_secret_post":t.includes("none")?"none":n?"client_secret_post":"none"}function HR(e,t,n,o){let{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":GR(r,i,n);return;case"client_secret_post":WR(r,i,o);return;case"none":BR(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function GR(e,t,n){if(!t)throw new Error("client_secret_basic authentication requires a client_secret");let o=btoa(`${e}:${t}`);n.set("Authorization",`Basic ${o}`)}function WR(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function BR(e,t){t.set("client_id",e)}async function uw(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let o=nw.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=sw[r]||Et;return new s(i||"",a)}catch(o){let r=e instanceof Response?Tc(e,e.url):void 0,i=`${t?`HTTP ${t}: `:""}${r??`Invalid OAuth error response: ${o}. Raw body: ${n}`}`;return new Et(i)}}function XR(e,t){let[n,o]=[e,t];try{[n,o]=[new URL(e).href,new URL(t).href]}catch{}return n===o||n.endsWith("/")&&n.slice(0,-1)===o||o.endsWith("/")&&o.slice(0,-1)===n}function hg(e,t){if(e)return typeof e.issuer!="string"?e.issuer==null?e:{...e,issuer:void 0}:XR(e.issuer,t)?e:void 0}var YR=rw.omit({issuer:!0}),QR=ow.omit({issuer:!0});function lw(e,t){return new Error(`OAuth client information is bound to authorization server ${e.issuer} and is not presented to ${t}. Clear the stored client information, or correct \`expectedIssuer\`, if the authorization server has moved.`)}async function Ri(e,t){try{return await fg(e,t)}catch(n){if(n instanceof Ir||n instanceof Tr)return await e.invalidateCredentials?.("all"),await fg(e,t);if(n instanceof Pr)return await e.invalidateCredentials?.("tokens"),await fg(e,t);throw n}}async function fg(e,{serverUrl:t,authorizationCode:n,scope:o,resourceMetadataUrl:r,fetchFn:i}){let a=await e.discoveryState?.(),s,c,u,l=r;if(!l&&a?.resourceMetadataUrl&&(l=new URL(a.resourceMetadataUrl)),a?.authorizationServerUrl){if(c=a.authorizationServerUrl,s=a.resourceMetadata,u=a.authorizationServerMetadata??await pw(c,{fetchFn:i}),!s)try{s=await dw(t,{resourceMetadataUrl:l},i)}catch{}(u!==a.authorizationServerMetadata||s!==a.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}else{let G=await aN(t,{resourceMetadataUrl:l,fetchFn:i});c=G.authorizationServerUrl,u=G.authorizationServerMetadata,s=G.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}let d=String(c),f=await tN(t,e,s),p=f&&s&&!e.validateResourceURL?s.resource:f,h=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,v=await Promise.resolve(e.clientInformation()),y=hg(v,d),k=e.saveClientInformation!==void 0&&!!e.redirectUrl;if(v&&!y&&!k)throw lw(v,d);let E=y?.issuer==null?y:void 0,j=async()=>{try{E&&await e.saveClientInformation?.({...E,issuer:d})}catch{}};if(!y){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let G=u?.client_id_metadata_document_supported===!0,ve=e.clientMetadataUrl;if(ve&&!eN(ve))throw new Er(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${ve}`);if(G&&ve)y={client_id:ve,issuer:d},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");y={...await dN(c,{metadata:u,clientMetadata:e.clientMetadata,scope:h,fetchFn:i}),issuer:d},await e.saveClientInformation(y)}}let U=!e.redirectUrl;if(n!==void 0||U){let G=await lN(e,c,{metadata:u,resource:p,authorizationCode:n,fetchFn:i});return await j(),await e.saveTokens({...G,issuer:d}),"AUTHORIZED"}let $=hg(await e.tokens(),d);if($?.refresh_token&&$.issuer==null&&console.warn("[mcp-sdk] stored OAuth tokens have no 'issuer' property (saved by an earlier version, or by a provider that does not keep it) and are used as-is; make sure your OAuthClientProvider stores what saveTokens() and saveClientInformation() receive unchanged."),$?.refresh_token)try{let G=await uN(c,{metadata:u,clientInformation:y,refreshToken:$.refresh_token,resource:p,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await j(),await e.saveTokens({...G,issuer:d}),"AUTHORIZED"}catch(G){if(!(!(G instanceof ge)||G instanceof Et))throw G}let I=e.state?await e.state():void 0,{authorizationUrl:A,codeVerifier:le}=await sN(c,{metadata:u,clientInformation:y,state:I,redirectUrl:e.redirectUrl,scope:h,resource:p});return await e.saveCodeVerifier(le),await e.redirectToAuthorization(A),"REDIRECT"}function eN(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function tN(e,t,n){let o=iw(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!aw({requestedResource:o,configuredResource:n.resource}))throw new Error(`Protected resource ${n.resource} does not match expected ${o} (or origin)`);return new URL(n.resource)}}function gg(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[n,o]=t.split(" ");if(n.toLowerCase()!=="bearer"||!o)return{};let r=mg(e,"resource_metadata")||void 0,i;if(r)try{i=new URL(r)}catch{}let a=mg(e,"scope")||void 0,s=mg(e,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function mg(e,t){let n=e.headers.get("WWW-Authenticate");if(!n)return null;let o=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),r=n.match(o);return r?r[1]||r[2]:null}async function dw(e,t,n=fetch){let o=await oN(e,"oauth-protected-resource",n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!o||o.status===404)throw await o?.body?.cancel(),new Error("Resource server does not implement OAuth 2.0 Protected Resource Metadata.");if(!o.ok)throw await o.body?.cancel(),new Error(`HTTP ${o.status} trying to load well-known OAuth protected resource metadata.`);return ew.parse(await o.json())}async function vg(e,t,n=fetch){try{return await zr(n)(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?vg(e,void 0,n):void 0;throw o}}function rN(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function cw(e,t,n=fetch){return await vg(e,{"MCP-Protocol-Version":t},n)}function nN(e,t){return!e||!e.ok&&e.status<500&&t!=="/"}async function oN(e,t,n,o){let r=new URL(e),i=o?.protocolVersion??Vt,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let c=rN(t,r.pathname);a=new URL(c,o?.metadataServerUrl??r),a.search=r.search}let s=await cw(a,i,n);if(!o?.metadataUrl&&nN(s,r.pathname)){let c=new URL(`/.well-known/${t}`,r);s=await cw(c,i,n)}return s}function iN(e){let t=typeof e=="string"?new URL(e):e,n=t.pathname!=="/",o=[];if(!n)return o.push({url:new URL("/.well-known/oauth-authorization-server",t.origin),type:"oauth"}),o.push({url:new URL("/.well-known/openid-configuration",t.origin),type:"oidc"}),o;let r=t.pathname;return r.endsWith("/")&&(r=r.slice(0,-1)),o.push({url:new URL(`/.well-known/oauth-authorization-server${r}`,t.origin),type:"oauth"}),o.push({url:new URL(`/.well-known/openid-configuration${r}`,t.origin),type:"oidc"}),o.push({url:new URL(`${r}/.well-known/openid-configuration`,t.origin),type:"oidc"}),o}async function pw(e,{fetchFn:t=fetch,protocolVersion:n=Vt}={}){let o={"MCP-Protocol-Version":n,Accept:"application/json"},r=iN(e);for(let{url:i,type:a}of r){let s=await vg(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?lg.parse(await s.json()):tw.parse(await s.json())}}}async function aN(e,t){let n,o;try{n=await dw(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(o=n.authorization_servers[0])}catch{}o||(o=String(new URL("/",e)));let r=await pw(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:r,resourceMetadata:n}}function fw(e){return typeof e=="string"?e:e.href}async function sN(e,{metadata:t,clientInformation:n,redirectUrl:o,scope:r,state:i,resource:a}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(dg))throw new Error(`Incompatible auth server: does not support response type ${dg}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(pg))throw new Error(`Incompatible auth server: does not support code challenge method ${pg}`)}else s=new URL("/authorize",e);let c=await ug(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",dg),s.searchParams.set("client_id",n.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",pg),s.searchParams.set("redirect_uri",String(o)),i&&s.searchParams.set("state",i),r&&s.searchParams.set("scope",r),r?.includes("offline_access")&&s.searchParams.append("prompt","consent"),a&&s.searchParams.set("resource",fw(a)),{authorizationUrl:s,codeVerifier:u}}function cN(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}async function mw(e,{metadata:t,tokenRequestParams:n,clientInformation:o,addClientAuthentication:r,resource:i,fetchFn:a}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL("/token",e),c=new Headers({"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"});if(i&&n.set("resource",fw(i)),r)await r(c,n,s,t);else if(o){let l=t?.token_endpoint_auth_methods_supported??[],d=KR(o,l);HR(d,o,c,n)}let u=await zr(a??fetch)(s,{method:"POST",headers:c,body:n});if(!u.ok)throw await uw(u);return YR.parse(await u.json())}async function uN(e,{metadata:t,clientInformation:n,refreshToken:o,resource:r,addClientAuthentication:i,fetchFn:a}){let s=new URLSearchParams({grant_type:"refresh_token",refresh_token:o}),c=await mw(e,{metadata:t,tokenRequestParams:s,clientInformation:n,addClientAuthentication:i,resource:r,fetchFn:a});return{refresh_token:o,...c}}async function lN(e,t,{metadata:n,resource:o,authorizationCode:r,fetchFn:i}={}){let a=async()=>{let l=await e.clientInformation(),d=hg(l,String(t));if(l&&!d)throw lw(l,String(t));return d},s=await a(),c=e.clientMetadata.scope,u;if(e.prepareTokenRequest&&(u=await e.prepareTokenRequest(c)),!u){if(!r)throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");if(!e.redirectUrl)throw new Error("redirectUrl is required for authorization_code flow");let l=await e.codeVerifier();u=cN(r,l,e.redirectUrl)}return s??(s=await a()),mw(t,{metadata:n,tokenRequestParams:u,clientInformation:s,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function dN(e,{metadata:t,clientMetadata:n,scope:o,fetchFn:r}){let i;if(t){if(!t.registration_endpoint)throw new Error("Incompatible auth server: does not support dynamic client registration");i=new URL(t.registration_endpoint)}else i=new URL("/register",e);let a=await zr(r??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await uw(a);return QR.parse(await a.json())}var Ni=class extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}},hw=10,pN=13,Or=32;function _g(e){}function _w(e){if(typeof e=="function")throw new TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=_g,onError:n=_g,onRetry:o=_g,onComment:r,maxBufferSize:i}=e,a=[],s=0,c=!0,u,l="",d=0,f,p=!1;function h($){if(p)throw new Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,$.charCodeAt(0)===239&&$.charCodeAt(1)===187&&$.charCodeAt(2)===191&&($=$.slice(3))),a.length===0){let le=y($);le!==""&&(a.push(le),s=le.length),v();return}if($.indexOf(`
81
81
  `)===-1&&$.indexOf("\r")===-1){a.push($),s+=$.length,v();return}a.push($);let I=a.join("");a.length=0,s=0;let A=y(I);A!==""&&(a.push(A),s=A.length),v()}function v(){i!==void 0&&(s+l.length<=i||(p=!0,a.length=0,s=0,u=void 0,l="",d=0,f=void 0,n(new Ni(`Buffered data exceeded max buffer size of ${i} characters`,{type:"max-buffer-size-exceeded"}))))}function y($){let I=0;if($.indexOf("\r")===-1){let A=$.indexOf(`
82
82
  `,I);for(;A!==-1;){if(I===A){d>0&&t({id:u,event:f,data:l}),u=void 0,l="",d=0,f=void 0,I=A+1,A=$.indexOf(`
83
83
  `,I);continue}let le=$.charCodeAt(I);if(gw($,I,le)){let G=$.charCodeAt(I+5)===Or?I+6:I+5,ve=$.slice(G,A);if(d===0&&$.charCodeAt(A+1)===hw){t({id:u,event:f,data:ve}),u=void 0,l="",f=void 0,I=A+2,A=$.indexOf(`
package/dist/index.d.ts CHANGED
@@ -1,5 +1,24 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ /** Raw deterministic metrics for one repo tree (the BASE checkout). */
4
+ interface RepoComplexityMetrics {
5
+ metric_version: string;
6
+ source_files: number;
7
+ code_files: number;
8
+ source_loc: number;
9
+ oversize_skipped_files: number;
10
+ language_count: number;
11
+ languages: string[];
12
+ max_dir_depth: number;
13
+ dependency_count: number;
14
+ package_json_count: number;
15
+ build_configs: string[];
16
+ build_config_count: number;
17
+ test_files: number;
18
+ has_tests: boolean;
19
+ monorepo: boolean;
20
+ }
21
+
3
22
  declare const RESUME_ACTIONS: readonly ["continue", "wrap_up"];
4
23
  type ResumeAction = (typeof RESUME_ACTIONS)[number];
5
24
 
@@ -117,6 +136,7 @@ type RunnerConfig = {
117
136
  assetMap?: Record<string, string[]>;
118
137
  cache?: NativeSessionCacheConfig;
119
138
  pendingUndeployedChanges?: boolean;
139
+ repoComplexity?: RepoComplexityMetrics;
120
140
  } & ({
121
141
  mode: Exclude<RunnerMode, 'redeploy'>;
122
142
  prompt: string;