@netlify/agent-runner-cli 1.176.0-context-err-logs.0 → 1.176.0-has-db-from-site.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.
- package/dist/bin-local.js +179 -179
- package/dist/bin.js +194 -194
- package/dist/connections-mcp-server.js +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.js +154 -154
- package/package.json +1 -1
|
@@ -75,7 +75,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
75
75
|
`}var hc=class{constructor(t=yx.stdin,n=yx.stdout){this._stdin=t,this._stdout=n,this._readBuffer=new mc,this._started=!1,this._ondata=o=>{this._readBuffer.append(o),this.processReadBuffer()},this._onerror=o=>{this.onerror?.(o)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(t){return new Promise(n=>{let o=_x(t);this._stdout.write(o)?n():this._stdout.once("drain",n)})}};import{createReadStream as RZ}from"fs";import{request as UZ}from"http";import{request as CZ}from"https";import{pipeline as ZZ}from"stream/promises";import hi from"process";import jj from"process";var $x=e=>Object.entries(e).filter(([,t])=>t!=null&&t!=="").map(([t,n])=>{let o=String(n);if(!/[\s"=]/.test(o))return`${t}=${o}`;let r=o.replace(/([\\"])/g,"\\$1").replace(/\r/g,"\\r").replace(/\n/g,"\\n");return`${t}="${r}"`}).join(" ");import{AsyncLocalStorage as Ej}from"async_hooks";var Oj=new Ej;var bx=()=>Oj.getStore();var xx;var li=()=>xx?`-[session:${xx}]`:"",di=()=>jj.env.LOG!=="0",wx=e=>{let t=bx();if(!t)return e;let n=$x({...t});return n?[...e,n]:e};function gc(e){return{log:(...t)=>{di()&&console.log(`[AR]-[${e}]${li()}`,...t)},error:(...t)=>{di()&&console.error(`[AR]-[ERROR]-[${e}]${li()}`,...wx(t))},warn:(...t)=>{di()&&console.warn(`[AR]-[WARN]-[${e}]${li()}`,...wx(t))},info:(...t)=>{di()&&console.info(`[AR]-[${e}]${li()}`,...t)},debug:(...t)=>{di()&&console.debug(`[AR]-[DEBUG]-[${e}]${li()}`,...t)}}}import{AsyncLocalStorage as Rj}from"async_hooks";import Nj from"dgram";import Nn from"process";var Uj="buildbot.agent_runner.",Dj=8125,Cj=e=>{let t=Object.keys(e);return t.length===0?"":"|#"+t.map(n=>`${n}:${e[n]}`).join(",")},pi=(e,t,n,o={})=>`${Uj}${e}:${t}|${n}${Cj(o)}`,Aj={service:"buildbot"},Zj={},qj=new Rj;var fi=e=>({...Zj,...qj.getStore()??{},...e,...Aj}),Lj=(e,t)=>{let n=!1,o=Nj.createSocket("udp4");return o.unref(),o.once("error",r=>{if(!n){let i=r.code??r.message;Nn.stderr.write(`[metrics] UDP error: ${i}
|
|
76
76
|
`),n=!0}}),r=>{n||o.send(r,t,e,i=>{if(i&&!n){let a=i.code??i.message;Nn.stderr.write(`[metrics] UDP send to ${e}:${t} failed: ${a}
|
|
77
77
|
`),n=!0}})}},Fh=()=>{},Mj=()=>!!Nn.env.VITEST;var Fj=()=>{if(Mj())return Fh;let e=Nn.env.HOST_NODE_IP;if(!e)return Fh;let t=Nn.env.DD_AGENT_PORT,n=t===void 0?Dj:Number(t);return!Number.isInteger(n)||n<=0||n>65535?(Nn.stderr.write(`[metrics] DD_AGENT_PORT="${t}" is not a valid port; metrics disabled
|
|
78
|
-
`),Fh):Lj(e,n)},Vj=(e=Fj())=>({inc(t,n=1,o={}){e(pi(t,n,"c",fi(o)))},gauge(t,n,o={}){e(pi(t,n,"g",fi(o)))},histogram(t,n,o={}){e(pi(t,n,"h",fi(o)))},timing(t,n,o={}){e(pi(t,n,"ms",fi(o)))},distribution(t,n,o={}){e(pi(t,n,"d",fi(o)))}}),kx=Vj();import{spawn as fZ}from"child_process";import{existsSync as hZ,mkdirSync as gZ,writeFileSync as vZ}from"fs";import{connect as yZ}from"net";import Jj from"path";import xZ from"process";var kZ=gc("step-preview"),SZ=Jj.join("apps","netlify-react-ui","public","agent-run-preview.json"),Kj=9001,Hj="components-agentrunners-rendersteps--live",zZ=`http://localhost:${Kj}/?path=/story/${Hj}`;var mi=class extends Error{constructor(n,o,r,i=!1){super(n);this.statusCode=o;this.userMessage=r;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}};var Vh=hi.env.NETLIFY_API_URL,Jh=hi.env.NETLIFY_API_TOKEN,Un=gc("api"),Gj=()=>hi.env.NETLIFY_LOCAL_MODE==="true",Wj=async(e,t={})=>{if(!Vh||!Jh)throw new Error("No API URL or token");let n=new URL(e,Vh),o={...t,headers:{...t.headers,Authorization:`Bearer ${Jh}`}};hi.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=await fetch(n,o),i=r.ok&&r.status<=299,a=t.expectStatuses?.includes(r.status)??!1;if(hi.env.AGENT_RUNNERS_DEBUG==="true")Un.log(`Response headers for ${n}:`),r.headers.forEach((c,u)=>{Un.log(` ${u}: ${c}`)});else{let c=r.headers.get("x-request-id")||r.headers.get("x-nf-request-id");Un.log(`Request ID for ${n}: ${c||"N/A"}`)}if(!i&&!a&&(Un.error(`Got status ${r.status} for request ${n}`),kx.inc("api.request_failed",1,{status:r.status})),t.raw){if(!i)throw new Error(`API request failed: ${r.status} ${r.statusText}`);return r}let s=await(r.headers.get("content-type")?.includes("application/json")?r.json():r.text());if(!i){let c=typeof s=="string"?s:JSON.stringify(s);throw r.status===404?new mi(`API request failed: 404 - ${c}`,404,"The site associated with this agent run no longer exists."):r.status===503&&t.gracefulOn503&&c.toLowerCase().includes("usage exceeded")?new mi(`API request failed: 503 - ${c}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${r.status} - ${c}`)}return s},Sx=e=>{Un.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Vh=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Jh=e.constants.NETLIFY_API_TOKEN)};var zx=async(e,t)=>Gj()?(Un.log("Mock API: getAgentConnectionTokens called",{runnerId:e,sessionId:t}),{connections:[]}):Wj(`/api/v1/agent_runners/${e}/sessions/${t}/connections/tokens`,{method:"POST"});var Ix=["user","project","team"],Kh=(e="project")=>{let t=Ix.indexOf(e);return t===-1?Ix.length:t};var Bj={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.")},Hh=xt.object(Bj),Px="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 PR from"process";var vc=class{constructor(t){this._client=t}async*callToolStream(t,n=Ht,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 U(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 U(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof U){yield{type:"error",error:l};return}yield{type:"error",error:new U(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 _c(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&&_c(i,n[r])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!="boolean"&&_c(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!="boolean"&&_c(n,t)}}function Xj(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 yc=class extends mn{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 Rn,n?.listChanged&&(this._pendingListChangedConfig=n.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mf,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Zf,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",jf,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new vc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ts(this._capabilities,t)}setRequestHandler(t,n){let r=tn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i;if(Ft(r)){let s=r;i=s._zod?.def?.value??s.value}else{let s=r;i=s._def?.value??s.value}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=Ne(Jf,c);if(!l.success){let j=l.error instanceof Error?l.error.message:String(l.error);throw new U(C.InvalidParams,`Invalid elicitation request: ${j}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=Xj(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new U(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new U(C.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(n(c,u));if(d.task){let j=Ne(kt,g);if(!j.success){let T=j.error instanceof Error?j.error.message:String(j.error);throw new U(C.InvalidParams,`Invalid task creation result: ${T}`)}return j.data}let _=Ne(Gt,g);if(!_.success){let j=_.error instanceof Error?_.error.message:String(_.error);throw new U(C.InvalidParams,`Invalid elicitation result: ${j}`)}let y=_.data,S=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{_c(S,y.content)}catch{}return y};return super.setRequestHandler(t,s)}if(a==="sampling/createMessage"){let s=async(c,u)=>{let l=Ne(Vf,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new U(C.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let y=Ne(kt,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new U(C.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let g=d.tools||d.toolChoice?Ro:mr,_=Ne(g,p);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new U(C.InvalidParams,`Invalid sampling result: ${y}`)}return _.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:Jt,capabilities:this._capabilities,clientInfo:this._clientInfo}},zf,n);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!gs.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){dc(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&pc(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},Kf,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},Af,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},Rf,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Pf,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Tf,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},Of,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=Ht,o){if(this.isToolTaskRequired(t.name))throw new U(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 U(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 U(C.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof U?a:new U(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},Lf,n);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(t,n,o,r){let i=ky.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 p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(s){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(u,s);this._listChangedDebounceTimers.set(t,p)}else u()};this.setNotificationHandler(n,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function $c(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Tx(e=fetch,t){return t?async(n,o)=>{let r={...t,...o,headers:o?.headers?{...$c(t.headers),...$c(o.headers)}:t.headers};return e(n,r)}:e}var Gh;Gh=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(e=>e.webcrypto);async function Yj(e){return(await Gh).getRandomValues(new Uint8Array(e))}async function Qj(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let r=await Yj(e-o.length);for(let i of r)i<n&&(o+=t[i%t.length])}return o}async function eR(e){return await Qj(e)}async function tR(e){let t=await(await Gh).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Wh(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await eR(e),n=await tR(t);return{code_verifier:t,code_challenge:n}}var Se=Ka().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:$f.custom,message:"URL must be parseable",fatal:!0}),An}).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"}),Ox=me({resource:m().url(),authorization_servers:z(Se).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:Q().optional(),authorization_details_types_supported:z(m()).optional(),dpop_signing_alg_values_supported:z(m()).optional(),dpop_bound_access_tokens_required:Q().optional()}),Bh=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,registration_endpoint:Se.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:Se.optional(),revocation_endpoint:Se.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:Q().optional()}),rR=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,userinfo_endpoint:Se.optional(),jwks_uri:Se,registration_endpoint:Se.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:Q().optional(),request_parameter_supported:Q().optional(),request_uri_parameter_supported:Q().optional(),require_request_uri_registration:Q().optional(),op_policy_uri:Se.optional(),op_tos_uri:Se.optional(),client_id_metadata_document_supported:Q().optional()}),jx=P({...rR.shape,...Bh.pick({code_challenge_methods_supported:!0}).shape}),Rx=P({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:xo.number().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Nx=P({error:m(),error_description:m().optional(),error_uri:m().optional()}),Ex=Se.optional().or(N("").transform(()=>{})),nR=P({redirect_uris:z(Se),token_endpoint_auth_method:m().optional(),grant_types:z(m()).optional(),response_types:z(m()).optional(),client_name:m().optional(),client_uri:Se.optional(),logo_uri:Ex,scope:m().optional(),contacts:z(m()).optional(),tos_uri:Ex,policy_uri:m().optional(),jwks_uri:Se.optional(),jwks:us().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),oR=P({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional()}).strip(),Ux=nR.merge(oR),aq=P({error:m(),error_description:m().optional()}).strip(),sq=P({token:m(),token_type_hint:m().optional()}).strip();function Dx(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Cx({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}},gi=class extends ge{};gi.errorCode="invalid_request";var zr=class extends ge{};zr.errorCode="invalid_client";var Ir=class extends ge{};Ir.errorCode="invalid_grant";var Pr=class extends ge{};Pr.errorCode="unauthorized_client";var vi=class extends ge{};vi.errorCode="unsupported_grant_type";var _i=class extends ge{};_i.errorCode="invalid_scope";var yi=class extends ge{};yi.errorCode="access_denied";var Et=class extends ge{};Et.errorCode="server_error";var $i=class extends ge{};$i.errorCode="temporarily_unavailable";var bi=class extends ge{};bi.errorCode="unsupported_response_type";var xi=class extends ge{};xi.errorCode="unsupported_token_type";var wi=class extends ge{};wi.errorCode="invalid_token";var ki=class extends ge{};ki.errorCode="method_not_allowed";var Si=class extends ge{};Si.errorCode="too_many_requests";var Tr=class extends ge{};Tr.errorCode="invalid_client_metadata";var zi=class extends ge{};zi.errorCode="insufficient_scope";var Ii=class extends ge{};Ii.errorCode="invalid_target";var Ax={[gi.errorCode]:gi,[zr.errorCode]:zr,[Ir.errorCode]:Ir,[Pr.errorCode]:Pr,[vi.errorCode]:vi,[_i.errorCode]:_i,[yi.errorCode]:yi,[Et.errorCode]:Et,[$i.errorCode]:$i,[bi.errorCode]:bi,[xi.errorCode]:xi,[wi.errorCode]:wi,[ki.errorCode]:ki,[Si.errorCode]:Si,[Tr.errorCode]:Tr,[zi.errorCode]:zi,[Ii.errorCode]:Ii};var Ot=class extends Error{constructor(t){super(t??"Unauthorized")}};function iR(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Xh="code",Yh="S256";function aR(e,t){let n=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&iR(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 sR(e,t,n,o){let{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":cR(r,i,n);return;case"client_secret_post":uR(r,i,o);return;case"none":lR(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function cR(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 uR(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function lR(e,t){t.set("client_id",e)}async function qx(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let o=Nx.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=Ax[r]||Et;return new s(i||"",a)}catch(o){let r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new Et(r)}}async function Pi(e,t){try{return await Qh(e,t)}catch(n){if(n instanceof zr||n instanceof Pr)return await e.invalidateCredentials?.("all"),await Qh(e,t);if(n instanceof Ir)return await e.invalidateCredentials?.("tokens"),await Qh(e,t);throw n}}async function Qh(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 Mx(c,{fetchFn:i}),!s)try{s=await Lx(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 T=await vR(t,{resourceMetadataUrl:l,fetchFn:i});c=T.authorizationServerUrl,u=T.authorizationServerMetadata,s=T.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}let d=await pR(t,e,s),p=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let T=u?.client_id_metadata_document_supported===!0,R=e.clientMetadataUrl;if(R&&!dR(R))throw new Tr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${R}`);if(T&&R)f={client_id:R},await e.saveClientInformation?.(f);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let I=await xR(c,{metadata:u,clientMetadata:e.clientMetadata,scope:p,fetchFn:i});await e.saveClientInformation(I),f=I}}let g=!e.redirectUrl;if(n!==void 0||g){let T=await bR(e,c,{metadata:u,resource:d,authorizationCode:n,fetchFn:i});return await e.saveTokens(T),"AUTHORIZED"}let _=await e.tokens();if(_?.refresh_token)try{let T=await $R(c,{metadata:u,clientInformation:f,refreshToken:_.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof ge)||T instanceof Et))throw T}let y=e.state?await e.state():void 0,{authorizationUrl:S,codeVerifier:j}=await _R(c,{metadata:u,clientInformation:f,state:y,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(S),"REDIRECT"}function dR(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function pR(e,t,n){let o=Dx(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!Cx({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 tg(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[n,o]=t.split(" ");if(n.toLowerCase()!=="bearer"||!o)return{};let r=eg(e,"resource_metadata")||void 0,i;if(r)try{i=new URL(r)}catch{}let a=eg(e,"scope")||void 0,s=eg(e,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function eg(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 Lx(e,t,n=fetch){let o=await hR(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 Ox.parse(await o.json())}async function rg(e,t,n=fetch){try{return await n(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rg(e,void 0,n):void 0;throw o}}function fR(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Zx(e,t,n=fetch){return await rg(e,{"MCP-Protocol-Version":t},n)}function mR(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function hR(e,t,n,o){let r=new URL(e),i=o?.protocolVersion??Jt,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let c=fR(t,r.pathname);a=new URL(c,o?.metadataServerUrl??r),a.search=r.search}let s=await Zx(a,i,n);if(!o?.metadataUrl&&mR(s,r.pathname)){let c=new URL(`/.well-known/${t}`,r);s=await Zx(c,i,n)}return s}function gR(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 Mx(e,{fetchFn:t=fetch,protocolVersion:n=Jt}={}){let o={"MCP-Protocol-Version":n,Accept:"application/json"},r=gR(e);for(let{url:i,type:a}of r){let s=await rg(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Bh.parse(await s.json()):jx.parse(await s.json())}}}async function vR(e,t){let n,o;try{n=await Lx(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 Mx(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:r,resourceMetadata:n}}async function _R(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(Xh))throw new Error(`Incompatible auth server: does not support response type ${Xh}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Yh))throw new Error(`Incompatible auth server: does not support code challenge method ${Yh}`)}else s=new URL("/authorize",e);let c=await Wh(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",Xh),s.searchParams.set("client_id",n.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",Yh),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",a.href),{authorizationUrl:s,codeVerifier:u}}function yR(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}async function Fx(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",i.href),r)await r(c,n,s,t);else if(o){let l=t?.token_endpoint_auth_methods_supported??[],d=aR(o,l);sR(d,o,c,n)}let u=await(a??fetch)(s,{method:"POST",headers:c,body:n});if(!u.ok)throw await qx(u);return Rx.parse(await u.json())}async function $R(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 Fx(e,{metadata:t,tokenRequestParams:s,clientInformation:n,addClientAuthentication:i,resource:r,fetchFn:a});return{refresh_token:o,...c}}async function bR(e,t,{metadata:n,resource:o,authorizationCode:r,fetchFn:i}={}){let a=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(a)),!s){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 u=await e.codeVerifier();s=yR(r,u,e.redirectUrl)}let c=await e.clientInformation();return Fx(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function xR(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(r??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await qx(a);return Ux.parse(await a.json())}var Ti=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}},Vx=10,wR=13,Er=32;function ng(e){}function Hx(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=ng,onError:n=ng,onRetry:o=ng,onComment:r,maxBufferSize:i}=e,a=[],s=0,c=!0,u,l="",d=0,p,f=!1;function g($){if(f)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 de=y($);de!==""&&(a.push(de),s=de.length),_();return}if($.indexOf(`
|
|
78
|
+
`),Fh):Lj(e,n)},Vj=(e=Fj())=>({inc(t,n=1,o={}){e(pi(t,n,"c",fi(o)))},gauge(t,n,o={}){e(pi(t,n,"g",fi(o)))},histogram(t,n,o={}){e(pi(t,n,"h",fi(o)))},timing(t,n,o={}){e(pi(t,n,"ms",fi(o)))},distribution(t,n,o={}){e(pi(t,n,"d",fi(o)))}}),kx=Vj();import{spawn as fZ}from"child_process";import{existsSync as hZ,mkdirSync as gZ,writeFileSync as vZ}from"fs";import{connect as yZ}from"net";import Jj from"path";import xZ from"process";var kZ=gc("step-preview"),SZ=Jj.join("apps","netlify-react-ui","public","agent-run-preview.json"),Kj=9001,Hj="components-agentrunners-rendersteps--live",zZ=`http://localhost:${Kj}/?path=/story/${Hj}`;var mi=class extends Error{constructor(n,o,r,i=!1){super(n);this.statusCode=o;this.userMessage=r;this.isCreditLimitExceeded=i;this.name="GracefulShutdownError"}};var Vh=hi.env.NETLIFY_API_URL,Jh=hi.env.NETLIFY_API_TOKEN,Un=gc("api"),Gj=()=>hi.env.NETLIFY_LOCAL_MODE==="true",Wj=async(e,t={})=>{if(!Vh||!Jh)throw new Error("No API URL or token");let n=new URL(e,Vh),o={...t,headers:{...t.headers,Authorization:`Bearer ${Jh}`}};hi.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=await fetch(n,o),i=r.ok&&r.status<=299;if(hi.env.AGENT_RUNNERS_DEBUG==="true")Un.log(`Response headers for ${n}:`),r.headers.forEach((s,c)=>{Un.log(` ${c}: ${s}`)});else{let s=r.headers.get("x-request-id")||r.headers.get("x-nf-request-id");Un.log(`Request ID for ${n}: ${s||"N/A"}`)}if(i||(Un.error(`Got status ${r.status} for request ${n}`),kx.inc("api.request_failed",1,{status:r.status})),t.raw){if(!i)throw new Error(`API request failed: ${r.status} ${r.statusText}`);return r}let a=await(r.headers.get("content-type")?.includes("application/json")?r.json():r.text());if(!i){let s=typeof a=="string"?a:JSON.stringify(a);throw r.status===404?new mi(`API request failed: 404 - ${s}`,404,"The site associated with this agent run no longer exists."):r.status===503&&t.gracefulOn503&&s.toLowerCase().includes("usage exceeded")?new mi(`API request failed: 503 - ${s}`,503,"Credit limit reached. Please add more credits to continue using Agent Runners.",!0):new Error(`API request failed: ${r.status} - ${s}`)}return a},Sx=e=>{Un.log("Setting details for api",{apiUrl:e?.constants?.NETLIFY_API_HOST,token:!!e?.constants?.NETLIFY_API_TOKEN}),e?.constants?.NETLIFY_API_HOST&&(Vh=`https://${e.constants.NETLIFY_API_HOST}`),e?.constants?.NETLIFY_API_TOKEN&&(Jh=e.constants.NETLIFY_API_TOKEN)};var zx=async(e,t)=>Gj()?(Un.log("Mock API: getAgentConnectionTokens called",{runnerId:e,sessionId:t}),{connections:[]}):Wj(`/api/v1/agent_runners/${e}/sessions/${t}/connections/tokens`,{method:"POST"});var Ix=["user","project","team"],Kh=(e="project")=>{let t=Ix.indexOf(e);return t===-1?Ix.length:t};var Bj={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.")},Hh=xt.object(Bj),Px="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 PR from"process";var vc=class{constructor(t){this._client=t}async*callToolStream(t,n=Ht,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 U(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 U(C.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof U){yield{type:"error",error:l};return}yield{type:"error",error:new U(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 _c(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&&_c(i,n[r])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!="boolean"&&_c(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!="boolean"&&_c(n,t)}}function Xj(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 yc=class extends mn{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 Rn,n?.listChanged&&(this._pendingListChangedConfig=n.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",Mf,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",Zf,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",jf,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new vc(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Ts(this._capabilities,t)}setRequestHandler(t,n){let r=tn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let i;if(Ft(r)){let s=r;i=s._zod?.def?.value??s.value}else{let s=r;i=s._def?.value??s.value}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=Ne(Jf,c);if(!l.success){let j=l.error instanceof Error?l.error.message:String(l.error);throw new U(C.InvalidParams,`Invalid elicitation request: ${j}`)}let{params:d}=l.data;d.mode=d.mode??"form";let{supportsFormMode:p,supportsUrlMode:f}=Xj(this._capabilities.elicitation);if(d.mode==="form"&&!p)throw new U(C.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!f)throw new U(C.InvalidParams,"Client does not support URL-mode elicitation requests");let g=await Promise.resolve(n(c,u));if(d.task){let j=Ne(kt,g);if(!j.success){let T=j.error instanceof Error?j.error.message:String(j.error);throw new U(C.InvalidParams,`Invalid task creation result: ${T}`)}return j.data}let _=Ne(Gt,g);if(!_.success){let j=_.error instanceof Error?_.error.message:String(_.error);throw new U(C.InvalidParams,`Invalid elicitation result: ${j}`)}let y=_.data,S=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&y.action==="accept"&&y.content&&S&&this._capabilities.elicitation?.form?.applyDefaults)try{_c(S,y.content)}catch{}return y};return super.setRequestHandler(t,s)}if(a==="sampling/createMessage"){let s=async(c,u)=>{let l=Ne(Vf,c);if(!l.success){let y=l.error instanceof Error?l.error.message:String(l.error);throw new U(C.InvalidParams,`Invalid sampling request: ${y}`)}let{params:d}=l.data,p=await Promise.resolve(n(c,u));if(d.task){let y=Ne(kt,p);if(!y.success){let S=y.error instanceof Error?y.error.message:String(y.error);throw new U(C.InvalidParams,`Invalid task creation result: ${S}`)}return y.data}let g=d.tools||d.toolChoice?Ro:mr,_=Ne(g,p);if(!_.success){let y=_.error instanceof Error?_.error.message:String(_.error);throw new U(C.InvalidParams,`Invalid sampling result: ${y}`)}return _.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:Jt,capabilities:this._capabilities,clientInfo:this._clientInfo}},zf,n);if(o===void 0)throw new Error(`Server sent invalid initialize result: ${o}`);if(!gs.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){dc(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&pc(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},Kf,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},Af,n)}async listPrompts(t,n){return this.request({method:"prompts/list",params:t},Rf,n)}async listResources(t,n){return this.request({method:"resources/list",params:t},Pf,n)}async listResourceTemplates(t,n){return this.request({method:"resources/templates/list",params:t},Tf,n)}async readResource(t,n){return this.request({method:"resources/read",params:t},Of,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=Ht,o){if(this.isToolTaskRequired(t.name))throw new U(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 U(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 U(C.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof U?a:new U(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},Lf,n);return this.cacheToolMetadata(o.tools),o}_setupListChangedHandler(t,n,o,r){let i=ky.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 p=d instanceof Error?d:new Error(String(d));c(p,null)}},l=()=>{if(s){let d=this._listChangedDebounceTimers.get(t);d&&clearTimeout(d);let p=setTimeout(u,s);this._listChangedDebounceTimers.set(t,p)}else u()};this.setNotificationHandler(n,l)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};function $c(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Tx(e=fetch,t){return t?async(n,o)=>{let r={...t,...o,headers:o?.headers?{...$c(t.headers),...$c(o.headers)}:t.headers};return e(n,r)}:e}var Gh;Gh=globalThis.crypto?.webcrypto??globalThis.crypto??import("crypto").then(e=>e.webcrypto);async function Yj(e){return(await Gh).getRandomValues(new Uint8Array(e))}async function Qj(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",n=Math.pow(2,8)-Math.pow(2,8)%t.length,o="";for(;o.length<e;){let r=await Yj(e-o.length);for(let i of r)i<n&&(o+=t[i%t.length])}return o}async function eR(e){return await Qj(e)}async function tR(e){let t=await(await Gh).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}async function Wh(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await eR(e),n=await tR(t);return{code_verifier:t,code_challenge:n}}var Se=Ka().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:$f.custom,message:"URL must be parseable",fatal:!0}),An}).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"}),Ox=me({resource:m().url(),authorization_servers:z(Se).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:Q().optional(),authorization_details_types_supported:z(m()).optional(),dpop_signing_alg_values_supported:z(m()).optional(),dpop_bound_access_tokens_required:Q().optional()}),Bh=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,registration_endpoint:Se.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:Se.optional(),revocation_endpoint:Se.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:Q().optional()}),rR=me({issuer:m(),authorization_endpoint:Se,token_endpoint:Se,userinfo_endpoint:Se.optional(),jwks_uri:Se,registration_endpoint:Se.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:Q().optional(),request_parameter_supported:Q().optional(),request_uri_parameter_supported:Q().optional(),require_request_uri_registration:Q().optional(),op_policy_uri:Se.optional(),op_tos_uri:Se.optional(),client_id_metadata_document_supported:Q().optional()}),jx=P({...rR.shape,...Bh.pick({code_challenge_methods_supported:!0}).shape}),Rx=P({access_token:m(),id_token:m().optional(),token_type:m(),expires_in:xo.number().optional(),scope:m().optional(),refresh_token:m().optional()}).strip(),Nx=P({error:m(),error_description:m().optional(),error_uri:m().optional()}),Ex=Se.optional().or(N("").transform(()=>{})),nR=P({redirect_uris:z(Se),token_endpoint_auth_method:m().optional(),grant_types:z(m()).optional(),response_types:z(m()).optional(),client_name:m().optional(),client_uri:Se.optional(),logo_uri:Ex,scope:m().optional(),contacts:z(m()).optional(),tos_uri:Ex,policy_uri:m().optional(),jwks_uri:Se.optional(),jwks:us().optional(),software_id:m().optional(),software_version:m().optional(),software_statement:m().optional()}).strip(),oR=P({client_id:m(),client_secret:m().optional(),client_id_issued_at:H().optional(),client_secret_expires_at:H().optional()}).strip(),Ux=nR.merge(oR),aq=P({error:m(),error_description:m().optional()}).strip(),sq=P({token:m(),token_type_hint:m().optional()}).strip();function Dx(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}function Cx({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}},gi=class extends ge{};gi.errorCode="invalid_request";var zr=class extends ge{};zr.errorCode="invalid_client";var Ir=class extends ge{};Ir.errorCode="invalid_grant";var Pr=class extends ge{};Pr.errorCode="unauthorized_client";var vi=class extends ge{};vi.errorCode="unsupported_grant_type";var _i=class extends ge{};_i.errorCode="invalid_scope";var yi=class extends ge{};yi.errorCode="access_denied";var Et=class extends ge{};Et.errorCode="server_error";var $i=class extends ge{};$i.errorCode="temporarily_unavailable";var bi=class extends ge{};bi.errorCode="unsupported_response_type";var xi=class extends ge{};xi.errorCode="unsupported_token_type";var wi=class extends ge{};wi.errorCode="invalid_token";var ki=class extends ge{};ki.errorCode="method_not_allowed";var Si=class extends ge{};Si.errorCode="too_many_requests";var Tr=class extends ge{};Tr.errorCode="invalid_client_metadata";var zi=class extends ge{};zi.errorCode="insufficient_scope";var Ii=class extends ge{};Ii.errorCode="invalid_target";var Ax={[gi.errorCode]:gi,[zr.errorCode]:zr,[Ir.errorCode]:Ir,[Pr.errorCode]:Pr,[vi.errorCode]:vi,[_i.errorCode]:_i,[yi.errorCode]:yi,[Et.errorCode]:Et,[$i.errorCode]:$i,[bi.errorCode]:bi,[xi.errorCode]:xi,[wi.errorCode]:wi,[ki.errorCode]:ki,[Si.errorCode]:Si,[Tr.errorCode]:Tr,[zi.errorCode]:zi,[Ii.errorCode]:Ii};var Ot=class extends Error{constructor(t){super(t??"Unauthorized")}};function iR(e){return["client_secret_basic","client_secret_post","none"].includes(e)}var Xh="code",Yh="S256";function aR(e,t){let n=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&iR(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 sR(e,t,n,o){let{client_id:r,client_secret:i}=t;switch(e){case"client_secret_basic":cR(r,i,n);return;case"client_secret_post":uR(r,i,o);return;case"none":lR(r,o);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}function cR(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 uR(e,t,n){n.set("client_id",e),t&&n.set("client_secret",t)}function lR(e,t){t.set("client_id",e)}async function qx(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let o=Nx.parse(JSON.parse(n)),{error:r,error_description:i,error_uri:a}=o,s=Ax[r]||Et;return new s(i||"",a)}catch(o){let r=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${o}. Raw body: ${n}`;return new Et(r)}}async function Pi(e,t){try{return await Qh(e,t)}catch(n){if(n instanceof zr||n instanceof Pr)return await e.invalidateCredentials?.("all"),await Qh(e,t);if(n instanceof Ir)return await e.invalidateCredentials?.("tokens"),await Qh(e,t);throw n}}async function Qh(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 Mx(c,{fetchFn:i}),!s)try{s=await Lx(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 T=await vR(t,{resourceMetadataUrl:l,fetchFn:i});c=T.authorizationServerUrl,u=T.authorizationServerMetadata,s=T.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(c),resourceMetadataUrl:l?.toString(),resourceMetadata:s,authorizationServerMetadata:u})}let d=await pR(t,e,s),p=o||s?.scopes_supported?.join(" ")||e.clientMetadata.scope,f=await Promise.resolve(e.clientInformation());if(!f){if(n!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let T=u?.client_id_metadata_document_supported===!0,R=e.clientMetadataUrl;if(R&&!dR(R))throw new Tr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${R}`);if(T&&R)f={client_id:R},await e.saveClientInformation?.(f);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let I=await xR(c,{metadata:u,clientMetadata:e.clientMetadata,scope:p,fetchFn:i});await e.saveClientInformation(I),f=I}}let g=!e.redirectUrl;if(n!==void 0||g){let T=await bR(e,c,{metadata:u,resource:d,authorizationCode:n,fetchFn:i});return await e.saveTokens(T),"AUTHORIZED"}let _=await e.tokens();if(_?.refresh_token)try{let T=await $R(c,{metadata:u,clientInformation:f,refreshToken:_.refresh_token,resource:d,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(T),"AUTHORIZED"}catch(T){if(!(!(T instanceof ge)||T instanceof Et))throw T}let y=e.state?await e.state():void 0,{authorizationUrl:S,codeVerifier:j}=await _R(c,{metadata:u,clientInformation:f,state:y,redirectUrl:e.redirectUrl,scope:p,resource:d});return await e.saveCodeVerifier(j),await e.redirectToAuthorization(S),"REDIRECT"}function dR(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}async function pR(e,t,n){let o=Dx(e);if(t.validateResourceURL)return await t.validateResourceURL(o,n?.resource);if(n){if(!Cx({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 tg(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[n,o]=t.split(" ");if(n.toLowerCase()!=="bearer"||!o)return{};let r=eg(e,"resource_metadata")||void 0,i;if(r)try{i=new URL(r)}catch{}let a=eg(e,"scope")||void 0,s=eg(e,"error")||void 0;return{resourceMetadataUrl:i,scope:a,error:s}}function eg(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 Lx(e,t,n=fetch){let o=await hR(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 Ox.parse(await o.json())}async function rg(e,t,n=fetch){try{return await n(e,{headers:t})}catch(o){if(o instanceof TypeError)return t?rg(e,void 0,n):void 0;throw o}}function fR(e,t="",n={}){return t.endsWith("/")&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function Zx(e,t,n=fetch){return await rg(e,{"MCP-Protocol-Version":t},n)}function mR(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}async function hR(e,t,n,o){let r=new URL(e),i=o?.protocolVersion??Jt,a;if(o?.metadataUrl)a=new URL(o.metadataUrl);else{let c=fR(t,r.pathname);a=new URL(c,o?.metadataServerUrl??r),a.search=r.search}let s=await Zx(a,i,n);if(!o?.metadataUrl&&mR(s,r.pathname)){let c=new URL(`/.well-known/${t}`,r);s=await Zx(c,i,n)}return s}function gR(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 Mx(e,{fetchFn:t=fetch,protocolVersion:n=Jt}={}){let o={"MCP-Protocol-Version":n,Accept:"application/json"},r=gR(e);for(let{url:i,type:a}of r){let s=await rg(i,o,t);if(s){if(!s.ok){if(await s.body?.cancel(),s.status>=400&&s.status<500)continue;throw new Error(`HTTP ${s.status} trying to load ${a==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return a==="oauth"?Bh.parse(await s.json()):jx.parse(await s.json())}}}async function vR(e,t){let n,o;try{n=await Lx(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 Mx(o,{fetchFn:t?.fetchFn});return{authorizationServerUrl:o,authorizationServerMetadata:r,resourceMetadata:n}}async function _R(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(Xh))throw new Error(`Incompatible auth server: does not support response type ${Xh}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Yh))throw new Error(`Incompatible auth server: does not support code challenge method ${Yh}`)}else s=new URL("/authorize",e);let c=await Wh(),u=c.code_verifier,l=c.code_challenge;return s.searchParams.set("response_type",Xh),s.searchParams.set("client_id",n.client_id),s.searchParams.set("code_challenge",l),s.searchParams.set("code_challenge_method",Yh),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",a.href),{authorizationUrl:s,codeVerifier:u}}function yR(e,t,n){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(n)})}async function Fx(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",i.href),r)await r(c,n,s,t);else if(o){let l=t?.token_endpoint_auth_methods_supported??[],d=aR(o,l);sR(d,o,c,n)}let u=await(a??fetch)(s,{method:"POST",headers:c,body:n});if(!u.ok)throw await qx(u);return Rx.parse(await u.json())}async function $R(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 Fx(e,{metadata:t,tokenRequestParams:s,clientInformation:n,addClientAuthentication:i,resource:r,fetchFn:a});return{refresh_token:o,...c}}async function bR(e,t,{metadata:n,resource:o,authorizationCode:r,fetchFn:i}={}){let a=e.clientMetadata.scope,s;if(e.prepareTokenRequest&&(s=await e.prepareTokenRequest(a)),!s){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 u=await e.codeVerifier();s=yR(r,u,e.redirectUrl)}let c=await e.clientInformation();return Fx(t,{metadata:n,tokenRequestParams:s,clientInformation:c??void 0,addClientAuthentication:e.addClientAuthentication,resource:o,fetchFn:i})}async function xR(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(r??fetch)(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,...o!==void 0?{scope:o}:{}})});if(!a.ok)throw await qx(a);return Ux.parse(await a.json())}var Ti=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}},Vx=10,wR=13,Er=32;function ng(e){}function Hx(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=ng,onError:n=ng,onRetry:o=ng,onComment:r,maxBufferSize:i}=e,a=[],s=0,c=!0,u,l="",d=0,p,f=!1;function g($){if(f)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 de=y($);de!==""&&(a.push(de),s=de.length),_();return}if($.indexOf(`
|
|
79
79
|
`)===-1&&$.indexOf("\r")===-1){a.push($),s+=$.length,_();return}a.push($);let I=a.join("");a.length=0,s=0;let A=y(I);A!==""&&(a.push(A),s=A.length),_()}function _(){i!==void 0&&(s+l.length<=i||(f=!0,a.length=0,s=0,u=void 0,l="",d=0,p=void 0,n(new Ti(`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(`
|
|
80
80
|
`,I);for(;A!==-1;){if(I===A){d>0&&t({id:u,event:p,data:l}),u=void 0,l="",d=0,p=void 0,I=A+1,A=$.indexOf(`
|
|
81
81
|
`,I);continue}let de=$.charCodeAt(I);if(Jx($,I,de)){let fe=$.charCodeAt(I+5)===Er?I+6:I+5,Ce=$.slice(fe,A);if(d===0&&$.charCodeAt(A+1)===Vx){t({id:u,event:p,data:Ce}),u=void 0,l="",p=void 0,I=A+2,A=$.indexOf(`
|
package/dist/index.d.ts
CHANGED
|
@@ -68,6 +68,7 @@ type RunnerConfig = {
|
|
|
68
68
|
});
|
|
69
69
|
type Site = {
|
|
70
70
|
id: string;
|
|
71
|
+
has_database?: boolean;
|
|
71
72
|
published_deploy?: {
|
|
72
73
|
id: string;
|
|
73
74
|
};
|
|
@@ -119,6 +120,6 @@ interface PipelineOptions {
|
|
|
119
120
|
traceparent?: string;
|
|
120
121
|
};
|
|
121
122
|
}
|
|
122
|
-
declare const runPipeline: (
|
|
123
|
+
declare const runPipeline: (options: PipelineOptions) => Promise<void>;
|
|
123
124
|
|
|
124
125
|
export { type Context, type PipelineOptions, runPipeline };
|