nimblebrain 0.9.0-beta.1 → 0.9.0-beta.2

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.
@@ -1,48 +1,48 @@
1
1
  #!/usr/bin/env node
2
- var S=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Et(e,t,n={}){let{apiError:r}=n;if(r==="authentication_failed"||!r&&yw.test(t))return new Ne("signed_out",_w[e]);if(r==="rate_limit"||r==="billing_error"||zw.test(t))return new Ne("plan_limit",xw(e,t));return new Ne("cli_failed",Sw(e,t,n))}function zc(e){return new Ne("cli_missing",bw[e])}function xw(e,t){let n=e==="claude"?"Your Claude plan":"Your ChatGPT plan",r=kw(t);return`${n} has reached its usage limit${r?` (${r})`:""}. Send your message again once it resets, or run \`npx nimblebrain use api\` in a terminal to use an API key instead.`}function kw(e){let t=e.match(/limit reached\|(\d{10})\b/i)?.[1];if(t)return`it resets ${new Date(Number(t)*1000).toLocaleString()}`;let n=e.match(/\bresets?\s+((?:at\s+)?[^·\n.!]{1,60})/i)?.[1]?.trim();if(n)return`it resets ${n}`;let r=e.match(/try again (in|at) ([^\n.!]{1,60})/i);return r?`try again ${r[1]} ${r[2]?.trim()}`:void 0}function Sw(e,t,n){let r=n.exitCode===void 0?"stopped":`exited (${n.exitCode??"signal"})`,o=vw(t),i=n.log?`Check ${n.log}`:"Check the agent worker's log";return`${ww[e]} ${r} without finishing the turn${o?`: ${o}`:""}. ${i} for more, then send your message again.`}function vw(e){let t=e.split(`
3
- `).map((n)=>n.trim()).filter(Boolean).pop()??"";return $w(t).slice(0,240)}function $w(e){return e.replace(/\b(bearer|basic)\s+[^\s,;]+/gi,"$1 [redacted]").replace(/\b[A-Z][A-Z0-9_]*(KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*=\S+/g,"$1=[redacted]").replace(/\b(sk|sess|rt|pk)-[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{10,}(\.[A-Za-z0-9_-]+)*/g,"[redacted]")}var yc="nimblebrain-subscription/failure",Ne,ww,_w,bw,yw,zw;var Yt=S(()=>{Ne=class Ne extends Error{code;constructor(e,t){super(t);this.code=e}};ww={claude:"Claude Code",codex:"Codex"},_w={claude:"Claude Code is signed out. Run `claude /login` in a terminal, then send your message again.",codex:"Codex is signed out. Run `codex login` in a terminal and choose Sign in with ChatGPT, then send your message again."},bw={claude:"Claude Code is not installed where the agent worker looks for it. Install it (https://claude.com/claude-code), sign in, then run `npx nimblebrain use claude` and send your message again.",codex:"Codex is not installed where the agent worker looks for it. Install it with `npm i -g @openai/codex`, run `codex login`, then run `npx nimblebrain use codex` and send your message again."},yw=/not logged in|please run \/login|\/login|oauth token|token (has )?expired|invalid api key|authentication_failed|\b401\b|unauthorized|codex login|refresh token/i,zw=/usage limit|limit reached|hit your limit|limit will reset|rate_limit_exceeded/i});function Ge(e=process.env){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0&&!Bo.includes(n))t[n]=r;return t}function Kn(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}}function Jn(e,t){let n=new Promise((r,o)=>{e.once("error",(i)=>o(i.code==="ENOENT"?zc(t):Et(t,`could not be started: ${i.message}`)))});return n.catch(()=>{}),n}var Q,Bo;var It=S(()=>{Yt();Q=class Q extends Error{reason;constructor(e,t){super(t);this.reason=e}};Bo=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","OPENAI_API_KEY","CODEX_API_KEY"]});import{spawn as xc}from"node:child_process";import{mkdtemp as Ew,rm as Iw}from"node:fs/promises";import{tmpdir as Cw}from"node:os";import{join as Tw}from"node:path";import{createInterface as Aw}from"node:readline";function kc(e={}){let t=e.bin??"claude";return{id:"claude-code",label:"Claude Code",takesSystemPrompt:!0,toolsAreNimbleBrainOnly:!0,preflight:()=>Rw(t),run:(n)=>Nw(t,e.model,n,e.log)}}async function Rw(e){return qo(await qw(e,Vo).catch(()=>{return}))}function qo(e){if(e===void 0)throw new Q("not_installed","Claude Code is not installed. Install it from https://claude.com/claude-code, then run `claude` and sign in.");let t;try{t=JSON.parse(e)}catch{throw new Q("unreadable","Could not read `claude auth status`. Update Claude Code.")}if(!t.loggedIn)throw new Q("not_signed_in","Claude Code is not signed in. Run `claude` and sign in with your Claude account.");if(t.authMethod!=="claude.ai"||!t.subscriptionType)throw new Q("api_key",`Claude Code is signed in with ${t.authMethod??"an API key"}, which bills API pricing. Run \`claude /login\` and choose your Claude subscription.`);let n=t.subscriptionType.charAt(0).toUpperCase()+t.subscriptionType.slice(1);return{describe:`your Claude ${n} subscription (claude.ai login, no API key)`,plan:`Claude ${n}`}}function Ow(e,t){let n={mcpServers:{[Fo]:{type:"http",url:e.mcpUrl}}};return["-p","--output-format","stream-json","--verbose","--include-partial-messages","--mcp-config",JSON.stringify(n),"--strict-mcp-config","--tools","","--allowedTools",`mcp__${Fo}`,"--setting-sources","","--disable-slash-commands","--no-session-persistence",...e.system?["--system-prompt",e.system]:[],...t?["--model",t]:[]]}async function Nw(e,t,n,r){let o=await Ew(Tw(Cw(),"nb-claude-")),i=xc(e,Ow(n,t),{cwd:o,env:Ge(),stdio:["pipe","pipe","pipe"]}),s=()=>i.kill("SIGTERM");n.signal.addEventListener("abort",s,{once:!0}),i.stdin.end(n.prompt);let a="";i.stderr.on("data",(g)=>{a=(a+g.toString()).slice(-4000)});let l=new Promise((g)=>i.on("close",g)),d=Jn(i,"claude"),f=jw(n.emit);try{let g=await Promise.race([Pw(i.stdout,f,s),d]),w=await Promise.race([l,d]);if(g)throw new Ne("api_key",g);if(n.signal.aborted)return{stopReason:"cancelled",...f.totals()};return{stopReason:Dw(f.result(),f.apiError(),{code:w,stderr:a,log:r}),...f.totals()}}finally{n.signal.removeEventListener("abort",s),await Iw(o,{recursive:!0,force:!0})}}async function Pw(e,t,n){for await(let r of Aw({input:e})){let o=Lw(r);if(!o)continue;let i=Mw(o);if(i)return n(),i;t(o)}return}function Lw(e){if(!e.trim())return;try{return JSON.parse(e)}catch{return}}function Dw(e,t,n){if(!e||e.is_error&&e.subtype==="success"){let r=`${n.stderr}
4
- ${e?.result??""}`;throw Et("claude",r,{apiError:t,exitCode:n.code,log:n.log})}return e.subtype==="error_max_turns"?"max_turn_requests":"end_turn"}function Mw(e){if(e.type!=="system"||e.subtype!=="init")return;if(e.apiKeySource==="none"||e.apiKeySource===void 0)return;return`Claude Code would bill an API key (source: ${e.apiKeySource}) instead of your subscription. Remove that key, or run \`claude /login\`.`}function jw(e){let t,n;return Object.assign((o)=>{if(o.type==="stream_event")Uw(o,e);else if(o.type==="assistant"){if(typeof o.error==="string")n=o.error;Zw(o,e)}else if(o.type==="user")Bw(o,e);else if(o.type==="result")t=o},{result:()=>t,apiError:()=>n,totals:()=>Fw(t)})}function Uw(e,t){let n=e.event?.type==="content_block_delta"?e.event.delta:void 0;if(n?.type==="text_delta"&&n.text)t({sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.text}});else if(n?.type==="thinking_delta"&&n.thinking)t({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.thinking}})}function Zw(e,t){for(let n of e.message?.content??[]){if(n.type!=="tool_use"||!n.id)continue;t({sessionUpdate:"tool_call",toolCallId:n.id,title:Vw(n.name??"tool"),kind:"other",status:"in_progress",rawInput:n.input})}}function Bw(e,t){for(let n of e.message?.content??[]){if(n.type!=="tool_result"||!n.tool_use_id)continue;t({sessionUpdate:"tool_call_update",toolCallId:n.tool_use_id,status:n.is_error?"failed":"completed"})}}function Fw(e){let t=Object.entries(e?.modelUsage??{}).map(([o,i])=>({model:`claude-code-subscription:${o}`,purpose:"turn",usage:{inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,cacheReadTokens:i.cacheReadInputTokens??0,cacheWriteTokens:i.cacheCreationInputTokens??0}})),n=e?.usage;return{usage:n?{inputTokens:n.input_tokens??0,outputTokens:n.output_tokens??0,cacheReadTokens:n.cache_read_input_tokens??0,cacheWriteTokens:n.cache_creation_input_tokens??0}:Kn(),calls:t}}function Vw(e){let t=`mcp__${Fo}__`;return e.startsWith(t)?e.slice(t.length):e}function qw(e,t){return new Promise((n,r)=>{let o=xc(e,t,{env:Ge(),stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(s)=>{i+=s.toString()}),o.on("error",r),o.on("close",()=>n(i))})}var Fo="nimblebrain",Vo;var Ho=S(()=>{Yt();It();Vo=["auth","status","--json"]});import{spawn as Sc}from"node:child_process";import{mkdtemp as Hw,rm as Gw}from"node:fs/promises";import{tmpdir as Ww}from"node:os";import{join as Kw}from"node:path";import{createInterface as Jw}from"node:readline";function vc(e={}){let t=e.bin??"codex";return{id:"codex",label:"Codex",takesSystemPrompt:!1,toolsAreNimbleBrainOnly:!1,preflight:()=>Xw(t),run:(n)=>Qw(t,e.model,n,e.log)}}async function Xw(e){return Wo(await o_(e,Go).catch(()=>{return}))}function Wo(e){if(e===void 0)throw new Q("not_installed","Codex is not installed. Install it (`npm i -g @openai/codex`), then run `codex login`.");if(/chatgpt/i.test(e))return{describe:"your ChatGPT plan (Sign in with ChatGPT, no API key)",plan:"ChatGPT"};if(/api key/i.test(e))throw new Q("api_key","Codex is signed in with an API key, which bills API pricing. Run `codex logout`, then `codex login` and choose Sign in with ChatGPT.");throw new Q("not_signed_in","Codex is not signed in. Run `codex login` and choose Sign in with ChatGPT.")}async function Qw(e,t,n,r){let o=await Hw(Kw(Ww(),"nb-codex-")),i=["exec","--json","--skip-git-repo-check","--ephemeral","--ignore-user-config","--sandbox","read-only","-C",o,"-c",'approval_policy="never"',"-c",`mcp_servers.${Yw}.url=${JSON.stringify(n.mcpUrl)}`,...t?["-m",t]:[],"-"],s=Sc(e,i,{cwd:o,env:Ge(),stdio:["pipe","pipe","pipe"]}),a=()=>s.kill("SIGTERM");n.signal.addEventListener("abort",a,{once:!0}),s.stdin.end(n.prompt);let l="";s.stderr.on("data",(w)=>{l=(l+w.toString()).slice(-4000)});let d=new Promise((w)=>s.on("close",w)),f=Jn(s,"codex"),g=t_(n.emit);try{await Promise.race([e_(s.stdout,g),f]);let w=await Promise.race([d,f]);if(n.signal.aborted)return{stopReason:"cancelled",...g.totals()};if(g.completed())return{stopReason:"end_turn",...g.totals()};let b=`${l}
5
- ${g.failure()??""}`;throw Et("codex",b,{exitCode:w,log:r})}finally{n.signal.removeEventListener("abort",a),await Gw(o,{recursive:!0,force:!0})}}async function e_(e,t){for await(let n of Jw({input:e})){if(!n.trim())continue;try{t(JSON.parse(n))}catch{}}}function t_(e){let t=Kn(),n=!1,r;return Object.assign((i)=>{switch(i.type){case"item.started":if($c(i.item))Ec(i.item,"in_progress",e);return;case"item.completed":if(i.item)n_(i.item,e);return;case"turn.completed":t=r_(i.usage),n=!0;return;case"turn.failed":case"error":r=i.error?.message??i.message??r;return}},{completed:()=>n,failure:()=>r,totals:()=>({usage:t,calls:[{model:"codex-subscription:codex",purpose:"turn",usage:t}]})})}function Ec(e,t,n){if(!e.id)return;if(t!=="in_progress"){n({sessionUpdate:"tool_call_update",toolCallId:e.id,status:t});return}let r=e.type==="command_execution";n({sessionUpdate:"tool_call",toolCallId:e.id,title:r?`shell: ${e.command??""}`:e.tool??"tool",kind:r?"execute":"other",status:t,rawInput:e.arguments})}function n_(e,t){if(e.type==="agent_message"&&e.text)t({sessionUpdate:"agent_message_chunk",content:{type:"text",text:e.text}});else if(e.type==="reasoning"&&e.text)t({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e.text}});else if($c(e))Ec(e,e.status==="failed"?"failed":"completed",t)}function r_(e={}){return{inputTokens:e.input_tokens??0,outputTokens:e.output_tokens??0,cacheReadTokens:e.cached_input_tokens??0,cacheWriteTokens:0,reasoningTokens:e.reasoning_output_tokens??0}}function o_(e,t){return new Promise((n,r)=>{let o=Sc(e,t,{env:Ge(),stdio:["ignore","pipe","pipe"]}),i="",s=(a)=>{i+=a.toString()};o.stdout.on("data",s),o.stderr.on("data",s),o.on("error",r),o.on("close",()=>n(i))})}var Yw="nimblebrain",Go,$c=(e)=>e?.type==="mcp_tool_call"||e?.type==="command_execution";var Ko=S(()=>{Yt();It();Go=["login","status"]});var it="__agent-worker",Ct,Yn;var Tt=S(()=>{Ct={"claude-code":27290,codex:27291},Yn={"claude-code":"only your NimbleBrain workspace's tools",codex:"your NimbleBrain workspace's tools, plus Codex's read-only shell (it has no off switch)"}});function Lt(e){process.stderr.write(`[${new Date().toISOString().slice(11,19)}] ${e}
6
- `)}var k,O,_i,bi=1;var sn=S(()=>{k={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_archive:"session/archive",session_unarchive:"session/unarchive",session_status:"session/status",session_set_title:"session/set_title",session_resume:"session/resume",session_close:"session/close",logout:"logout",auth_status:"auth/status"},O={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_message:"mcp/message",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete",auth_status_update:"auth/status_update"},_i={cancel_request:"$/cancel_request"}});function Iu(e,t,n){if(e!=="session/close"&&e!=="session/delete")return t;return t.catch((r)=>{if(r instanceof T&&r.code===-32002)return n();throw r})}function pt(e){return yi(e)&&"id"in e&&typeof e.method==="string"&&zi(e.id)}function ft(e){if(!yi(e)||"method"in e)return!1;if(!("id"in e)||!zi(e.id))return!1;let t=Object.hasOwn(e,"result"),n=Object.hasOwn(e,"error");if(t===n)return!1;return!n||Ob(e.error)}function mt(e){return yi(e)&&!("id"in e)&&typeof e.method==="string"}function ee(e){return typeof e==="object"&&e!==null}function yi(e){return ee(e)&&e.jsonrpc==="2.0"}function zi(e){return e===null||typeof e==="string"||typeof e==="number"&&Number.isFinite(e)}function an(e){return ee(e)&&!("method"in e)&&(("id"in e)||("result"in e)||("error"in e))}function Rb(e){if(!ee(e)||!zi(e.requestId))return;return e.requestId}function Ob(e){return ee(e)&&typeof e.code==="number"&&Number.isInteger(e.code)&&typeof e.message==="string"}function gr(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function Nb(e){if(e instanceof Error)return e.message;if(typeof e==="object"&&e!=null&&"message"in e&&typeof e.message==="string")return e.message;return}function Pb(e){return typeof e==="object"&&e!==null&&"name"in e&&e.name==="ZodError"&&"issues"in e&&Array.isArray(e.issues)&&"format"in e&&typeof e.format==="function"}function Eu(e){if(Array.isArray(e))return{type:"array"};if(ee(e))return{type:"object",keys:Object.keys(e)};return{type:e===null?"null":typeof e}}function Cu(e){if(e instanceof T)return e.toResult();if(Pb(e))return T.invalidParams(e.format()).toResult();let t=Nb(e);try{return T.internalError(t?JSON.parse(t):{}).toResult()}catch{return T.internalError({details:t}).toResult()}}function Tu(e){if(e instanceof T&&e.code===-32800)return e;return T.requestCancelled(e)}function Lb(e,t){let n=Db(e,t);return n?n.toResult():Cu(e)}function Db(e,t){if(!t.aborted||!Mb(e))return;return Tu(t.reason)}function Mb(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.name==="AbortError"||t.code==="ABORT_ERR"}class wr{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof T?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){if(this.didRespond)return gr(Error("JSON-RPC request already responded"));return this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()})}}class Au{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}}class _r{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;fallbackHandlers=[];stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Au(this);receiveReader;constructor(e,t,n,r){if(typeof e==="function"){let a=e,l=t,d=n;this.initialize(d,[...r?.handlers??[],this.legacyHandler(a,l)],r);return}let o=e,i=t,s=n;this.initialize(o,[...s?.handlers??[],...i],s)}static builder(){return new Ru}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch((n)=>this.close(n));return new cn(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return gr(this.closedReason());let o=this.prepareRequest(e,t,n,r);if(this.sendMessage(o.message).catch(()=>{}),r.cancellationSignal?.aborted)o.cancel();return o.response}sendCancelRequest(e){return this.sendNotification("$/cancel_request",{requestId:e})}sendNotification(e,t){if(this.abortController.signal.aborted)return gr(this.closedReason());return this.sendMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,n,r={}){let o=this.nextRequestId++,i=()=>{},s=new Promise((a,l)=>{let d={resolve:(f)=>{try{a(n?n(f):f)}catch(g){l(g)}},reject:l};i=()=>{if(d.cancellationSent)return;if(d.cancellationSent=!0,d.cleanup?.(),this.sendCancelRequest(o).catch(()=>{}),r.stopWaitingOnCancel)d.abandoned=!0,l(Tu(r.cancellationSignal?.reason))},r.cancellationSignal?.addEventListener("abort",i,{once:!0}),d.cleanup=()=>{r.cancellationSignal?.removeEventListener("abort",i)},this.pendingResponses.set(o,d)});return s.catch(()=>{}),{message:{jsonrpc:"2.0",id:o,method:e,params:t},response:s,cancel:()=>i()}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error("ACP connection closed");this.abortController.abort(t);for(let n of this.pendingResponses.values())n.cleanup?.(),n.reject(t);this.pendingResponses.clear();for(let n of this.incomingRequests.values())n.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,n){this.stream=e,this.staticHandlers=t,this.fallbackHandlers=[...n?.fallbackHandlers??[]],this.closedPromise=new Promise((r)=>{this.abortController.signal.addEventListener("abort",()=>r())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind==="request"){let o=await e(n.method,n.params,r);await n.responder.respond(o)}else await t(n.method,n.params,r);return K.yes()}}}async receive(){let e=void 0;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{while(!this.abortController.signal.aborted){let{value:n,done:r}=await t.read();if(this.abortController.signal.aborted)break;if(r)break;this.receiveUnvalidatedMessage(n)}}finally{if(this.receiveReader===t)this.receiveReader=void 0;t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveUnvalidatedMessage(e){if(Array.isArray(e)){this.sendMessage(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported"))).catch(()=>{});return}if(!pt(e)&&!mt(e)&&!an(e)){this.sendMessage(Se(T.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveMessage(e){if(this.abortController.signal.aborted)return Promise.resolve();if(!ee(e))return console.error("Invalid message",Eu(e)),Promise.resolve();if("method"in e){if(!("id"in e))this.handleProtocolNotification(e);return this.processIncomingMessage(this.toIncomingMessage(e)).catch((t)=>this.close(t))}else if("id"in e)this.handleResponse(e);else console.error("Invalid message",Eu(e));return Promise.resolve()}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let r of[...this.staticHandlers,...this.dynamicHandlers.values(),...this.fallbackHandlers]){if(this.abortController.signal.aborted)return;let o=await r.handleMessage(t,this.context)??{handled:!0};if(o.handled)return;t=o.message??t,n=n||Boolean(o.retry)}if(n)this.retryQueue.push(t);else if(t.kind==="request")await t.responder.respondWithError(T.methodNotFound(t.method))}catch(r){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(Lb(r,t.responder.signal));else{let o=Cu(r);if("error"in o)console.error("Error handling notification",{method:e.method,code:o.error.code,message:o.error.message})}}}toIncomingMessage(e){if("id"in e){let t=new AbortController;this.incomingRequests.set(e.id,t);let n=()=>{if(this.incomingRequests.get(e.id)===t)this.incomingRequests.delete(e.id)},r=new wr(e.id,(o)=>{let i={jsonrpc:"2.0",id:jb.has(r)?null:e.id,...o};return this.sendMessage(i)},t.signal,n);return{kind:"request",method:e.method,params:e.params,raw:e,signal:t.signal,responder:r}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t){if(this.pendingResponses.delete(e.id),t.cleanup?.(),t.abandoned)return;if(!ft(e))t.reject(T.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:n,message:r,data:o}=e.error;t.reject(new T(n,r,o))}}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!=="$/cancel_request")return;let t=Rb(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);if(!n||n.signal.aborted)return;n.abort(T.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error("ACP connection closed")}async sendMessage(e){if(this.abortController.signal.aborted)return gr(this.closedReason());return this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch((t)=>{throw this.close(t),t}),this.writeQueue}}class Ru{handlers=[];fallbackHandlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}withFallbackHandler(e){return this.fallbackHandlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??K.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,o)=>{if(r.kind!=="request"||r.method!==e)return K.no(r);let i=t(r.params);return await n(i,r.responder,o)??K.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,o)=>{if(r.kind!=="notification"||r.method!==e)return K.no(r);let i=t(r.params);return await n(i,o)??K.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new _r(e,this.handlers,{...t,fallbackHandlers:[...t?.fallbackHandlers??[],...this.fallbackHandlers]})}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}}function Se(e){return{jsonrpc:"2.0",id:null,error:e.toErrorResponse()}}var K,jb,cn,T;var ge=S(()=>{K={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};jb=new WeakSet;cn=class cn{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){if(!this.active)return;this.active=!1,this.disposeHandler()}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}};T=class T extends Error{code;data;constructor(e,t,n){super(t);this.code=e,this.name="RequestError",this.data=n}static parseError(e,t){return new T(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new T(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new T(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new T(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new T(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new T(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new T(-32000,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new T(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}static sessionNotFound(e){return new T(-32002,"Resource not found",{sessionId:e})}static unsupportedProtocolVersion(e,t){return new T(-32022,"Unsupported protocol version",{requested:e,supported:[...t]})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}});function Ou(e){return Ub.has(e)}function un(e){if(!ee(e))return;let t=e.sessionId;return typeof t==="string"?t:void 0}function Nu(e){return"method"in e?un(e.params):void 0}function Pu(e){if(!ft(e)||!("result"in e))return;if(!ee(e.result))return;let t=e.result.sessionId;return typeof t==="string"?t:void 0}function ln(e){return e.jsonrpc==="2.0"&&"id"in e&&"method"in e&&e.method===k.initialize}function Me(e){if(typeof e==="string")return`string:${e}`;if(typeof e==="number")return`number:${e}`;if(e===null)return"null";return}var Dt="Acp-Connection-Id",br="Acp-Session-Id",xi="text/event-stream",ki="application/json",Ub;var dn=S(()=>{sn();ge();Ub=new Set([k.session_cancel,k.session_close,k.session_delete,k.session_fork,k.session_load,k.session_prompt,k.session_resume,k.session_set_config_option,k.session_set_mode,"session/set_model"])});function Lu(e){Du(e,!0)}function Du(e,t=!1){if(e.destroyed||e.readableEnded)return;let n=()=>{e.off("error",r),e.off("end",n),e.off("close",n),e.off("aborted",n)},r=()=>{n()};if(e.once("error",r),e.once("end",n),e.once("close",n),e.once("aborted",n),t)e.resume()}async function Mu(e,t){let n=Zb(e);if(n!==void 0&&n>t)throw Du(e),new pn(t);let r=new TextDecoder;return new Promise((o,i)=>{let s="",a=0,l=!1,d=()=>{e.off("data",g),e.off("end",w),e.off("error",b),e.off("aborted",z),e.off("close",I)},f=(E,A=!0)=>{if(l){if(A)d();return}if(l=!0,A)d();i(E)},g=(E)=>{if(l)return;if(a+=Bb(E),a>t){e.pause(),f(new pn(t),!1);return}if(typeof E==="string"){s+=E.length===0?r.decode(new Uint8Array,{stream:!0}):r.decode(),s+=E;return}s+=r.decode(Fb(E),{stream:!0})},w=()=>{if(d(),l)return;l=!0,o(s+r.decode())},b=(E)=>{f(E)},z=()=>{f(Error("Request aborted"))},I=()=>{f(Error("Request closed"))};e.once("end",w),e.once("error",b),e.once("aborted",z),e.once("close",I),e.on("data",g)})}function Zb(e){let t=e.headers["content-length"],n=Array.isArray(t)?t[0]:t;if(n===void 0)return;let r=n.trim();if(!/^\d+$/.test(r))return;let o=Number(r);return Number.isSafeInteger(o)?o:Number.POSITIVE_INFINITY}function Bb(e){if(typeof e==="string")return Buffer.byteLength(e);if(e instanceof Uint8Array)return e.byteLength;return Buffer.byteLength(String(e))}function Fb(e){if(e instanceof Uint8Array)return e;return Buffer.from(String(e))}var pn;var ju=S(()=>{pn=class pn extends Error{constructor(e){super(`Request body exceeds ${e} bytes`)}}});function Zu(e,t={}){let n=Kb(t.maxRequestBodyBytes);return(r,o)=>{qb(e,r,o,n)}}async function qb(e,t,n,r){let o=Hb(t,n);try{await ey(n,await e.handleRequest(await Gb(t,o.signal,r)))}catch(i){if(i instanceof pn){Uu(n,413,i.message),Lu(t);return}if(n.headersSent){n.destroy();return}Uu(n,500,i instanceof Error?i.message:"Internal Server Error")}finally{o.cleanup()}}function Uu(e,t,n){if(!e.headersSent)e.statusCode=t,e.setHeader("Content-Type","text/plain");e.end(n)}function Hb(e,t){let n=new AbortController,r=!1,o=()=>{r=!0},i=()=>{if(!r)n.abort(Error("Node HTTP response closed"))};return e.once("aborted",i),t.once("finish",o),t.once("close",i),{signal:n.signal,cleanup:()=>{e.off("aborted",i),t.off("finish",o),t.off("close",i)}}}async function Gb(e,t,n){return new Request(Xb(e),{method:e.method??"GET",headers:Qb(e),body:Wb(e)?await Mu(e,n):void 0,signal:t})}function Wb(e){return e.method!=="GET"&&e.method!=="HEAD"}function Kb(e){let t=e??Vb;if(!Number.isSafeInteger(t)||t<0)throw RangeError("maxRequestBodyBytes must be a non-negative safe integer");return t}function Jb(e){let t=e.headers.host,n=Array.isArray(t)?t[0]:t;if(n===void 0)return"localhost";let r=n.trim();if(r.length===0||Yb(r))return"localhost";try{let o=new URL(`http://${r}`);if(o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")return"localhost"}catch{return"localhost"}return r}function Yb(e){for(let t of e){let n=t.codePointAt(0);if(n===void 0||n<=31||n===127||t.trim()===""||t==="/"||t==="?"||t==="#"||t==="@"||t==="\\")return!0}return!1}function Xb(e){return`http://${Jb(e)}${e.url??"/"}`}function Qb(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers)){if(Array.isArray(r)){for(let o of r)t.append(n,o);continue}if(r!==void 0)t.set(n,r)}return t}async function ey(e,t){e.statusCode=t.status,ty(e,t.headers),e.flushHeaders();let n=t.body;if(!n){e.end();return}let r=n.getReader(),o=new AbortController;r.closed.catch((l)=>{o.abort(l)});let i,s=!1,a=()=>{i=r.cancel(new fn).catch(()=>{return})};e.once("close",a);try{while(!0){let l=await r.read();if(l.done){if(s=!0,e.off("close",a),!Bu(e))e.end();return}await ry(e,l.value,o.signal)}}catch(l){if(l instanceof fn)return;throw l}finally{if(e.off("close",a),!s&&!i)a();await i,r.releaseLock()}}function ty(e,t){let n=ny(t),r=[];t.forEach((i,s)=>{if(s.toLowerCase()==="set-cookie"){if(!n)r.push(i);return}e.setHeader(s,i)});let o=n??r;if(o.length>0)e.setHeader("Set-Cookie",o)}function ny(e){let t=e.getSetCookie;return typeof t==="function"?t.call(e):void 0}function ry(e,t,n){return new Promise((r,o)=>{let i=!1,s=(g)=>{if(i)return;i=!0,e.off("close",d),e.off("drain",l),e.off("error",a),n.removeEventListener("abort",f),g()},a=(g)=>{s(()=>{o(g)})},l=()=>{s(r)},d=()=>{s(()=>{o(new fn)})},f=()=>{s(()=>{o(n.reason)})};if(Bu(e)){o(new fn);return}if(n.aborted){o(n.reason);return}if(e.once("close",d),e.once("error",a),n.addEventListener("abort",f,{once:!0}),e.write(t)){s(r);return}e.once("drain",l)})}function Bu(e){return e.destroyed||e.writableEnded}var Vb=16777216,fn;var Fu=S(()=>{dn();ju();fn=class fn extends Error{constructor(){super("Node HTTP response closed")}}});function zr(e,t){return new ve(`Connection exceeds ${e} (${t[e]})`)}function vi(e){return new ve(`Connection output stalled for maxOutputStallMs (${e.maxOutputStallMs})`)}class yr{enabled;onReceiverChange;observer;queue=[];head=0;activeLease;isFinished=!1;isAborted=!1;abortError;constructor(e=!0,t,n){this.enabled=e,this.onReceiverChange=t,this.observer=n}push(e){if(!this.enabled||this.isFinished)return;this.queue.push(e),this.observer?.queued?.(e),this.activeLease?.wake()}get hasReceiver(){return this.activeLease!==void 0}get hasQueuedMessages(){return this.head<this.queue.length}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new Ku(this);return this.activeLease=e,this.onReceiverChange?.(),e}finish(){if(this.isFinished)return;this.isFinished=!0,this.activeLease?.wake()}abort(e){if(this.isAborted)return;this.isAborted=!0,this.abortError=e,this.isFinished=!0;while(this.hasQueuedMessages)this.dequeue();this.observer=void 0,this.onReceiverChange=void 0,this.activeLease?.stop(e??new we)}async receive(e){for(;;){if(e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.isAborted){if(this.abortError!==void 0)throw this.abortError;return{done:!0,value:void 0}}if(this.hasQueuedMessages)return{done:!1,value:this.dequeue()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){if(this.activeLease!==e)return;this.activeLease=void 0,e.markReleased(),this.onReceiverChange?.()}dequeue(){let e=this.queue[this.head];if(this.queue[this.head]=void 0,this.head+=1,this.head===this.queue.length)this.queue=[],this.head=0;else if(this.head>=1024&&this.head*2>=this.queue.length)this.queue=this.queue.slice(this.head),this.head=0;return this.observer?.dequeued(e),e}}class Si{transport;limits;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;bufferedBytes=0;streamObserver={queued:(e)=>{this.bufferedBytes+=e.length},dequeued:(e)=>{this.bufferedBytes-=e.length,this.notifyOutboundProgress()}};bufferedSessionStreams=0;progressWaiters=new Set;hasStartedRouter=!1;hasAgentOutputEnded=!1;hasFinishedRouting=!1;hasStartedShutdown=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;abortAgentInbound=()=>{};endAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,t,n){this.transport=t,this.limits=n,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new yr(t==="http",void 0,this.streamObserver),this.allOutbound=new yr(t==="websocket",void 0,{dequeued:()=>{this.notifyOutboundProgress()}}),this.closed=new Promise((s)=>{this.resolveClosed=s});let r=new TransformStream({start:(s)=>{this.abortAgentInbound=(a)=>s.error(a)}}),o=iy(()=>{this.hasAgentOutputEnded=!0,this.notifyOutboundProgress()});this.inboundTx=r.writable,this.outboundRx=o.readable,this.endAgentOutbound=o.end;let i={readable:r.readable,writable:o.writable};this.agentConnection=e.connect(i,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let t=this.outboundRx.getReader();this.initialReader=t;try{let n=await t.read();if(n.done||!n.value||!sy(n.value,e)){if(!this.shutdownPromise)await this.shutdown();throw Error("Expected initialize response from agent")}return n.value}finally{if(this.initialReader===t)this.initialReader=void 0;t.releaseLock()}}async writeInbound(e){let t=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=t.catch(()=>{return}),await t}startRouter(){if(this.hasStartedRouter)return;this.hasStartedRouter=!0,this.routerPromise=this.runRouter()}startConnectHandlers(){if(typeof this.agentConnection==="object"&&this.agentConnection!==null&&"startConnectHandlers"in this.agentConnection&&typeof this.agentConnection.startConnectHandlers==="function")this.agentConnection.startConnectHandlers()}get isClosed(){return this.hasStartedShutdown}get hasOutboundBacklog(){return this.transport==="http"?this.bufferedBytes>=this.limits.maxBufferedBytes:this.allOutbound.hasQueuedMessages}validateSessionId(e){this.validateIdLength("Session ID",e)}validateRequestId(e){if(typeof e==="string")this.validateIdLength("Request ID",e)}async waitForOutboundCapacity(e){await this.waitForRoom(()=>this.hasFinishedRouting,e)}ensureSession(e){if(this.validateSessionId(e),this.transport==="websocket")return this.connectionStream;let t=this.sessionStreams.get(e);if(t)return t;if(this.bufferedSessionStreams>=this.limits.maxBufferedSessionStreams)throw zr("maxBufferedSessionStreams",this.limits);return this.createSessionStream(e)}acquireSessionStream(e){if(this.validateSessionId(e),this.transport==="websocket")return;let t=this.sessionStreams.get(e);if(t)return t.tryAcquire();if(this.isClosed||this.hasFinishedRouting)throw new we;return this.createSessionStream(e).tryAcquire()}async shutdown(e){if(!this.shutdownPromise)this.shutdownPromise=this.runShutdown(e);return this.shutdownPromise}async runShutdown(e){try{this.hasStartedShutdown=!0,this.notifyOutboundProgress(),this.connectionStream.abort(e),this.allOutbound.abort(e);for(let t of this.sessionStreams.values())t.abort(e);this.sessionStreams.clear(),this.bufferedSessionStreams=0,this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.closeInbound(e),this.cancelOutboundReader()])}finally{this.resolveClosedOnce()}}observeAgentConnection(){if(typeof this.agentConnection!=="object"||this.agentConnection===null||!("closed"in this.agentConnection)||!this.agentConnection.closed)return;Promise.resolve(this.agentConnection.closed).finally(async()=>{if(!this.hasStartedRouter){await this.shutdown();return}this.endAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;if(e)return e.cancel();return this.outboundRx.cancel()}closeInbound(e){if(e!==void 0||this.inboundTx.locked)return this.abortAgentInbound(e??new we),Promise.resolve();return this.inboundTx.close()}async writeInboundMessage(e){if(this.isClosed||this.hasFinishedRouting)throw new we;let t=this.inboundTx.getWriter();try{await t.write(e)}catch(n){if(this.isClosed)throw new we;throw n}finally{t.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{while(!0){let t=await e.read();if(t.done||this.isClosed)return;this.routeOutbound(t.value),await this.waitForRoom(()=>this.hasAgentOutputEnded)}}catch(t){if(t instanceof ve)this.closeForLimit(t);else console.error(`ACP connection ${this.connectionId} router stopped unexpectedly:`,t),this.shutdown(t)}finally{if(this.hasFinishedRouting=!0,this.notifyOutboundProgress(),this.outboundReader===e)this.outboundReader=void 0;e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let t of this.sessionStreams.values())t.finish();this.resolveClosedOnce()}}resolveClosedOnce(){if(this.hasResolvedClosed)return;this.hasResolvedClosed=!0,this.resolveClosed()}async waitForRoom(e,t){while(!this.isClosed&&!e()&&this.hasOutboundBacklog)if(!await this.waitForProgress(t)){this.closeForLimit(vi(this.limits));return}}waitForProgress(e){let t=this.transport==="http"?this.limits.maxOutputStallMs:void 0;return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}let o,i=()=>{this.progressWaiters.delete(s),e?.removeEventListener("abort",a),clearTimeout(o)},s=()=>{i(),n(!0)},a=()=>{i(),r(e?.reason)};if(this.progressWaiters.add(s),e?.addEventListener("abort",a,{once:!0}),t!==void 0)o=setTimeout(()=>{i(),n(!1)},t)})}notifyOutboundProgress(){for(let e of[...this.progressWaiters])e()}routeOutbound(e){this.routeOutboundMessage(e),this.allOutbound.push(e)}routeOutboundMessage(e){if(ft(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let t=Me(e.id),n=t?this.pendingRoutes.get(t):void 0,r=Pu(e);if(r)this.validateSessionId(r);if(t)this.pendingRoutes.delete(t);this.pushToRoute(n??"connection",e)}createSessionStream(e){let t=new yr(!0,()=>{this.onSessionReceiverChange(e,t)},this.streamObserver);return this.sessionStreams.set(e,t),this.bufferedSessionStreams+=1,t}onSessionReceiverChange(e,t){if(this.isClosed)return;if(t.hasReceiver){this.bufferedSessionStreams-=1;return}if(!t.hasQueuedMessages){this.sessionStreams.delete(e),t.abort();return}if(this.bufferedSessionStreams+=1,!this.hasFinishedRouting&&this.bufferedSessionStreams>this.limits.maxBufferedSessionStreams)this.closeForLimit(zr("maxBufferedSessionStreams",this.limits))}closeForLimit(e){console.warn(`Closing ACP connection ${this.connectionId}:`,e.message),this.shutdown(e)}validateIdLength(e,t){if(t.length>this.limits.maxIdLength)throw new ve(`${e} exceeds maxIdLength (${this.limits.maxIdLength})`)}routeOutboundRequestOrNotification(e){let t=Nu(e);if(t){let n=this.ensureSession(t);this.trackClientResponseRoute(e,{session:t}),this.deliver(n,e);return}this.trackClientResponseRoute(e,"connection"),this.deliver(this.connectionStream,e)}trackClientResponseRoute(e,t){if(!("id"in e)||!("method"in e))return;let n=Me(e.id);if(n)this.clientResponseRoutes.set(n,t)}pushToRoute(e,t){if(e==="connection"){this.deliver(this.connectionStream,t);return}this.deliver(this.ensureSession(e.session),t)}deliver(e,t){if(this.transport==="http")e.push(JSON.stringify(t))}}class $i{limits;connections=new Map;pendingConnections=new Map;constructor(e={}){this.limits=oy(e)}createConnection(e,t="http"){let n=new Si(e,t,this.limits);return this.connections.set(n.connectionId,n),this.trackConnectionClose(n),n}createPendingConnection(e,t="websocket"){let n=new Si(e,t,this.limits);return this.pendingConnections.set(n.connectionId,n),this.trackConnectionClose(n),n}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){let t=this.connections.get(e);return t?.isClosed?void 0:t}remove(e){let t=this.connections.get(e);if(!t)return;return this.connections.delete(e),t.shutdown(),t}discard(e){let t=this.connections.get(e)??this.pendingConnections.get(e);if(!t)return;return this.connections.delete(e),this.pendingConnections.delete(e),t.shutdown(),t}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,(t)=>t.shutdown()))}trackConnectionClose(e){e.closed.then(()=>{if(this.connections.get(e.connectionId)===e)this.connections.delete(e.connectionId);if(this.pendingConnections.get(e.connectionId)===e)this.pendingConnections.delete(e.connectionId)})}}function oy(e){let t={maxBufferedBytes:e.maxBufferedBytes??qu,maxOutputStallMs:e.maxOutputStallMs??Hu,maxBufferedSessionStreams:e.maxBufferedSessionStreams??Gu,maxIdLength:e.maxIdLength??Wu};for(let[n,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw RangeError(`${n} must be a positive safe integer`);if(t.maxOutputStallMs>Vu)throw RangeError(`maxOutputStallMs must be at most ${Vu}`);return t}class Ku{mailbox;released=!1;stoppedController=new AbortController;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}get stopped(){return this.stoppedController.signal}async receive(){if(this.receiving)throw Error("ACP outbound mailbox lease already has a pending receive");this.receiving=!0;try{return await this.mailbox.receive(this)}finally{this.receiving=!1}}release(){this.mailbox.release(this)}wake(){this.resolveWake?.(),this.wakePromise=void 0,this.resolveWake=void 0}wait(){if(!this.wakePromise)this.wakePromise=new Promise((e)=>{this.resolveWake=e});return this.wakePromise}markReleased(){this.released=!0,this.wake()}stop(e){this.stoppedController.abort(e),this.wake()}}function iy(e){let t,n=!1,r=!1,o,i=()=>{let d=o;o=void 0,d?.()},s=()=>{if(n)return;n=!0;try{t?.close()}catch{}i(),e()},a=(d)=>{if(n)return;n=!0;try{t?.error(d)}catch{}i(),e()},l=()=>{if(n||r)return;r=!0,i(),setTimeout(s,0)};return{readable:new ReadableStream({start(d){t=d},pull:i,cancel(){n=!0,i()}},{highWaterMark:0}),writable:new WritableStream({async write(d){if(n)throw Error("ACP outbound channel is closed");try{t?.enqueue(d)}catch(f){throw a(f),f}if(!n&&!r&&(t?.desiredSize??0)<0)await new Promise((f)=>{o=f})},close:s,abort:a}),end:l}}function sy(e,t){return"id"in e&&!("method"in e)&&e.id===t}var qu=67108864,Hu=60000,Gu=1024,Wu=1024,Vu=2147483647,ve,we;var xr=S(()=>{ge();dn();ve=class ve extends Error{constructor(e){super(e);this.name="ConnectionLimitError"}};we=class we extends Error{constructor(){super("ACP connection is closed");this.name="ConnectionClosedError"}}});var kr;var Ei=S(()=>{kr={initialize:"initialize",authenticate:"authenticate",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",session_list:"session/list",session_delete:"session/delete",session_resume:"session/resume",session_close:"session/close",logout:"logout"}});var mn=()=>{};var Ii=S(()=>{mn()});function Yu(e){return`data: ${e}
2
+ var v=(e,t,n)=>()=>{if(e)try{t=e(e=0)}catch(r){n=[r]}if(n)throw n[0];return t};function Tt(e){return mw[e]??e}var at="__agent-worker",ct,Jn,Cc,mw,Tc;var Re=v(()=>{ct={"claude-code":27290,codex:27291},Jn={"claude-code":"only your NimbleBrain workspace's tools",codex:"your NimbleBrain workspace's tools, plus Codex's read-only shell (it has no off switch)"},Cc={"claude-code":"sonnet",codex:void 0},mw={sonnet:"Sonnet",opus:"Opus",haiku:"Haiku"};Tc=/^[A-Za-z0-9][A-Za-z0-9._:-]*(\[[A-Za-z0-9]+\])?$/});function Nt(e,t,n={}){let{apiError:r}=n;if(r==="authentication_failed"||!r&&Jw.test(t))return new Pe("signed_out",Ww[e]);if(r==="rate_limit"||r==="billing_error"||Yw.test(t))return new Pe("plan_limit",Xw(e,t));return new Pe("cli_failed",e_(e,t,n))}function qc(e){return new Pe("cli_missing",Kw[e])}function Xw(e,t){let n=e==="claude"?"Your Claude plan":"Your ChatGPT plan",r=Qw(t);return`${n} has reached its usage limit${r?` (${r})`:""}. Send your message again once it resets, or run \`npx nimblebrain use api\` in a terminal to use an API key instead.`}function Qw(e){let t=e.match(/limit reached\|(\d{10})\b/i)?.[1];if(t)return`it resets ${new Date(Number(t)*1000).toLocaleString()}`;let n=e.match(/\bresets?\s+((?:at\s+)?[^·\n.!]{1,60})/i)?.[1]?.trim();if(n)return`it resets ${n}`;let r=e.match(/try again (in|at) ([^\n.!]{1,60})/i);return r?`try again ${r[1]} ${r[2]?.trim()}`:void 0}function e_(e,t,n){let r=n.exitCode===void 0?"stopped":`exited (${n.exitCode??"signal"})`,o=t_(t),i=n.log?`Check ${n.log}`:"Check the agent worker's log";return`${Gw[e]} ${r} without finishing the turn${o?`: ${o}`:""}. ${i} for more, then send your message again.`}function t_(e){let t=e.split(`
3
+ `).map((n)=>n.trim()).filter(Boolean).pop()??"";return n_(t).slice(0,240)}function n_(e){return e.replace(/\b(bearer|basic)\s+[^\s,;]+/gi,"$1 [redacted]").replace(/\b[A-Z][A-Z0-9_]*(KEY|TOKEN|SECRET|PASSWORD)[A-Z0-9_]*=\S+/g,"$1=[redacted]").replace(/\b(sk|sess|rt|pk)-[A-Za-z0-9_-]{8,}/g,"[redacted]").replace(/\beyJ[A-Za-z0-9_-]{10,}(\.[A-Za-z0-9_-]+)*/g,"[redacted]")}var Vc="nimblebrain-subscription/failure",Pe,Gw,Ww,Kw,Jw,Yw;var rn=v(()=>{Pe=class Pe extends Error{code;constructor(e,t){super(t);this.code=e}};Gw={claude:"Claude Code",codex:"Codex"},Ww={claude:"Claude Code is signed out. Run `claude /login` in a terminal, then send your message again.",codex:"Codex is signed out. Run `codex login` in a terminal and choose Sign in with ChatGPT, then send your message again."},Kw={claude:"Claude Code is not installed where the agent worker looks for it. Install it (https://claude.com/claude-code), sign in, then run `npx nimblebrain use claude` and send your message again.",codex:"Codex is not installed where the agent worker looks for it. Install it with `npm i -g @openai/codex`, run `codex login`, then run `npx nimblebrain use codex` and send your message again."},Jw=/not logged in|please run \/login|\/login|oauth token|token (has )?expired|invalid api key|authentication_failed|\b401\b|unauthorized|codex login|refresh token/i,Yw=/usage limit|limit reached|hit your limit|limit will reset|rate_limit_exceeded/i});function Ge(e=process.env){let t={};for(let[n,r]of Object.entries(e))if(r!==void 0&&!ei.includes(n))t[n]=r;return t}function ir(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0}}function sr(e,t){let n=new Promise((r,o)=>{e.once("error",(i)=>o(i.code==="ENOENT"?qc(t):Nt(t,`could not be started: ${i.message}`)))});return n.catch(()=>{}),n}var X,ei;var Pt=v(()=>{rn();X=class X extends Error{reason;constructor(e,t){super(t);this.reason=e}};ei=["ANTHROPIC_API_KEY","ANTHROPIC_AUTH_TOKEN","CLAUDE_CODE_OAUTH_TOKEN","OPENAI_API_KEY","CODEX_API_KEY"]});import{spawn as Hc}from"node:child_process";import{mkdtemp as r_,rm as o_}from"node:fs/promises";import{tmpdir as i_}from"node:os";import{join as s_}from"node:path";import{createInterface as a_}from"node:readline";function Gc(e={}){let t=e.bin??"claude";return{id:"claude-code",label:"Claude Code",...e.model?{modelLabel:Tt(e.model)}:{},takesSystemPrompt:!0,toolsAreNimbleBrainOnly:!0,preflight:()=>c_(t),run:(n)=>d_(t,e.model,n,e.log)}}async function c_(e){return ri(await x_(e,ni).catch(()=>{return}))}function ri(e){if(e===void 0)throw new X("not_installed","Claude Code is not installed. Install it from https://claude.com/claude-code, then run `claude` and sign in.");let t;try{t=JSON.parse(e)}catch{throw new X("unreadable","Could not read `claude auth status`. Update Claude Code.")}if(!t.loggedIn)throw new X("not_signed_in","Claude Code is not signed in. Run `claude` and sign in with your Claude account.");if(t.authMethod!=="claude.ai"||!t.subscriptionType)throw new X("api_key",`Claude Code is signed in with ${t.authMethod??"an API key"}, which bills API pricing. Run \`claude /login\` and choose your Claude subscription.`);let n=t.subscriptionType.charAt(0).toUpperCase()+t.subscriptionType.slice(1);return{describe:`your Claude ${n} subscription (claude.ai login, no API key)`,plan:`Claude ${n}`}}function l_(e,t){let n=e.purpose==="internal"||e.mcpUrl===void 0,r=n?{mcpServers:{}}:{mcpServers:{[ti]:{type:"http",url:e.mcpUrl}}},o=n?u_:t;return["-p","--output-format","stream-json","--verbose","--include-partial-messages","--mcp-config",JSON.stringify(r),"--strict-mcp-config","--tools","",...n?[]:["--allowedTools",`mcp__${ti}`],"--setting-sources","","--disable-slash-commands","--no-session-persistence",...e.system?["--system-prompt",e.system]:[],...o?["--model",o]:[]]}async function d_(e,t,n,r){let o=await r_(s_(i_(),"nb-claude-")),i=Hc(e,l_(n,t),{cwd:o,env:Ge(),stdio:["pipe","pipe","pipe"]}),s=()=>i.kill("SIGTERM");n.signal.addEventListener("abort",s,{once:!0}),i.stdin.end(n.prompt);let a="";i.stderr.on("data",(g)=>{a=(a+g.toString()).slice(-4000)});let u=new Promise((g)=>i.on("close",g)),d=sr(i,"claude"),p=g_(n.emit);try{let g=await Promise.race([f_(i.stdout,p,s),d]),w=await Promise.race([u,d]);if(g)throw new Pe("api_key",g);if(n.signal.aborted)return{stopReason:"cancelled",...p.totals()};return{stopReason:m_(p.result(),p.apiError(),{code:w,stderr:a,log:r}),...p.totals()}}finally{n.signal.removeEventListener("abort",s),await o_(o,{recursive:!0,force:!0})}}async function f_(e,t,n){for await(let r of a_({input:e})){let o=p_(r);if(!o)continue;let i=h_(o);if(i)return n(),i;t(o)}return}function p_(e){if(!e.trim())return;try{return JSON.parse(e)}catch{return}}function m_(e,t,n){if(!e||e.is_error&&e.subtype==="success"){let r=`${n.stderr}
4
+ ${e?.result??""}`;throw Nt("claude",r,{apiError:t,exitCode:n.code,log:n.log})}return e.subtype==="error_max_turns"?"max_turn_requests":"end_turn"}function h_(e){if(e.type!=="system"||e.subtype!=="init")return;if(e.apiKeySource==="none"||e.apiKeySource===void 0)return;return`Claude Code would bill an API key (source: ${e.apiKeySource}) instead of your subscription. Remove that key, or run \`claude /login\`.`}function g_(e){let t,n;return Object.assign((o)=>{if(o.type==="stream_event")w_(o,e);else if(o.type==="assistant"){if(typeof o.error==="string")n=o.error;__(o,e)}else if(o.type==="user")b_(o,e);else if(o.type==="result")t=o},{result:()=>t,apiError:()=>n,totals:()=>y_(t)})}function w_(e,t){let n=e.event?.type==="content_block_delta"?e.event.delta:void 0;if(n?.type==="text_delta"&&n.text)t({sessionUpdate:"agent_message_chunk",content:{type:"text",text:n.text}});else if(n?.type==="thinking_delta"&&n.thinking)t({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:n.thinking}})}function __(e,t){for(let n of e.message?.content??[]){if(n.type!=="tool_use"||!n.id)continue;t({sessionUpdate:"tool_call",toolCallId:n.id,title:z_(n.name??"tool"),kind:"other",status:"in_progress",rawInput:n.input})}}function b_(e,t){for(let n of e.message?.content??[]){if(n.type!=="tool_result"||!n.tool_use_id)continue;t({sessionUpdate:"tool_call_update",toolCallId:n.tool_use_id,status:n.is_error?"failed":"completed"})}}function y_(e){let t=Object.entries(e?.modelUsage??{}).map(([o,i])=>({model:`claude-code-subscription:${o}`,purpose:"turn",usage:{inputTokens:i.inputTokens??0,outputTokens:i.outputTokens??0,cacheReadTokens:i.cacheReadInputTokens??0,cacheWriteTokens:i.cacheCreationInputTokens??0}})),n=e?.usage;return{usage:n?{inputTokens:n.input_tokens??0,outputTokens:n.output_tokens??0,cacheReadTokens:n.cache_read_input_tokens??0,cacheWriteTokens:n.cache_creation_input_tokens??0}:ir(),calls:t}}function z_(e){let t=`mcp__${ti}__`;return e.startsWith(t)?e.slice(t.length):e}function x_(e,t){return new Promise((n,r)=>{let o=Hc(e,t,{env:Ge(),stdio:["ignore","pipe","pipe"]}),i="";o.stdout.on("data",(s)=>{i+=s.toString()}),o.on("error",r),o.on("close",()=>n(i))})}var ti="nimblebrain",ni,u_="haiku";var oi=v(()=>{Re();rn();Pt();ni=["auth","status","--json"]});import{spawn as Wc}from"node:child_process";import{mkdtemp as k_,rm as S_}from"node:fs/promises";import{tmpdir as v_}from"node:os";import{join as $_}from"node:path";import{createInterface as E_}from"node:readline";function Kc(e={}){let t=e.bin??"codex";return{id:"codex",label:"Codex",...e.model?{modelLabel:Tt(e.model)}:{},takesSystemPrompt:!1,toolsAreNimbleBrainOnly:!1,preflight:()=>C_(t),run:(n)=>T_(t,e.model,n,e.log)}}async function C_(e){return si(await P_(e,ii).catch(()=>{return}))}function si(e){if(e===void 0)throw new X("not_installed","Codex is not installed. Install it (`npm i -g @openai/codex`), then run `codex login`.");if(/chatgpt/i.test(e))return{describe:"your ChatGPT plan (Sign in with ChatGPT, no API key)",plan:"ChatGPT"};if(/api key/i.test(e))throw new X("api_key","Codex is signed in with an API key, which bills API pricing. Run `codex logout`, then `codex login` and choose Sign in with ChatGPT.");throw new X("not_signed_in","Codex is not signed in. Run `codex login` and choose Sign in with ChatGPT.")}async function T_(e,t,n,r){let o=await k_($_(v_(),"nb-codex-")),i=["exec","--json","--skip-git-repo-check","--ephemeral","--ignore-user-config","--sandbox","read-only","-C",o,"-c",'approval_policy="never"',...n.purpose==="internal"||n.mcpUrl===void 0?[]:["-c",`mcp_servers.${I_}.url=${JSON.stringify(n.mcpUrl)}`],...t?["-m",t]:[],"-"],s=Wc(e,i,{cwd:o,env:Ge(),stdio:["pipe","pipe","pipe"]}),a=()=>s.kill("SIGTERM");n.signal.addEventListener("abort",a,{once:!0}),s.stdin.end(n.prompt);let u="";s.stderr.on("data",(w)=>{u=(u+w.toString()).slice(-4000)});let d=new Promise((w)=>s.on("close",w)),p=sr(s,"codex"),g=R_(n.emit);try{await Promise.race([A_(s.stdout,g),p]);let w=await Promise.race([d,p]);if(n.signal.aborted)return{stopReason:"cancelled",...g.totals()};if(g.completed())return{stopReason:"end_turn",...g.totals()};let b=`${u}
5
+ ${g.failure()??""}`;throw Nt("codex",b,{exitCode:w,log:r})}finally{n.signal.removeEventListener("abort",a),await S_(o,{recursive:!0,force:!0})}}async function A_(e,t){for await(let n of E_({input:e})){if(!n.trim())continue;try{t(JSON.parse(n))}catch{}}}function R_(e){let t=ir(),n=!1,r;return Object.assign((i)=>{switch(i.type){case"item.started":if(Jc(i.item))Yc(i.item,"in_progress",e);return;case"item.completed":if(i.item)O_(i.item,e);return;case"turn.completed":t=N_(i.usage),n=!0;return;case"turn.failed":case"error":r=i.error?.message??i.message??r;return}},{completed:()=>n,failure:()=>r,totals:()=>({usage:t,calls:[{model:"codex-subscription:codex",purpose:"turn",usage:t}]})})}function Yc(e,t,n){if(!e.id)return;if(t!=="in_progress"){n({sessionUpdate:"tool_call_update",toolCallId:e.id,status:t});return}let r=e.type==="command_execution";n({sessionUpdate:"tool_call",toolCallId:e.id,title:r?`shell: ${e.command??""}`:e.tool??"tool",kind:r?"execute":"other",status:t,rawInput:e.arguments})}function O_(e,t){if(e.type==="agent_message"&&e.text)t({sessionUpdate:"agent_message_chunk",content:{type:"text",text:e.text}});else if(e.type==="reasoning"&&e.text)t({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:e.text}});else if(Jc(e))Yc(e,e.status==="failed"?"failed":"completed",t)}function N_(e={}){return{inputTokens:e.input_tokens??0,outputTokens:e.output_tokens??0,cacheReadTokens:e.cached_input_tokens??0,cacheWriteTokens:0,reasoningTokens:e.reasoning_output_tokens??0}}function P_(e,t){return new Promise((n,r)=>{let o=Wc(e,t,{env:Ge(),stdio:["ignore","pipe","pipe"]}),i="",s=(a)=>{i+=a.toString()};o.stdout.on("data",s),o.stderr.on("data",s),o.on("error",r),o.on("close",()=>n(i))})}var I_="nimblebrain",ii,Jc=(e)=>e?.type==="mcp_tool_call"||e?.type==="command_execution";var ai=v(()=>{Re();rn();Pt();ii=["login","status"]});function Bt(e){process.stderr.write(`[${new Date().toISOString().slice(11,19)}] ${e}
6
+ `)}var S,O,Ti,Ai=1;var pn=v(()=>{S={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_archive:"session/archive",session_unarchive:"session/unarchive",session_status:"session/status",session_set_title:"session/set_title",session_resume:"session/resume",session_close:"session/close",logout:"logout",auth_status:"auth/status"},O={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_message:"mcp/message",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete",auth_status_update:"auth/status_update"},Ti={cancel_request:"$/cancel_request"}});function Wu(e,t,n){if(e!=="session/close"&&e!=="session/delete")return t;return t.catch((r)=>{if(r instanceof T&&r.code===-32002)return n();throw r})}function gt(e){return Ri(e)&&"id"in e&&typeof e.method==="string"&&Oi(e.id)}function wt(e){if(!Ri(e)||"method"in e)return!1;if(!("id"in e)||!Oi(e.id))return!1;let t=Object.hasOwn(e,"result"),n=Object.hasOwn(e,"error");if(t===n)return!1;return!n||uy(e.error)}function _t(e){return Ri(e)&&!("id"in e)&&typeof e.method==="string"}function Q(e){return typeof e==="object"&&e!==null}function Ri(e){return Q(e)&&e.jsonrpc==="2.0"}function Oi(e){return e===null||typeof e==="string"||typeof e==="number"&&Number.isFinite(e)}function mn(e){return Q(e)&&!("method"in e)&&(("id"in e)||("result"in e)||("error"in e))}function cy(e){if(!Q(e)||!Oi(e.requestId))return;return e.requestId}function uy(e){return Q(e)&&typeof e.code==="number"&&Number.isInteger(e.code)&&typeof e.message==="string"}function xr(e){let t=Promise.reject(e);return t.catch(()=>{}),t}function ly(e){if(e instanceof Error)return e.message;if(typeof e==="object"&&e!=null&&"message"in e&&typeof e.message==="string")return e.message;return}function dy(e){return typeof e==="object"&&e!==null&&"name"in e&&e.name==="ZodError"&&"issues"in e&&Array.isArray(e.issues)&&"format"in e&&typeof e.format==="function"}function Gu(e){if(Array.isArray(e))return{type:"array"};if(Q(e))return{type:"object",keys:Object.keys(e)};return{type:e===null?"null":typeof e}}function Ku(e){if(e instanceof T)return e.toResult();if(dy(e))return T.invalidParams(e.format()).toResult();let t=ly(e);try{return T.internalError(t?JSON.parse(t):{}).toResult()}catch{return T.internalError({details:t}).toResult()}}function Ju(e){if(e instanceof T&&e.code===-32800)return e;return T.requestCancelled(e)}function fy(e,t){let n=py(e,t);return n?n.toResult():Ku(e)}function py(e,t){if(!t.aborted||!my(e))return;return Ju(t.reason)}function my(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.name==="AbortError"||t.code==="ABORT_ERR"}class kr{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,n=new AbortController().signal,r){this.id=e,this.sendResult=t,this.signal=n,this.finishRequest=r}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof T?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){if(this.didRespond)return xr(Error("JSON-RPC request already responded"));return this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()})}}class Yu{connection;constructor(e){this.connection=e}sendRequest(e,t,n,r){return this.connection.sendRequest(e,t,n,r)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}}class Sr{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;fallbackHandlers=[];stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Yu(this);receiveReader;constructor(e,t,n,r){if(typeof e==="function"){let a=e,u=t,d=n;this.initialize(d,[...r?.handlers??[],this.legacyHandler(a,u)],r);return}let o=e,i=t,s=n;this.initialize(o,[...s?.handlers??[],...i],s)}static builder(){return new Xu}runUntil(e){let t=!1,n=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),r=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([n,r]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch((n)=>this.close(n));return new hn(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,n,r={}){if(this.abortController.signal.aborted)return xr(this.closedReason());let o=this.prepareRequest(e,t,n,r);if(this.sendMessage(o.message).catch(()=>{}),r.cancellationSignal?.aborted)o.cancel();return o.response}sendCancelRequest(e){return this.sendNotification("$/cancel_request",{requestId:e})}sendNotification(e,t){if(this.abortController.signal.aborted)return xr(this.closedReason());return this.sendMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,n,r={}){let o=this.nextRequestId++,i=()=>{},s=new Promise((a,u)=>{let d={resolve:(p)=>{try{a(n?n(p):p)}catch(g){u(g)}},reject:u};i=()=>{if(d.cancellationSent)return;if(d.cancellationSent=!0,d.cleanup?.(),this.sendCancelRequest(o).catch(()=>{}),r.stopWaitingOnCancel)d.abandoned=!0,u(Ju(r.cancellationSignal?.reason))},r.cancellationSignal?.addEventListener("abort",i,{once:!0}),d.cleanup=()=>{r.cancellationSignal?.removeEventListener("abort",i)},this.pendingResponses.set(o,d)});return s.catch(()=>{}),{message:{jsonrpc:"2.0",id:o,method:e,params:t},response:s,cancel:()=>i()}}close(e){if(this.abortController.signal.aborted)return;let t=e??Error("ACP connection closed");this.abortController.abort(t);for(let n of this.pendingResponses.values())n.cleanup?.(),n.reject(t);this.pendingResponses.clear();for(let n of this.incomingRequests.values())n.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,n){this.stream=e,this.staticHandlers=t,this.fallbackHandlers=[...n?.fallbackHandlers??[]],this.closedPromise=new Promise((r)=>{this.abortController.signal.addEventListener("abort",()=>r())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(n,r)=>{if(n.kind==="request"){let o=await e(n.method,n.params,r);await n.responder.respond(o)}else await t(n.method,n.params,r);return K.yes()}}}async receive(){let e=void 0;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{while(!this.abortController.signal.aborted){let{value:n,done:r}=await t.read();if(this.abortController.signal.aborted)break;if(r)break;this.receiveUnvalidatedMessage(n)}}finally{if(this.receiveReader===t)this.receiveReader=void 0;t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveUnvalidatedMessage(e){if(Array.isArray(e)){this.sendMessage(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported"))).catch(()=>{});return}if(!gt(e)&&!_t(e)&&!mn(e)){this.sendMessage(Se(T.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveMessage(e){if(this.abortController.signal.aborted)return Promise.resolve();if(!Q(e))return console.error("Invalid message",Gu(e)),Promise.resolve();if("method"in e){if(!("id"in e))this.handleProtocolNotification(e);return this.processIncomingMessage(this.toIncomingMessage(e)).catch((t)=>this.close(t))}else if("id"in e)this.handleResponse(e);else console.error("Invalid message",Gu(e));return Promise.resolve()}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,n=!1;try{for(let r of[...this.staticHandlers,...this.dynamicHandlers.values(),...this.fallbackHandlers]){if(this.abortController.signal.aborted)return;let o=await r.handleMessage(t,this.context)??{handled:!0};if(o.handled)return;t=o.message??t,n=n||Boolean(o.retry)}if(n)this.retryQueue.push(t);else if(t.kind==="request")await t.responder.respondWithError(T.methodNotFound(t.method))}catch(r){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(fy(r,t.responder.signal));else{let o=Ku(r);if("error"in o)console.error("Error handling notification",{method:e.method,code:o.error.code,message:o.error.message})}}}toIncomingMessage(e){if("id"in e){let t=new AbortController;this.incomingRequests.set(e.id,t);let n=()=>{if(this.incomingRequests.get(e.id)===t)this.incomingRequests.delete(e.id)},r=new kr(e.id,(o)=>{let i={jsonrpc:"2.0",id:hy.has(r)?null:e.id,...o};return this.sendMessage(i)},t.signal,n);return{kind:"request",method:e.method,params:e.params,raw:e,signal:t.signal,responder:r}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t){if(this.pendingResponses.delete(e.id),t.cleanup?.(),t.abandoned)return;if(!wt(e))t.reject(T.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:n,message:r,data:o}=e.error;t.reject(new T(n,r,o))}}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!=="$/cancel_request")return;let t=cy(e.params);if(t===void 0)return;let n=this.incomingRequests.get(t);if(!n||n.signal.aborted)return;n.abort(T.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??Error("ACP connection closed")}async sendMessage(e){if(this.abortController.signal.aborted)return xr(this.closedReason());return this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch((t)=>{throw this.close(t),t}),this.writeQueue}}class Xu{handlers=[];fallbackHandlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}withFallbackHandler(e){return this.fallbackHandlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,n)=>await e(t,n)??K.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,n){return this.withHandler({handleMessage:async(r,o)=>{if(r.kind!=="request"||r.method!==e)return K.no(r);let i=t(r.params);return await n(i,r.responder,o)??K.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,n){return this.withHandler({handleMessage:async(r,o)=>{if(r.kind!=="notification"||r.method!==e)return K.no(r);let i=t(r.params);return await n(i,o)??K.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new Sr(e,this.handlers,{...t,fallbackHandlers:[...t?.fallbackHandlers??[],...this.fallbackHandlers]})}connectWith(e,t,n){return this.connect(e,n).runUntil(t)}}function Se(e){return{jsonrpc:"2.0",id:null,error:e.toErrorResponse()}}var K,hy,hn,T;var ge=v(()=>{K={yes(){return{handled:!0}},no(e,t=!1){return{handled:!1,message:e,retry:t}}};hy=new WeakSet;hn=class hn{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){if(!this.active)return;this.active=!1,this.disposeHandler()}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}};T=class T extends Error{code;data;constructor(e,t,n){super(t);this.code=e,this.name="RequestError",this.data=n}static parseError(e,t){return new T(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new T(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new T(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new T(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new T(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new T(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new T(-32000,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new T(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}static sessionNotFound(e){return new T(-32002,"Resource not found",{sessionId:e})}static unsupportedProtocolVersion(e,t){return new T(-32022,"Unsupported protocol version",{requested:e,supported:[...t]})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}}});function Qu(e){return gy.has(e)}function gn(e){if(!Q(e))return;let t=e.sessionId;return typeof t==="string"?t:void 0}function el(e){return"method"in e?gn(e.params):void 0}function tl(e){if(!wt(e)||!("result"in e))return;if(!Q(e.result))return;let t=e.result.sessionId;return typeof t==="string"?t:void 0}function wn(e){return e.jsonrpc==="2.0"&&"id"in e&&"method"in e&&e.method===S.initialize}function je(e){if(typeof e==="string")return`string:${e}`;if(typeof e==="number")return`number:${e}`;if(e===null)return"null";return}var Ft="Acp-Connection-Id",vr="Acp-Session-Id",Ni="text/event-stream",Pi="application/json",gy;var _n=v(()=>{pn();ge();gy=new Set([S.session_cancel,S.session_close,S.session_delete,S.session_fork,S.session_load,S.session_prompt,S.session_resume,S.session_set_config_option,S.session_set_mode,"session/set_model"])});function nl(e){rl(e,!0)}function rl(e,t=!1){if(e.destroyed||e.readableEnded)return;let n=()=>{e.off("error",r),e.off("end",n),e.off("close",n),e.off("aborted",n)},r=()=>{n()};if(e.once("error",r),e.once("end",n),e.once("close",n),e.once("aborted",n),t)e.resume()}async function ol(e,t){let n=wy(e);if(n!==void 0&&n>t)throw rl(e),new bn(t);let r=new TextDecoder;return new Promise((o,i)=>{let s="",a=0,u=!1,d=()=>{e.off("data",g),e.off("end",w),e.off("error",b),e.off("aborted",z),e.off("close",I)},p=(k,A=!0)=>{if(u){if(A)d();return}if(u=!0,A)d();i(k)},g=(k)=>{if(u)return;if(a+=_y(k),a>t){e.pause(),p(new bn(t),!1);return}if(typeof k==="string"){s+=k.length===0?r.decode(new Uint8Array,{stream:!0}):r.decode(),s+=k;return}s+=r.decode(by(k),{stream:!0})},w=()=>{if(d(),u)return;u=!0,o(s+r.decode())},b=(k)=>{p(k)},z=()=>{p(Error("Request aborted"))},I=()=>{p(Error("Request closed"))};e.once("end",w),e.once("error",b),e.once("aborted",z),e.once("close",I),e.on("data",g)})}function wy(e){let t=e.headers["content-length"],n=Array.isArray(t)?t[0]:t;if(n===void 0)return;let r=n.trim();if(!/^\d+$/.test(r))return;let o=Number(r);return Number.isSafeInteger(o)?o:Number.POSITIVE_INFINITY}function _y(e){if(typeof e==="string")return Buffer.byteLength(e);if(e instanceof Uint8Array)return e.byteLength;return Buffer.byteLength(String(e))}function by(e){if(e instanceof Uint8Array)return e;return Buffer.from(String(e))}var bn;var il=v(()=>{bn=class bn extends Error{constructor(e){super(`Request body exceeds ${e} bytes`)}}});function al(e,t={}){let n=vy(t.maxRequestBodyBytes);return(r,o)=>{zy(e,r,o,n)}}async function zy(e,t,n,r){let o=xy(t,n);try{await Ty(n,await e.handleRequest(await ky(t,o.signal,r)))}catch(i){if(i instanceof bn){sl(n,413,i.message),nl(t);return}if(n.headersSent){n.destroy();return}sl(n,500,i instanceof Error?i.message:"Internal Server Error")}finally{o.cleanup()}}function sl(e,t,n){if(!e.headersSent)e.statusCode=t,e.setHeader("Content-Type","text/plain");e.end(n)}function xy(e,t){let n=new AbortController,r=!1,o=()=>{r=!0},i=()=>{if(!r)n.abort(Error("Node HTTP response closed"))};return e.once("aborted",i),t.once("finish",o),t.once("close",i),{signal:n.signal,cleanup:()=>{e.off("aborted",i),t.off("finish",o),t.off("close",i)}}}async function ky(e,t,n){return new Request(Iy(e),{method:e.method??"GET",headers:Cy(e),body:Sy(e)?await ol(e,n):void 0,signal:t})}function Sy(e){return e.method!=="GET"&&e.method!=="HEAD"}function vy(e){let t=e??yy;if(!Number.isSafeInteger(t)||t<0)throw RangeError("maxRequestBodyBytes must be a non-negative safe integer");return t}function $y(e){let t=e.headers.host,n=Array.isArray(t)?t[0]:t;if(n===void 0)return"localhost";let r=n.trim();if(r.length===0||Ey(r))return"localhost";try{let o=new URL(`http://${r}`);if(o.username!==""||o.password!==""||o.pathname!=="/"||o.search!==""||o.hash!=="")return"localhost"}catch{return"localhost"}return r}function Ey(e){for(let t of e){let n=t.codePointAt(0);if(n===void 0||n<=31||n===127||t.trim()===""||t==="/"||t==="?"||t==="#"||t==="@"||t==="\\")return!0}return!1}function Iy(e){return`http://${$y(e)}${e.url??"/"}`}function Cy(e){let t=new Headers;for(let[n,r]of Object.entries(e.headers)){if(Array.isArray(r)){for(let o of r)t.append(n,o);continue}if(r!==void 0)t.set(n,r)}return t}async function Ty(e,t){e.statusCode=t.status,Ay(e,t.headers),e.flushHeaders();let n=t.body;if(!n){e.end();return}let r=n.getReader(),o=new AbortController;r.closed.catch((u)=>{o.abort(u)});let i,s=!1,a=()=>{i=r.cancel(new yn).catch(()=>{return})};e.once("close",a);try{while(!0){let u=await r.read();if(u.done){if(s=!0,e.off("close",a),!cl(e))e.end();return}await Oy(e,u.value,o.signal)}}catch(u){if(u instanceof yn)return;throw u}finally{if(e.off("close",a),!s&&!i)a();await i,r.releaseLock()}}function Ay(e,t){let n=Ry(t),r=[];t.forEach((i,s)=>{if(s.toLowerCase()==="set-cookie"){if(!n)r.push(i);return}e.setHeader(s,i)});let o=n??r;if(o.length>0)e.setHeader("Set-Cookie",o)}function Ry(e){let t=e.getSetCookie;return typeof t==="function"?t.call(e):void 0}function Oy(e,t,n){return new Promise((r,o)=>{let i=!1,s=(g)=>{if(i)return;i=!0,e.off("close",d),e.off("drain",u),e.off("error",a),n.removeEventListener("abort",p),g()},a=(g)=>{s(()=>{o(g)})},u=()=>{s(r)},d=()=>{s(()=>{o(new yn)})},p=()=>{s(()=>{o(n.reason)})};if(cl(e)){o(new yn);return}if(n.aborted){o(n.reason);return}if(e.once("close",d),e.once("error",a),n.addEventListener("abort",p,{once:!0}),e.write(t)){s(r);return}e.once("drain",u)})}function cl(e){return e.destroyed||e.writableEnded}var yy=16777216,yn;var ul=v(()=>{_n();il();yn=class yn extends Error{constructor(){super("Node HTTP response closed")}}});function Er(e,t){return new ve(`Connection exceeds ${e} (${t[e]})`)}function Mi(e){return new ve(`Connection output stalled for maxOutputStallMs (${e.maxOutputStallMs})`)}class $r{enabled;onReceiverChange;observer;queue=[];head=0;activeLease;isFinished=!1;isAborted=!1;abortError;constructor(e=!0,t,n){this.enabled=e,this.onReceiverChange=t,this.observer=n}push(e){if(!this.enabled||this.isFinished)return;this.queue.push(e),this.observer?.queued?.(e),this.activeLease?.wake()}get hasReceiver(){return this.activeLease!==void 0}get hasQueuedMessages(){return this.head<this.queue.length}tryAcquire(){if(!this.enabled||this.isAborted||this.activeLease)return;let e=new hl(this);return this.activeLease=e,this.onReceiverChange?.(),e}finish(){if(this.isFinished)return;this.isFinished=!0,this.activeLease?.wake()}abort(e){if(this.isAborted)return;this.isAborted=!0,this.abortError=e,this.isFinished=!0;while(this.hasQueuedMessages)this.dequeue();this.observer=void 0,this.onReceiverChange=void 0,this.activeLease?.stop(e??new we)}async receive(e){for(;;){if(e.released||this.activeLease!==e)return{done:!0,value:void 0};if(this.isAborted){if(this.abortError!==void 0)throw this.abortError;return{done:!0,value:void 0}}if(this.hasQueuedMessages)return{done:!1,value:this.dequeue()};if(this.isFinished)return{done:!0,value:void 0};await e.wait()}}release(e){if(this.activeLease!==e)return;this.activeLease=void 0,e.markReleased(),this.onReceiverChange?.()}dequeue(){let e=this.queue[this.head];if(this.queue[this.head]=void 0,this.head+=1,this.head===this.queue.length)this.queue=[],this.head=0;else if(this.head>=1024&&this.head*2>=this.queue.length)this.queue=this.queue.slice(this.head),this.head=0;return this.observer?.dequeued(e),e}}class Li{transport;limits;connectionId;inboundTx;outboundRx;connectionStream;allOutbound;sessionStreams=new Map;pendingRoutes=new Map;clientResponseRoutes=new Map;closed;agentConnection;bufferedBytes=0;streamObserver={queued:(e)=>{this.bufferedBytes+=e.length},dequeued:(e)=>{this.bufferedBytes-=e.length,this.notifyOutboundProgress()}};bufferedSessionStreams=0;progressWaiters=new Set;hasStartedRouter=!1;hasAgentOutputEnded=!1;hasFinishedRouting=!1;hasStartedShutdown=!1;inboundWriteChain=Promise.resolve();initialReader;outboundReader;routerPromise;shutdownPromise;hasResolvedClosed=!1;abortAgentInbound=()=>{};endAgentOutbound=()=>{};resolveClosed=()=>{};constructor(e,t,n){this.transport=t,this.limits=n,this.connectionId=globalThis.crypto.randomUUID(),this.connectionStream=new $r(t==="http",void 0,this.streamObserver),this.allOutbound=new $r(t==="websocket",void 0,{dequeued:()=>{this.notifyOutboundProgress()}}),this.closed=new Promise((s)=>{this.resolveClosed=s});let r=new TransformStream({start:(s)=>{this.abortAgentInbound=(a)=>s.error(a)}}),o=Py(()=>{this.hasAgentOutputEnded=!0,this.notifyOutboundProgress()});this.inboundTx=r.writable,this.outboundRx=o.readable,this.endAgentOutbound=o.end;let i={readable:r.readable,writable:o.writable};this.agentConnection=e.connect(i,{deferConnectHandlers:!0}),this.observeAgentConnection()}async recvInitial(e){let t=this.outboundRx.getReader();this.initialReader=t;try{let n=await t.read();if(n.done||!n.value||!Ly(n.value,e)){if(!this.shutdownPromise)await this.shutdown();throw Error("Expected initialize response from agent")}return n.value}finally{if(this.initialReader===t)this.initialReader=void 0;t.releaseLock()}}async writeInbound(e){let t=this.inboundWriteChain.then(()=>this.writeInboundMessage(e));this.inboundWriteChain=t.catch(()=>{return}),await t}startRouter(){if(this.hasStartedRouter)return;this.hasStartedRouter=!0,this.routerPromise=this.runRouter()}startConnectHandlers(){if(typeof this.agentConnection==="object"&&this.agentConnection!==null&&"startConnectHandlers"in this.agentConnection&&typeof this.agentConnection.startConnectHandlers==="function")this.agentConnection.startConnectHandlers()}get isClosed(){return this.hasStartedShutdown}get hasOutboundBacklog(){return this.transport==="http"?this.bufferedBytes>=this.limits.maxBufferedBytes:this.allOutbound.hasQueuedMessages}validateSessionId(e){this.validateIdLength("Session ID",e)}validateRequestId(e){if(typeof e==="string")this.validateIdLength("Request ID",e)}async waitForOutboundCapacity(e){await this.waitForRoom(()=>this.hasFinishedRouting,e)}ensureSession(e){if(this.validateSessionId(e),this.transport==="websocket")return this.connectionStream;let t=this.sessionStreams.get(e);if(t)return t;if(this.bufferedSessionStreams>=this.limits.maxBufferedSessionStreams)throw Er("maxBufferedSessionStreams",this.limits);return this.createSessionStream(e)}acquireSessionStream(e){if(this.validateSessionId(e),this.transport==="websocket")return;let t=this.sessionStreams.get(e);if(t)return t.tryAcquire();if(this.isClosed||this.hasFinishedRouting)throw new we;return this.createSessionStream(e).tryAcquire()}async shutdown(e){if(!this.shutdownPromise)this.shutdownPromise=this.runShutdown(e);return this.shutdownPromise}async runShutdown(e){try{this.hasStartedShutdown=!0,this.notifyOutboundProgress(),this.connectionStream.abort(e),this.allOutbound.abort(e);for(let t of this.sessionStreams.values())t.abort(e);this.sessionStreams.clear(),this.bufferedSessionStreams=0,this.pendingRoutes.clear(),this.clientResponseRoutes.clear(),await Promise.allSettled([this.closeInbound(e),this.cancelOutboundReader()])}finally{this.resolveClosedOnce()}}observeAgentConnection(){if(typeof this.agentConnection!=="object"||this.agentConnection===null||!("closed"in this.agentConnection)||!this.agentConnection.closed)return;Promise.resolve(this.agentConnection.closed).finally(async()=>{if(!this.hasStartedRouter){await this.shutdown();return}this.endAgentOutbound(),await this.routerPromise})}cancelOutboundReader(){let e=this.initialReader??this.outboundReader;if(e)return e.cancel();return this.outboundRx.cancel()}closeInbound(e){if(e!==void 0||this.inboundTx.locked)return this.abortAgentInbound(e??new we),Promise.resolve();return this.inboundTx.close()}async writeInboundMessage(e){if(this.isClosed||this.hasFinishedRouting)throw new we;let t=this.inboundTx.getWriter();try{await t.write(e)}catch(n){if(this.isClosed)throw new we;throw n}finally{t.releaseLock()}}async runRouter(){let e=this.outboundRx.getReader();this.outboundReader=e;try{while(!0){let t=await e.read();if(t.done||this.isClosed)return;this.routeOutbound(t.value),await this.waitForRoom(()=>this.hasAgentOutputEnded)}}catch(t){if(t instanceof ve)this.closeForLimit(t);else console.error(`ACP connection ${this.connectionId} router stopped unexpectedly:`,t),this.shutdown(t)}finally{if(this.hasFinishedRouting=!0,this.notifyOutboundProgress(),this.outboundReader===e)this.outboundReader=void 0;e.releaseLock(),this.connectionStream.finish(),this.allOutbound.finish();for(let t of this.sessionStreams.values())t.finish();this.resolveClosedOnce()}}resolveClosedOnce(){if(this.hasResolvedClosed)return;this.hasResolvedClosed=!0,this.resolveClosed()}async waitForRoom(e,t){while(!this.isClosed&&!e()&&this.hasOutboundBacklog)if(!await this.waitForProgress(t)){this.closeForLimit(Mi(this.limits));return}}waitForProgress(e){let t=this.transport==="http"?this.limits.maxOutputStallMs:void 0;return new Promise((n,r)=>{if(e?.aborted){r(e.reason);return}let o,i=()=>{this.progressWaiters.delete(s),e?.removeEventListener("abort",a),clearTimeout(o)},s=()=>{i(),n(!0)},a=()=>{i(),r(e?.reason)};if(this.progressWaiters.add(s),e?.addEventListener("abort",a,{once:!0}),t!==void 0)o=setTimeout(()=>{i(),n(!1)},t)})}notifyOutboundProgress(){for(let e of[...this.progressWaiters])e()}routeOutbound(e){this.routeOutboundMessage(e),this.allOutbound.push(e)}routeOutboundMessage(e){if(wt(e)){this.routeOutboundResponse(e);return}this.routeOutboundRequestOrNotification(e)}routeOutboundResponse(e){let t=je(e.id),n=t?this.pendingRoutes.get(t):void 0,r=tl(e);if(r)this.validateSessionId(r);if(t)this.pendingRoutes.delete(t);this.pushToRoute(n??"connection",e)}createSessionStream(e){let t=new $r(!0,()=>{this.onSessionReceiverChange(e,t)},this.streamObserver);return this.sessionStreams.set(e,t),this.bufferedSessionStreams+=1,t}onSessionReceiverChange(e,t){if(this.isClosed)return;if(t.hasReceiver){this.bufferedSessionStreams-=1;return}if(!t.hasQueuedMessages){this.sessionStreams.delete(e),t.abort();return}if(this.bufferedSessionStreams+=1,!this.hasFinishedRouting&&this.bufferedSessionStreams>this.limits.maxBufferedSessionStreams)this.closeForLimit(Er("maxBufferedSessionStreams",this.limits))}closeForLimit(e){console.warn(`Closing ACP connection ${this.connectionId}:`,e.message),this.shutdown(e)}validateIdLength(e,t){if(t.length>this.limits.maxIdLength)throw new ve(`${e} exceeds maxIdLength (${this.limits.maxIdLength})`)}routeOutboundRequestOrNotification(e){let t=el(e);if(t){let n=this.ensureSession(t);this.trackClientResponseRoute(e,{session:t}),this.deliver(n,e);return}this.trackClientResponseRoute(e,"connection"),this.deliver(this.connectionStream,e)}trackClientResponseRoute(e,t){if(!("id"in e)||!("method"in e))return;let n=je(e.id);if(n)this.clientResponseRoutes.set(n,t)}pushToRoute(e,t){if(e==="connection"){this.deliver(this.connectionStream,t);return}this.deliver(this.ensureSession(e.session),t)}deliver(e,t){if(this.transport==="http")e.push(JSON.stringify(t))}}class Di{limits;connections=new Map;pendingConnections=new Map;constructor(e={}){this.limits=Ny(e)}createConnection(e,t="http"){let n=new Li(e,t,this.limits);return this.connections.set(n.connectionId,n),this.trackConnectionClose(n),n}createPendingConnection(e,t="websocket"){let n=new Li(e,t,this.limits);return this.pendingConnections.set(n.connectionId,n),this.trackConnectionClose(n),n}register(e){this.pendingConnections.delete(e.connectionId),this.connections.set(e.connectionId,e)}get(e){let t=this.connections.get(e);return t?.isClosed?void 0:t}remove(e){let t=this.connections.get(e);if(!t)return;return this.connections.delete(e),t.shutdown(),t}discard(e){let t=this.connections.get(e)??this.pendingConnections.get(e);if(!t)return;return this.connections.delete(e),this.pendingConnections.delete(e),t.shutdown(),t}async closeAll(){let e=new Set([...this.connections.values(),...this.pendingConnections.values()]);this.connections.clear(),this.pendingConnections.clear(),await Promise.all(Array.from(e,(t)=>t.shutdown()))}trackConnectionClose(e){e.closed.then(()=>{if(this.connections.get(e.connectionId)===e)this.connections.delete(e.connectionId);if(this.pendingConnections.get(e.connectionId)===e)this.pendingConnections.delete(e.connectionId)})}}function Ny(e){let t={maxBufferedBytes:e.maxBufferedBytes??dl,maxOutputStallMs:e.maxOutputStallMs??fl,maxBufferedSessionStreams:e.maxBufferedSessionStreams??pl,maxIdLength:e.maxIdLength??ml};for(let[n,r]of Object.entries(t))if(!Number.isSafeInteger(r)||r<=0)throw RangeError(`${n} must be a positive safe integer`);if(t.maxOutputStallMs>ll)throw RangeError(`maxOutputStallMs must be at most ${ll}`);return t}class hl{mailbox;released=!1;stoppedController=new AbortController;receiving=!1;wakePromise;resolveWake;constructor(e){this.mailbox=e}get stopped(){return this.stoppedController.signal}async receive(){if(this.receiving)throw Error("ACP outbound mailbox lease already has a pending receive");this.receiving=!0;try{return await this.mailbox.receive(this)}finally{this.receiving=!1}}release(){this.mailbox.release(this)}wake(){this.resolveWake?.(),this.wakePromise=void 0,this.resolveWake=void 0}wait(){if(!this.wakePromise)this.wakePromise=new Promise((e)=>{this.resolveWake=e});return this.wakePromise}markReleased(){this.released=!0,this.wake()}stop(e){this.stoppedController.abort(e),this.wake()}}function Py(e){let t,n=!1,r=!1,o,i=()=>{let d=o;o=void 0,d?.()},s=()=>{if(n)return;n=!0;try{t?.close()}catch{}i(),e()},a=(d)=>{if(n)return;n=!0;try{t?.error(d)}catch{}i(),e()},u=()=>{if(n||r)return;r=!0,i(),setTimeout(s,0)};return{readable:new ReadableStream({start(d){t=d},pull:i,cancel(){n=!0,i()}},{highWaterMark:0}),writable:new WritableStream({async write(d){if(n)throw Error("ACP outbound channel is closed");try{t?.enqueue(d)}catch(p){throw a(p),p}if(!n&&!r&&(t?.desiredSize??0)<0)await new Promise((p)=>{o=p})},close:s,abort:a}),end:u}}function Ly(e,t){return"id"in e&&!("method"in e)&&e.id===t}var dl=67108864,fl=60000,pl=1024,ml=1024,ll=2147483647,ve,we;var Ir=v(()=>{ge();_n();ve=class ve extends Error{constructor(e){super(e);this.name="ConnectionLimitError"}};we=class we extends Error{constructor(){super("ACP connection is closed");this.name="ConnectionClosedError"}}});var Cr;var ji=v(()=>{Cr={initialize:"initialize",authenticate:"authenticate",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",session_list:"session/list",session_delete:"session/delete",session_resume:"session/resume",session_close:"session/close",logout:"logout"}});var zn=()=>{};var Ui=v(()=>{zn()});function wl(e){return`data: ${e}
7
7
 
8
- `}function Xu(){return`:
8
+ `}function _l(){return`:
9
9
 
10
- `}var qI,HI;var Qu=S(()=>{ge();Ii();mn();qI=new TextEncoder().encode("data:"),HI=new Uint8Array([10])});function el(e){return new ReadableStream(dy(e),{highWaterMark:0})}function dy(e){let t=new TextEncoder,n,r=!1,o=!1,i=!1,s=()=>{if(n)clearInterval(n),n=void 0},a=(w,b)=>{r=!1;try{return w.enqueue(t.encode(b)),!0}catch{return!1}},l=(w)=>{if(i)return;i=!0,s(),e.release();try{w.close()}catch{}},d=(w,b)=>{if(i)return;i=!0,s(),e.release(),w.error(b)},f=(w)=>{if(e.stopped.aborted&&!r)d(w,e.stopped.reason)},g=async(w)=>{if(o)return;o=!0;try{while(r&&!i){let b=await e.receive();if(i)return;if(b.done){l(w);return}if(!a(w,Yu(b.value))){l(w);return}f(w)}}catch(b){d(w,b)}finally{o=!1}};return{start(w){e.stopped.addEventListener("abort",()=>{f(w)},{once:!0}),n=setInterval(()=>{if(i||!r)return;if(!a(w,Xu()))l(w)},15000)},pull(w){r=!0,g(w)},cancel(){i=!0,s(),e.release()}}}var tl=S(()=>{Qu()});function Sr(e,t,n){if(e.on){let r=(...o)=>{n(...py(t,o))};return e.on(t,r),()=>{if(e.off){e.off(t,r);return}e.removeListener?.(t,r)}}if(e.addEventListener){let r=(o)=>n(o);return e.addEventListener(t,r),()=>{e.removeEventListener?.(t,r)}}throw Error("WebSocket object does not support event listeners")}function nl(e){let t=my(e);if(typeof t==="string")return t;return}function py(e,t){if(e!=="message"||typeof t[1]!=="boolean")return t;if(t[1])return[void 0];return[fy(t[0])]}function fy(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e);if(ArrayBuffer.isView(e))return new TextDecoder().decode(e);if(gy(e))return wy(e);return}function my(e){let[t]=e;if(hy(t))return t.data;return t}function hy(e){return typeof e==="object"&&e!==null&&"data"in e}function gy(e){return Array.isArray(e)&&e.every(ArrayBuffer.isView)}function wy(e){let t=e.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength),r),r+=o.byteLength;return new TextDecoder().decode(n)}function il(e,t){let n=new sl(e,t);return n.start(),n}class sl{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();waitingInboundBytes=0;isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,t){this.socket=e,this.options=t,this.preparedConnection=t.connection,this.closedPromise=new Promise((n)=>{this.resolveClosed=n})}get closed(){return this.closedPromise}start(){this.detachListeners.push(Sr(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(Sr(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(Sr(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,t="Server shutting down"){return this.shutdown(e,t)}enqueueSocketMessage(e){if(this.isClosed)return;let t=nl(e);if(t===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let n=t.length+yy,{limits:r}=this.options.registry;if(this.waitingInboundBytes>0&&n>r.maxBufferedBytes-this.waitingInboundBytes){this.closeForLimit(zr("maxBufferedBytes",r));return}this.waitingInboundBytes+=n;let o=this.messageChain.then(()=>(this.waitingInboundBytes-=n,this.handleSocketMessage(t)));this.messageChain=o.catch((i)=>{if(this.isClosed||i instanceof we)return;if(i instanceof ve){this.closeForLimit(i);return}console.error("ACP WebSocket message handling failed:",i),this.shutdown(1011,"Message handling failed")})}async handleSocketMessage(e){if(this.isClosed)return;let t;try{t=JSON.parse(e)}catch{await this.waitForSocketCapacity(),this.send(Se(T.parseError()));return}if(!Array.isArray(t)&&!ee(t)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(t)));return}if(Array.isArray(t)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported")));return}let n=t;if(!this.connection){if(an(n))return;if(!pt(n)&&!mt(n)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(n)));return}await this.handleInitialize(n);return}let r=await this.forwardMessage(n);if(!r.ok)console.warn("Ignoring ACP WebSocket message:",r.message)}async handleInitialize(e){if(!ln(e)){console.warn("First ACP WebSocket message must be initialize"),await this.shutdown(1002,"First message must be initialize");return}if(!("id"in e)||e.id===null){console.warn("ACP WebSocket initialize request must include an ID"),await this.shutdown(1002,"Initialize request must include an ID");return}let t=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=t;try{await rl(t,e);let n=await t.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(t.connectionId);return}this.preparedConnection=void 0,this.connection=t,this.options.registry.register(t),t.startRouter(),t.startConnectHandlers(),this.send(n),this.startOutboundPump(t)}catch(n){this.preparedConnection=void 0,this.options.registry.discard(t.connectionId);let r={jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:n instanceof Error?n.message:void 0}};this.send(r),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let t=this.connection;if(!t)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(pt(e)&&ln(e))return await this.waitForSocketCapacity(),this.send({jsonrpc:"2.0",id:e.id,error:{code:-32600,message:"Initialize not allowed on existing connection"}}),{ok:!1,message:"Initialize not allowed on existing connection"};return this.trackInboundRoutes(e),await this.forwardToAgent(t,e)}async forwardToAgent(e,t){if(zy(t))await e.waitForOutboundCapacity(),await this.waitForSocketCapacity();return await this.writeInbound(t),{ok:!0}}async waitForSocketCapacity(){let{limits:e}=this.options.registry,t=_y,n=this.socket.bufferedAmount??0,r=0;while(!this.isClosed&&n>=e.maxBufferedBytes){if(r>=e.maxOutputStallMs){this.closeForLimit(vi(e));return}await new Promise((i)=>setTimeout(i,t)),r+=t,t=Math.min(t*2,by);let o=n;if(n=this.socket.bufferedAmount??0,n<o)r=0}}trackInboundRoutes(e){let t=this.connection;if(!t)return;if(pt(e)){let n=ol(e);if(n!=="connection")t.validateSessionId(n.session);t.validateRequestId(e.id);let r=Me(e.id);if(r)t.pendingRoutes.set(r,e.method===kr.session_load?"connection":n);return}if(mt(e)){let n=ol(e);if(n!=="connection")t.validateSessionId(n.session);return}if(an(e)){let n=e.id,r=n===null||typeof n==="string"||typeof n==="number"&&Number.isFinite(n)?Me(n):void 0;if(r)t.clientResponseRoutes.delete(r)}}async writeInbound(e){let t=this.connection;if(!t)throw Error("ACP WebSocket connection is not initialized");let n=this.inboundWriteChain.then(()=>rl(t,e));this.inboundWriteChain=n.catch(()=>{return}),await n}startOutboundPump(e){let t=e.allOutbound.tryAcquire();if(!t){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=t,t.stopped.addEventListener("abort",()=>{this.closeForStoppedConnection(t.stopped.reason)},{once:!0}),(async()=>{try{while(!this.isClosed){let n=await t.receive();if(n.done)return;if(!this.send(n.value))return;await this.waitForSocketCapacity()}}catch(n){if(!t.stopped.aborted)console.error("ACP WebSocket outbound pump failed:",n);await this.closeForStoppedConnection(n)}finally{if(this.outboundLease===t)this.outboundLease=void 0;if(t.release(),!this.isClosed)this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(t){return console.warn("Failed to send ACP WebSocket message:",t),this.shutdown(1011,"Failed to send message"),!1}}closeForLimit(e){let t=this.connection?.connectionId??this.preparedConnection?.connectionId,n=t?`ACP connection ${t}`:"ACP connection";console.warn(`Closing ${n}:`,e.message),this.shutdown(1008,e.message)}async closeForStoppedConnection(e){if(this.isClosed)return;if(e instanceof ve)await this.shutdown(1008,e.message);else if(e instanceof we)await this.shutdown();else await this.shutdown(1011,"Internal error")}async shutdownIfUninitialized(e,t){if(this.connection)return;await this.shutdown(e,t)}async shutdown(e,t){this.closeSocket(e,t),await this.closeSession()}closeSocket(e,t){try{this.socket.close(e,t)}catch(n){console.warn("Failed to close ACP WebSocket:",n)}}async closeSession(){if(this.isClosed)return;this.isClosed=!0;try{for(let t of this.detachListeners.splice(0))t();let e=this.outboundLease;if(this.outboundLease=void 0,e?.release(),this.connection)this.options.registry.discard(this.connection.connectionId),this.connection=void 0;if(this.preparedConnection)this.options.registry.discard(this.preparedConnection.connectionId),this.preparedConnection=void 0}finally{this.resolveClosed()}}}async function rl(e,t){await e.writeInbound(t)}function ol(e){let t=un(e.params);if(t)return{session:t};return"connection"}function zy(e){return!mt(e)&&!an(e)}var _y=10,by=1000,yy=1024;var al=S(()=>{ge();dn();Ei();xr()});class Ti{agent;registry;webSocketSessions=new Set;constructor(e){this.agent=ll(e),this.registry=new $i(e)}async handleRequest(e,t={}){try{if(e.method==="POST")return await this.handlePost(e,t);if(e.method==="GET")return this.handleGet(e);if(e.method==="DELETE")return this.handleDelete(e);return V("Method Not Allowed",405)}catch(n){if(n instanceof ve)return V(n.message,400);if(n instanceof we)return V("Unknown Acp-Connection-Id",404);if(n instanceof ht)return V("Request aborted",499);throw n}}prepareWebSocketUpgrade(e={}){let t=cl(e,this.agent),n=this.registry.createPendingConnection(t),r=!1;return{connectionId:n.connectionId,accept:(o)=>{if(r)throw Error("ACP WebSocket upgrade has already been settled");r=!0;let i=il(o,{registry:this.registry,agent:t,connection:n});this.webSocketSessions.add(i),i.closed.finally(()=>{this.webSocketSessions.delete(i)})},reject:()=>{if(r)return;r=!0,this.registry.discard(n.connectionId)}}}async close(){let e=this.registry.closeAll(),t=Promise.all(Array.from(this.webSocketSessions,(n)=>n.close()));await Promise.all([e,t])}async handlePost(e,t){let n=e.headers.get("Content-Type");if(!Ty(n))return V("Unsupported Media Type",415);let r=await ky(e);if(!r.ok)return V("Invalid JSON",400);if(Array.isArray(r.value))return Ci(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported")),400);if(!ee(r.value))return V("Invalid JSON-RPC message",400);let o=r.value,i=e.headers.get(Dt);if(ln(o)){if(!i)return await this.handleInitialize(o,e.signal,t);return V("Initialize not allowed on existing connection",400)}if(!i)return V("Missing Acp-Connection-Id",400);let s=this.registry.get(i);if(!s)return V("Unknown Acp-Connection-Id",404);let a=await this.forwardConnectedMessage(s,o,e.headers,e.signal);if(!a.ok)return V(a.message,a.status);return ul(202)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return V("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(xi))return V("Not Acceptable",406);let n=e.headers.get(Dt);if(!n)return V("Missing Acp-Connection-Id",400);let r=this.registry.get(n);if(!r)return V("Unknown Acp-Connection-Id",404);let o=e.headers.get(br),i=o?r.acquireSessionStream(o):r.connectionStream.tryAcquire();if(!i)return V("Outbound stream already has an active receiver",409);return Ay(i)}handleDelete(e){let t=e.headers.get(Dt);if(!t)return V("Missing Acp-Connection-Id",400);if(!this.registry.remove(t))return V("Unknown Acp-Connection-Id",404);return ul(202)}async handleInitialize(e,t,n){if(!("id"in e)||e.id===null)return V("Initialize request must include an ID",400);if(t.aborted)return V("Request aborted",499);let r;try{r=this.registry.createConnection(cl(n,this.agent));let o=Sy(r,e);o.catch(()=>{return});let i=await vy(o,t);if(t.aborted)throw new ht;return r.startRouter(),r.startConnectHandlers(),Ci(i,200,{[Dt]:r.connectionId})}catch(o){if(r)this.registry.remove(r.connectionId);if(o instanceof ht)return V("Request aborted",499);return Ci({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:o instanceof Error?o.message:void 0}},500)}}async forwardConnectedMessage(e,t,n,r){if(ft(t))return await Ey(e,t,n);return await $y(e,t,n,r)}}function cl(e,t){if(dl(e),!xy(e))return t;return ll(e)}function xy(e){return Boolean(e.agent||e.createAgent)}function ll(e){if(dl(e),(e.agent?1:0)+(e.createAgent?1:0)!==1)throw Error("AcpServer requires exactly one of agent or createAgent");if(e.agent)return e.agent;return{connect:(n,r)=>e.createAgent().connect(n,r??{})}}function dl(e){if("createLegacyAgent"in e)throw Error("createLegacyAgent has been removed. Use agent or createAgent with an app.")}async function ky(e){try{return{ok:!0,value:await e.json()}}catch{return{ok:!1}}}async function Ai(e,t){await e.writeInbound(t)}async function Sy(e,t){if(await Ai(e,t),!("id"in t)||t.id===null)throw Error("Initialize request must include an ID");return await e.recvInitial(t.id)}async function vy(e,t){if(t.aborted)throw new ht;let n=()=>{},r=new Promise((o,i)=>{let s=()=>{i(new ht)};t.addEventListener("abort",s,{once:!0}),n=()=>{t.removeEventListener("abort",s)}});try{return await Promise.race([e,r])}finally{n()}}async function $y(e,t,n,r){let o=Cy(t,n);if(!o.ok)return o;if(o.value!=="connection")e.validateSessionId(o.value.session);if(!mt(t))e.validateRequestId(t.id),await e.waitForOutboundCapacity(r).catch((s)=>{throw r.aborted?new ht:s});let i=pt(t)?Me(t.id):void 0;if(i)e.pendingRoutes.set(i,Iy(t,o.value));return await Ai(e,t),{ok:!0}}async function Ey(e,t,n){let r=Me(t.id),o=r?e.clientResponseRoutes.get(r):void 0,i=n.get(br);if(o&&o!=="connection"&&!i)return{ok:!1,status:400,message:"Missing Acp-Session-Id"};if(o&&o!=="connection"&&i!==o.session)return{ok:!1,status:400,message:"Mismatched Acp-Session-Id"};if(r)e.clientResponseRoutes.delete(r);return await Ai(e,t),{ok:!0}}function Iy(e,t){return e.method===kr.session_load?"connection":t}function Cy(e,t){let n=t.get(br),r=un(e.params);if((Ou(e.method)||r!==void 0)&&!n)return{ok:!1,status:400,message:"Missing Acp-Session-Id"};if(n!==null&&r!==void 0&&n!==r)return{ok:!1,status:400,message:"Mismatched Acp-Session-Id"};if(n)return{ok:!0,value:{session:n}};if(r)return{ok:!0,value:{session:r}};return{ok:!0,value:"connection"}}function Ty(e){return e?.split(";",1)[0]?.trim().toLowerCase()===ki}function Ay(e){return new Response(el(e),{status:200,headers:{"Content-Type":xi,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function Ci(e,t,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":ki,...n}})}function V(e,t){return new Response(e,{status:t,headers:{"Content-Type":"text/plain"}})}function ul(e){return new Response(null,{status:e})}var ht;var pl=S(()=>{xr();dn();ge();Ei();tl();al();xr();ht=class ht extends Error{constructor(){super("Request aborted");this.name="RequestAbortedError"}}});function wn(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function Oi(e,t="|"){return e.map((n)=>Li(n)).join(t)}function _n(e,t){if(typeof t==="bigint")return t.toString();return t}class fl{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function vr(e){return new fl(e)}function ml(e){return e===null||e===void 0}function $r(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function hl(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function _e(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Er(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function je(e){return Er(e._zod.def)??e._zod.def.shape}function gl(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return _e(this,t,r),r},enumerable:!0,configurable:!0})}function wl(e,t,n){if(t in e)_e(e,t,n);else e[t]=n}function gt(e,t,n,r){let o=je(t);for(let i of n){let s=Object.getOwnPropertyDescriptor(o,i);if(!s.enumerable)continue;if(s.get)gl(e,i,()=>{let a=t._zod.def.shape[i];return r?r(a,i):a});else wl(e,i,r?r(s.value,i):s.value)}}function Ry(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)gl(e,n,()=>t[n]);else wl(e,n,r.value)}}function se(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function _l(e){return JSON.stringify(e)}function bl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function gn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function wt(e){if(gn(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(gn(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Pi(e){if(wt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function Je(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function v(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Li(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function xl(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function Oy(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return gt(i,e,Cr(e,t)),be(e,se(n,{shape:i,checks:[]}))}function Cr(e,t){let n=je(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function Ny(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(Cr(e,t)),s={};return gt(s,e,Reflect.ownKeys(je(e)).filter((a)=>!i.has(a))),be(e,se(n,{shape:s,checks:[]}))}function Py(e,t){if(!wt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=je(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return be(e,se(e._zod.def,{shape:kl(e,t)}))}function kl(e,t){let n={};return gt(n,e,Reflect.ownKeys(je(e))),Ry(n,t),n}function Ly(e,t){if(!wt(t))throw Error("Invalid input to safeExtend: expected a plain object");return be(e,se(e._zod.def,{shape:kl(e,t)}))}function Dy(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};gt(n,e,Reflect.ownKeys(je(e))),gt(n,t,Reflect.ownKeys(je(t)));let r=se(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return be(e,r)}function Sl(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Cr(t,n)):void 0,l={};return gt(l,t,Reflect.ownKeys(je(t)),e&&((d,f)=>a&&!a.has(f)?d:new e({type:"optional",innerType:d}))),be(t,se(t._zod.def,{shape:l,checks:[]}))}function My(e,t,n){let r=n?new Set(Cr(t,n)):void 0,o={};return gt(o,t,Reflect.ownKeys(je(t)),(i,s)=>r&&!r.has(s)?i:new e({type:"nonoptional",innerType:i})),be(t,se(t._zod.def,{shape:o}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function vl(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ye(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function hn(e){return typeof e==="string"?e:e?.message}function Mi(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let o=r.maximum??r.length??r.size;if(o>=0)t.push([o,n])}return t}function Tr(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function Ee(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:hn(e.inst?._zod.def?.error?.(e))??hn(i?.(e))??hn(t?.error?.(e))??hn(n.customError?.(e))??hn(n.localeError?.(e))??"Invalid input",a={};for(let l of Object.keys(e)){if(l==="inst"||l==="schema"||l==="continue"||l==="input"||l==="__proto__")continue;a[l]=e[l]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}function Ar(e){let t=e.length;if(!jy.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function Rr(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function $l(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function _t(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function El(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else Uy(e,n,r.value)}}function Ue(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Or(e,t,n){return Ue(e,t,n,!1)}function Il(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Ue(this,n,r(this))},set(o){Ue(this,n,o)}})}return t}function Uy(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Ue(this,t,n.bind(this))},set(r){Ue(this,t,r)}})}function Zy(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}function P(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Ri!==e._zod){Ri=void 0;return}Ri=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,By);let o=Ke;Ke=!1;try{let i=n(this);if(Ke)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return Ke=Ke||o,i}catch(i){throw delete this[t],Ke=Ke||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Fy(e,t,n,r){let o=Zy(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:i})}})}function Cl(e){let t=()=>e;return t[Vy]=!0,t}var Ni,yl,zl,Ir,Di,jy,Ri,Ke=!1,By,Vy="~constantCatch";var re=S(()=>{bt();Ni="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};yl=vr(()=>{if(oe.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});zl=new Set(["string","number","symbol"]);Ir=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Di={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};jy=/[\uD800-\uDBFF]/;By={configurable:!0,get(){Ke=!0;return}}});function qy(e){let t=Al;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return Al=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let o={};function i(w){this.def=w,this.constr=g,this.traits=new Set}i.prototype=o;let s=n,a=s&&new WeakSet;function l(w,b){if(!w._zod){ji.value=new i(b);try{Object.defineProperty(w,"_zod",ji)}finally{ji.value=void 0}}else if(w._zod.traits.has(e))return;if(w._zod.traits.add(e),t(w,b),a){let I=Object.getPrototypeOf(w),E=w._zod.constr.prototype,A=I;while(A&&A!==E)A=Object.getPrototypeOf(A);let X=A??I;if(!a.has(X))a.add(X),El(X,s)}let z=g.prototype;for(let I in z){if(!Object.prototype.hasOwnProperty.call(z,I))continue;if(!(I in w))w[I]=z[I].bind(w)}}let d=r?.Parent??Object;class f extends d{}Object.defineProperty(f,"name",{value:e});function g(w){let b=r?.Parent?qy(f):this;l(b,w);let z=b._zod.deferred;if(z){for(let E of z)E();b._zod.deferred=void 0}let I=globalThis.__zod_globalConfig?.postProcessor;if(I)I(b);return b}return Object.defineProperty(g,"init",{value:l}),Object.defineProperty(g,Symbol.hasInstance,{value:(w)=>{if(r?.Parent&&w instanceof r.Parent)return!0;return w?._zod?.traits?.has(e)}}),Object.defineProperty(g,"name",{value:e}),g}function ie(e){if(e)Object.assign(oe,e);return oe}var Tl,Nr,ji,Al,Ie,bn,oe;var bt=S(()=>{re();Nr=Object.freeze({status:"aborted"}),ji={value:void 0,enumerable:!1},Al="captureStackTrace"in Error?Error:null;Ie=class Ie extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};bn=class bn extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(Tl=globalThis).__zod_globalConfig??(Tl.__zod_globalConfig={});oe=globalThis.__zod_globalConfig});function Hy(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,_n,2)),e.message}function Gy(e){this._zod.message=e}function Ky(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function Bi(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)Ky(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function Fi(e,t=(n)=>n.message){let n={_errors:[]},r=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>r({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)n._errors.push(t(s));else{let l=n,d=0;while(d<a.length){let f=a[d],g=d===a.length-1;if(f==="_errors"){if(g)l._errors.push(t(s));d++;continue}if(!Object.prototype.hasOwnProperty.call(l,f))Object.defineProperty(l,f,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let w=l[f];if(g)w._errors.push(t(s));l=w,d++}}}};return r(e),n}var Wy,Zi,Rl,Ol=(e,t)=>{e.name="$ZodError",Zi.value=t,Object.defineProperty(e,"issues",Zi),Zi.value=void 0,Object.defineProperty(e,"message",Wy);let n=Object.getPrototypeOf(e);if(!Rl.has(n))Rl.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},Nl,mC;var Pl=S(()=>{bt();re();Wy={get:Hy,set:Gy,enumerable:!0,configurable:!0},Zi={value:void 0,enumerable:!1},Rl=new WeakSet([Object.prototype,Error.prototype]),Nl=y("$ZodError",Ol),mC=y("$ZodError",Ol,void 0,{Parent:Error})});function Pr(e,t){return{callee:t?.callee??e,Err:t?.Err}}function Ll(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>Ee(o,n,ie()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}function Xy(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,i;if(o)r[Yy]=!0,i=o({value:t,issues:[]},r);else i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)throw new Ie;return i.issues.length===0}var Lr=(e)=>{let t=(n,r,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Ie;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((d)=>Ee(d,s,ie())));throw Ni(l,i?.callee??t),l}return a.value};return t},Dr=(e)=>{let t=async(n,r,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let l=new(i?.Err??e)(a.issues.map((d)=>Ee(d,s,ie())));throw Ni(l,i?.callee??t),l}return a.value};return t},Mr=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ie;return i.issues.length?Ll(e,i.issues,o):{success:!0,data:i.value}},jr=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?Ll(e,i.issues,o):{success:!0,data:i.value}},Jy,Yy,Vi=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Jy)return!0;if(r.definite===!0&&n===void 0)return!1}return Xy(e,t,n)},qi=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},Dl=(e)=>{let t=Lr(e),n=(r,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,o,a,Pr(n,s))};return n},Ml=(e)=>{let t=Lr(e),n=(r,o,i,s)=>t(r,o,i,Pr(n,s));return n},jl=(e)=>{let t=Dr(e),n=async(r,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,o,a,Pr(n,s))};return n},Ul=(e)=>{let t=Dr(e),n=async(r,o,i,s)=>await t(r,o,i,Pr(n,s));return n},Zl=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Mr(e)(t,n,o)},Bl=(e)=>(t,n,r)=>Mr(e)(t,n,r),Fl=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return jr(e)(t,n,o)},Vl=(e)=>async(t,n,r)=>jr(e)(t,n,r);var ql=S(()=>{bt();re();Jy=Symbol.for("zod.compile.invalid"),Yy=Symbol.for("zod.compile.fallback")});function Xl(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function nd(){return new RegExp(Qy,"u")}function ez(e){return new RegExp(`^${e}$`)}function Hi(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function fd(e){return new RegExp(`^${Hi(e)}$`)}function md(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${Hi({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${Hi({precision:e.precision})}`:n;return new RegExp(`^${dd}T(?:${r})$`)}var Hl,Gl,Wl,Kl,Jl,Yl,Ql,ed,Gi=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},td,Qy="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",rd,od,id,sd,ad,cd,ud,ld,dd="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",pd,hd,Wi,yn,gd,wd,_d,bd;var zn=S(()=>{Hl=/^[cC][0-9a-z]{6,}$/,Gl=/^[0-9a-z]+$/,Wl=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Kl=/^[0-9a-vA-V]{20}$/,Jl=/^[A-Za-z0-9]{27}$/,Yl=/^[a-zA-Z0-9_-]{21}$/;Ql=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ed=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,td=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;rd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,od=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,id=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,sd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ad=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,cd=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,ud=/^https?$/,ld=/^\+[1-9]\d{6,14}$/;pd=ez(dd);hd=/^[\s\S]{0,}$/,Wi=/^-?\d+$/,yn=/^-?\d+(?:\.\d+)?$/,gd=/^(?:true|false)$/i,wd=/^null$/i,_d=/^[^A-Z]*$/,bd=/^[^a-z]*$/});var J,Ki=(e)=>{let t=e.value;return!ml(t)&&t.length!==void 0},Ur,Ji,Yi,yd,zd,xd,kd,Sd,xn,vd,$d,Ed,Id,Cd,Td,Ad;var Zr=S(()=>{bt();zn();re();J=y("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ur={number:"number",bigint:"bigint",object:"date"},Ji=y("$ZodCheckLessThan",(e,t)=>{J.init(e,t);let n=Ur[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:Ur[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Yi=y("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);let n=Ur[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:Ur[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),yd=y("$ZodCheckMultipleOf",(e,t)=>{J.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):hl(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),zd=y("$ZodCheckNumberFormat",(e,t)=>{J.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Ir[t.format];e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),xd=y("$ZodCheckMaxLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=Ki),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>t.maximum?Ar(o):i)<=t.maximum)return;let a=Rr(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),kd=y("$ZodCheckMinLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=Ki),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>=t.minimum&&i<t.minimum*2?Ar(o):i)>=t.minimum)return;let a=Rr(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Sd=y("$ZodCheckLengthEquals",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=Ki),e._zod.check=(r)=>{let o=r.value,i=o.length,s=typeof o==="string"&&i>=t.length&&i<=t.length*2?Ar(o):i;if(s===t.length)return;let a=Rr(o),l=s>t.length;r.issues.push({origin:a,...l?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),xn=y("$ZodCheckStringFormat",(e,t)=>{var n,r;if(J.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),vd=y("$ZodCheckRegex",(e,t)=>{xn.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),$d=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=_d),xn.init(e,t)}),Ed=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=bd),xn.init(e,t)}),Id=y("$ZodCheckIncludes",(e,t)=>{J.init(e,t);let n=Je(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Cd=y("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`^${Je(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Td=y("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`.*${Je(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Ad=y("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}})});class Xi{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
10
+ `}var jC,UC;var bl=v(()=>{ge();Ui();zn();jC=new TextEncoder().encode("data:"),UC=new Uint8Array([10])});function yl(e){return new ReadableStream(Zy(e),{highWaterMark:0})}function Zy(e){let t=new TextEncoder,n,r=!1,o=!1,i=!1,s=()=>{if(n)clearInterval(n),n=void 0},a=(w,b)=>{r=!1;try{return w.enqueue(t.encode(b)),!0}catch{return!1}},u=(w)=>{if(i)return;i=!0,s(),e.release();try{w.close()}catch{}},d=(w,b)=>{if(i)return;i=!0,s(),e.release(),w.error(b)},p=(w)=>{if(e.stopped.aborted&&!r)d(w,e.stopped.reason)},g=async(w)=>{if(o)return;o=!0;try{while(r&&!i){let b=await e.receive();if(i)return;if(b.done){u(w);return}if(!a(w,wl(b.value))){u(w);return}p(w)}}catch(b){d(w,b)}finally{o=!1}};return{start(w){e.stopped.addEventListener("abort",()=>{p(w)},{once:!0}),n=setInterval(()=>{if(i||!r)return;if(!a(w,_l()))u(w)},15000)},pull(w){r=!0,g(w)},cancel(){i=!0,s(),e.release()}}}var zl=v(()=>{bl()});function Tr(e,t,n){if(e.on){let r=(...o)=>{n(...By(t,o))};return e.on(t,r),()=>{if(e.off){e.off(t,r);return}e.removeListener?.(t,r)}}if(e.addEventListener){let r=(o)=>n(o);return e.addEventListener(t,r),()=>{e.removeEventListener?.(t,r)}}throw Error("WebSocket object does not support event listeners")}function xl(e){let t=Vy(e);if(typeof t==="string")return t;return}function By(e,t){if(e!=="message"||typeof t[1]!=="boolean")return t;if(t[1])return[void 0];return[Fy(t[0])]}function Fy(e){if(typeof e==="string")return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(e);if(ArrayBuffer.isView(e))return new TextDecoder().decode(e);if(Hy(e))return Gy(e);return}function Vy(e){let[t]=e;if(qy(t))return t.data;return t}function qy(e){return typeof e==="object"&&e!==null&&"data"in e}function Hy(e){return Array.isArray(e)&&e.every(ArrayBuffer.isView)}function Gy(e){let t=e.reduce((o,i)=>o+i.byteLength,0),n=new Uint8Array(t),r=0;for(let o of e)n.set(new Uint8Array(o.buffer,o.byteOffset,o.byteLength),r),r+=o.byteLength;return new TextDecoder().decode(n)}function vl(e,t){let n=new $l(e,t);return n.start(),n}class $l{socket;options;connection;preparedConnection;outboundLease;inboundWriteChain=Promise.resolve();messageChain=Promise.resolve();waitingInboundBytes=0;isClosed=!1;closedPromise;resolveClosed=()=>{};detachListeners=[];constructor(e,t){this.socket=e,this.options=t,this.preparedConnection=t.connection,this.closedPromise=new Promise((n)=>{this.resolveClosed=n})}get closed(){return this.closedPromise}start(){this.detachListeners.push(Tr(this.socket,"message",(...e)=>{this.enqueueSocketMessage(e)})),this.detachListeners.push(Tr(this.socket,"close",()=>{this.closeSession()})),this.detachListeners.push(Tr(this.socket,"error",()=>{this.shutdown(1011,"WebSocket error")}))}close(e=1001,t="Server shutting down"){return this.shutdown(e,t)}enqueueSocketMessage(e){if(this.isClosed)return;let t=xl(e);if(t===void 0){console.warn("Ignoring non-text ACP WebSocket frame");return}let n=t.length+Jy,{limits:r}=this.options.registry;if(this.waitingInboundBytes>0&&n>r.maxBufferedBytes-this.waitingInboundBytes){this.closeForLimit(Er("maxBufferedBytes",r));return}this.waitingInboundBytes+=n;let o=this.messageChain.then(()=>(this.waitingInboundBytes-=n,this.handleSocketMessage(t)));this.messageChain=o.catch((i)=>{if(this.isClosed||i instanceof we)return;if(i instanceof ve){this.closeForLimit(i);return}console.error("ACP WebSocket message handling failed:",i),this.shutdown(1011,"Message handling failed")})}async handleSocketMessage(e){if(this.isClosed)return;let t;try{t=JSON.parse(e)}catch{await this.waitForSocketCapacity(),this.send(Se(T.parseError()));return}if(!Array.isArray(t)&&!Q(t)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(t)));return}if(Array.isArray(t)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported")));return}let n=t;if(!this.connection){if(mn(n))return;if(!gt(n)&&!_t(n)){await this.waitForSocketCapacity(),this.send(Se(T.invalidRequest(n)));return}await this.handleInitialize(n);return}let r=await this.forwardMessage(n);if(!r.ok)console.warn("Ignoring ACP WebSocket message:",r.message)}async handleInitialize(e){if(!wn(e)){console.warn("First ACP WebSocket message must be initialize"),await this.shutdown(1002,"First message must be initialize");return}if(!("id"in e)||e.id===null){console.warn("ACP WebSocket initialize request must include an ID"),await this.shutdown(1002,"Initialize request must include an ID");return}let t=this.preparedConnection??this.options.registry.createPendingConnection(this.options.agent);this.preparedConnection=t;try{await kl(t,e);let n=await t.recvInitial(e.id);if(this.isClosed){this.options.registry.discard(t.connectionId);return}this.preparedConnection=void 0,this.connection=t,this.options.registry.register(t),t.startRouter(),t.startConnectHandlers(),this.send(n),this.startOutboundPump(t)}catch(n){this.preparedConnection=void 0,this.options.registry.discard(t.connectionId);let r={jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:n instanceof Error?n.message:void 0}};this.send(r),await this.shutdown(1011,"Initialize failed")}}async forwardMessage(e){let t=this.connection;if(!t)return{ok:!1,message:"ACP WebSocket connection is not initialized"};if(gt(e)&&wn(e))return await this.waitForSocketCapacity(),this.send({jsonrpc:"2.0",id:e.id,error:{code:-32600,message:"Initialize not allowed on existing connection"}}),{ok:!1,message:"Initialize not allowed on existing connection"};return this.trackInboundRoutes(e),await this.forwardToAgent(t,e)}async forwardToAgent(e,t){if(Yy(t))await e.waitForOutboundCapacity(),await this.waitForSocketCapacity();return await this.writeInbound(t),{ok:!0}}async waitForSocketCapacity(){let{limits:e}=this.options.registry,t=Wy,n=this.socket.bufferedAmount??0,r=0;while(!this.isClosed&&n>=e.maxBufferedBytes){if(r>=e.maxOutputStallMs){this.closeForLimit(Mi(e));return}await new Promise((i)=>setTimeout(i,t)),r+=t,t=Math.min(t*2,Ky);let o=n;if(n=this.socket.bufferedAmount??0,n<o)r=0}}trackInboundRoutes(e){let t=this.connection;if(!t)return;if(gt(e)){let n=Sl(e);if(n!=="connection")t.validateSessionId(n.session);t.validateRequestId(e.id);let r=je(e.id);if(r)t.pendingRoutes.set(r,e.method===Cr.session_load?"connection":n);return}if(_t(e)){let n=Sl(e);if(n!=="connection")t.validateSessionId(n.session);return}if(mn(e)){let n=e.id,r=n===null||typeof n==="string"||typeof n==="number"&&Number.isFinite(n)?je(n):void 0;if(r)t.clientResponseRoutes.delete(r)}}async writeInbound(e){let t=this.connection;if(!t)throw Error("ACP WebSocket connection is not initialized");let n=this.inboundWriteChain.then(()=>kl(t,e));this.inboundWriteChain=n.catch(()=>{return}),await n}startOutboundPump(e){let t=e.allOutbound.tryAcquire();if(!t){this.shutdown(1011,"Outbound stream already has an active receiver");return}this.outboundLease=t,t.stopped.addEventListener("abort",()=>{this.closeForStoppedConnection(t.stopped.reason)},{once:!0}),(async()=>{try{while(!this.isClosed){let n=await t.receive();if(n.done)return;if(!this.send(n.value))return;await this.waitForSocketCapacity()}}catch(n){if(!t.stopped.aborted)console.error("ACP WebSocket outbound pump failed:",n);await this.closeForStoppedConnection(n)}finally{if(this.outboundLease===t)this.outboundLease=void 0;if(t.release(),!this.isClosed)this.shutdown()}})()}send(e){if(this.isClosed)return!1;try{return this.socket.send(JSON.stringify(e)),!0}catch(t){return console.warn("Failed to send ACP WebSocket message:",t),this.shutdown(1011,"Failed to send message"),!1}}closeForLimit(e){let t=this.connection?.connectionId??this.preparedConnection?.connectionId,n=t?`ACP connection ${t}`:"ACP connection";console.warn(`Closing ${n}:`,e.message),this.shutdown(1008,e.message)}async closeForStoppedConnection(e){if(this.isClosed)return;if(e instanceof ve)await this.shutdown(1008,e.message);else if(e instanceof we)await this.shutdown();else await this.shutdown(1011,"Internal error")}async shutdownIfUninitialized(e,t){if(this.connection)return;await this.shutdown(e,t)}async shutdown(e,t){this.closeSocket(e,t),await this.closeSession()}closeSocket(e,t){try{this.socket.close(e,t)}catch(n){console.warn("Failed to close ACP WebSocket:",n)}}async closeSession(){if(this.isClosed)return;this.isClosed=!0;try{for(let t of this.detachListeners.splice(0))t();let e=this.outboundLease;if(this.outboundLease=void 0,e?.release(),this.connection)this.options.registry.discard(this.connection.connectionId),this.connection=void 0;if(this.preparedConnection)this.options.registry.discard(this.preparedConnection.connectionId),this.preparedConnection=void 0}finally{this.resolveClosed()}}}async function kl(e,t){await e.writeInbound(t)}function Sl(e){let t=gn(e.params);if(t)return{session:t};return"connection"}function Yy(e){return!_t(e)&&!mn(e)}var Wy=10,Ky=1000,Jy=1024;var El=v(()=>{ge();_n();ji();Ir()});class Bi{agent;registry;webSocketSessions=new Set;constructor(e){this.agent=Tl(e),this.registry=new Di(e)}async handleRequest(e,t={}){try{if(e.method==="POST")return await this.handlePost(e,t);if(e.method==="GET")return this.handleGet(e);if(e.method==="DELETE")return this.handleDelete(e);return q("Method Not Allowed",405)}catch(n){if(n instanceof ve)return q(n.message,400);if(n instanceof we)return q("Unknown Acp-Connection-Id",404);if(n instanceof bt)return q("Request aborted",499);throw n}}prepareWebSocketUpgrade(e={}){let t=Il(e,this.agent),n=this.registry.createPendingConnection(t),r=!1;return{connectionId:n.connectionId,accept:(o)=>{if(r)throw Error("ACP WebSocket upgrade has already been settled");r=!0;let i=vl(o,{registry:this.registry,agent:t,connection:n});this.webSocketSessions.add(i),i.closed.finally(()=>{this.webSocketSessions.delete(i)})},reject:()=>{if(r)return;r=!0,this.registry.discard(n.connectionId)}}}async close(){let e=this.registry.closeAll(),t=Promise.all(Array.from(this.webSocketSessions,(n)=>n.close()));await Promise.all([e,t])}async handlePost(e,t){let n=e.headers.get("Content-Type");if(!sz(n))return q("Unsupported Media Type",415);let r=await Qy(e);if(!r.ok)return q("Invalid JSON",400);if(Array.isArray(r.value))return Zi(Se(T.invalidRequest(void 0,"JSON-RPC batches are not supported")),400);if(!Q(r.value))return q("Invalid JSON-RPC message",400);let o=r.value,i=e.headers.get(Ft);if(wn(o)){if(!i)return await this.handleInitialize(o,e.signal,t);return q("Initialize not allowed on existing connection",400)}if(!i)return q("Missing Acp-Connection-Id",400);let s=this.registry.get(i);if(!s)return q("Unknown Acp-Connection-Id",404);let a=await this.forwardConnectedMessage(s,o,e.headers,e.signal);if(!a.ok)return q(a.message,a.status);return Cl(202)}handleGet(e){if(e.headers.get("Upgrade")?.toLowerCase()==="websocket")return q("WebSocket upgrade is not implemented",426);if(!e.headers.get("Accept")?.toLowerCase()?.includes(Ni))return q("Not Acceptable",406);let n=e.headers.get(Ft);if(!n)return q("Missing Acp-Connection-Id",400);let r=this.registry.get(n);if(!r)return q("Unknown Acp-Connection-Id",404);let o=e.headers.get(vr),i=o?r.acquireSessionStream(o):r.connectionStream.tryAcquire();if(!i)return q("Outbound stream already has an active receiver",409);return az(i)}handleDelete(e){let t=e.headers.get(Ft);if(!t)return q("Missing Acp-Connection-Id",400);if(!this.registry.remove(t))return q("Unknown Acp-Connection-Id",404);return Cl(202)}async handleInitialize(e,t,n){if(!("id"in e)||e.id===null)return q("Initialize request must include an ID",400);if(t.aborted)return q("Request aborted",499);let r;try{r=this.registry.createConnection(Il(n,this.agent));let o=ez(r,e);o.catch(()=>{return});let i=await tz(o,t);if(t.aborted)throw new bt;return r.startRouter(),r.startConnectHandlers(),Zi(i,200,{[Ft]:r.connectionId})}catch(o){if(r)this.registry.remove(r.connectionId);if(o instanceof bt)return q("Request aborted",499);return Zi({jsonrpc:"2.0",id:e.id,error:{code:-32603,message:"Initialize failed",data:o instanceof Error?o.message:void 0}},500)}}async forwardConnectedMessage(e,t,n,r){if(wt(t))return await rz(e,t,n);return await nz(e,t,n,r)}}function Il(e,t){if(Al(e),!Xy(e))return t;return Tl(e)}function Xy(e){return Boolean(e.agent||e.createAgent)}function Tl(e){if(Al(e),(e.agent?1:0)+(e.createAgent?1:0)!==1)throw Error("AcpServer requires exactly one of agent or createAgent");if(e.agent)return e.agent;return{connect:(n,r)=>e.createAgent().connect(n,r??{})}}function Al(e){if("createLegacyAgent"in e)throw Error("createLegacyAgent has been removed. Use agent or createAgent with an app.")}async function Qy(e){try{return{ok:!0,value:await e.json()}}catch{return{ok:!1}}}async function Fi(e,t){await e.writeInbound(t)}async function ez(e,t){if(await Fi(e,t),!("id"in t)||t.id===null)throw Error("Initialize request must include an ID");return await e.recvInitial(t.id)}async function tz(e,t){if(t.aborted)throw new bt;let n=()=>{},r=new Promise((o,i)=>{let s=()=>{i(new bt)};t.addEventListener("abort",s,{once:!0}),n=()=>{t.removeEventListener("abort",s)}});try{return await Promise.race([e,r])}finally{n()}}async function nz(e,t,n,r){let o=iz(t,n);if(!o.ok)return o;if(o.value!=="connection")e.validateSessionId(o.value.session);if(!_t(t))e.validateRequestId(t.id),await e.waitForOutboundCapacity(r).catch((s)=>{throw r.aborted?new bt:s});let i=gt(t)?je(t.id):void 0;if(i)e.pendingRoutes.set(i,oz(t,o.value));return await Fi(e,t),{ok:!0}}async function rz(e,t,n){let r=je(t.id),o=r?e.clientResponseRoutes.get(r):void 0,i=n.get(vr);if(o&&o!=="connection"&&!i)return{ok:!1,status:400,message:"Missing Acp-Session-Id"};if(o&&o!=="connection"&&i!==o.session)return{ok:!1,status:400,message:"Mismatched Acp-Session-Id"};if(r)e.clientResponseRoutes.delete(r);return await Fi(e,t),{ok:!0}}function oz(e,t){return e.method===Cr.session_load?"connection":t}function iz(e,t){let n=t.get(vr),r=gn(e.params);if((Qu(e.method)||r!==void 0)&&!n)return{ok:!1,status:400,message:"Missing Acp-Session-Id"};if(n!==null&&r!==void 0&&n!==r)return{ok:!1,status:400,message:"Mismatched Acp-Session-Id"};if(n)return{ok:!0,value:{session:n}};if(r)return{ok:!0,value:{session:r}};return{ok:!0,value:"connection"}}function sz(e){return e?.split(";",1)[0]?.trim().toLowerCase()===Pi}function az(e){return new Response(yl(e),{status:200,headers:{"Content-Type":Ni,"Cache-Control":"no-cache",Connection:"keep-alive"}})}function Zi(e,t,n){return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":Pi,...n}})}function q(e,t){return new Response(e,{status:t,headers:{"Content-Type":"text/plain"}})}function Cl(e){return new Response(null,{status:e})}var bt;var Rl=v(()=>{Ir();_n();ge();ji();zl();El();Ir();bt=class bt extends Error{constructor(){super("Request aborted");this.name="RequestAbortedError"}}});function Sn(e){let t=Object.values(e).filter((r)=>typeof r==="number");return Object.entries(e).filter(([r,o])=>t.indexOf(+r)===-1).map(([r,o])=>o)}function qi(e,t="|"){return e.map((n)=>Wi(n)).join(t)}function vn(e,t){if(typeof t==="bigint")return t.toString();return t}class Ol{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Ar(e){return new Ol(e)}function Nl(e){return e===null||e===void 0}function Rr(e){let t=e.startsWith("^")?1:0,n=e.endsWith("$")?e.length-1:e.length;return e.slice(t,n)}function Pl(e,t){let n=e/t,r=Math.round(n),o=4*Number.EPSILON*Math.max(Math.abs(n),1);if(Math.abs(n-r)<o)return 0;return n-r}function _e(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Or(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function Ue(e){return Or(e._zod.def)??e._zod.def.shape}function Ll(e,t,n){Object.defineProperty(e,t,{get(){let r=n();return _e(this,t,r),r},enumerable:!0,configurable:!0})}function Ml(e,t,n){if(t in e)_e(e,t,n);else e[t]=n}function yt(e,t,n,r){let o=Ue(t);for(let i of n){let s=Object.getOwnPropertyDescriptor(o,i);if(!s.enumerable)continue;if(s.get)Ll(e,i,()=>{let a=t._zod.def.shape[i];return r?r(a,i):a});else Ml(e,i,r?r(s.value,i):s.value)}}function cz(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);if(!r.enumerable)continue;if(r.get)Ll(e,n,()=>t[n]);else Ml(e,n,r.value)}}function ae(...e){let t={};for(let n of e){let r=Object.getOwnPropertyDescriptors(n);Object.assign(t,r)}return Object.defineProperties({},t)}function Dl(e){return JSON.stringify(e)}function jl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function kn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function zt(e){if(kn(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let n=t.prototype;if(kn(n)===!1)return!1;if(Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)return!1;return!0}function Gi(e){if(zt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}function Je(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function be(e,t,n){let r=new e._zod.constr(t??e._zod.def);if(!t||n?.parent)r._zod.parent=e;return r}function E(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Wi(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Bl(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}function uz(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let i={};return yt(i,e,Pr(e,t)),be(e,ae(n,{shape:i,checks:[]}))}function Pr(e,t){let n=Ue(e),r=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])r.push(o)}return r}function lz(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let i=new Set(Pr(e,t)),s={};return yt(s,e,Reflect.ownKeys(Ue(e)).filter((a)=>!i.has(a))),be(e,ae(n,{shape:s,checks:[]}))}function dz(e,t){if(!zt(t))throw Error("Invalid input to extend: expected a plain object");let n=e._zod.def.checks;if(n&&n.length>0){let o=Ue(e);for(let i of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return be(e,ae(e._zod.def,{shape:Fl(e,t)}))}function Fl(e,t){let n={};return yt(n,e,Reflect.ownKeys(Ue(e))),cz(n,t),n}function fz(e,t){if(!zt(t))throw Error("Invalid input to safeExtend: expected a plain object");return be(e,ae(e._zod.def,{shape:Fl(e,t)}))}function pz(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let n={};yt(n,e,Reflect.ownKeys(Ue(e))),yt(n,t,Reflect.ownKeys(Ue(t)));let r=ae(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return be(e,r)}function Vl(e,t,n,r="partial"){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Pr(t,n)):void 0,u={};return yt(u,t,Reflect.ownKeys(Ue(t)),e&&((d,p)=>a&&!a.has(p)?d:new e({type:"optional",innerType:d}))),be(t,ae(t._zod.def,{shape:u,checks:[]}))}function mz(e,t,n){let r=n?new Set(Pr(t,n)):void 0,o={};return yt(o,t,Reflect.ownKeys(Ue(t)),(i,s)=>r&&!r.has(s)?i:new e({type:"nonoptional",innerType:i})),be(t,ae(t._zod.def,{shape:o}))}function $e(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function ql(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function Ye(e,t){return t.map((n)=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(e),n})}function xn(e){return typeof e==="string"?e:e?.message}function Ji(e){let t=[];for(let n of e??[]){let r=n._zod.def;if(!/_(length|size)$|_equals$/.test(r.check))break;let o=r.maximum??r.length??r.size;if(o>=0)t.push([o,n])}return t}function Lr(e,t,n){var r;for(let o=t;o<e.length;o++)(r=e[o]).schema??(r.schema=n)}function Ee(e,t,n){var r;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(r=e).schema??(r.schema=e.inst);else e.schema=e.inst;let i=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,s=e.message?e.message:xn(e.inst?._zod.def?.error?.(e))??xn(i?.(e))??xn(t?.error?.(e))??xn(n.customError?.(e))??xn(n.localeError?.(e))??"Invalid input",a={};for(let u of Object.keys(e)){if(u==="inst"||u==="schema"||u==="continue"||u==="input"||u==="__proto__")continue;a[u]=e[u]}if(a.path??(a.path=[]),a.message=s,t?.reportInput)a.input=e.input;return a}function Mr(e){let t=e.length;if(!hz.test(e))return t;let n=t;for(let r=0;r<t-1;r++)if((e.charCodeAt(r)&64512)===55296&&(e.charCodeAt(r+1)&64512)===56320)n--,r++;return n}function Dr(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Hl(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let n=e;if(n&&Object.getPrototypeOf(n)!==Object.prototype&&"constructor"in n&&n.constructor)return n.constructor.name}}return t}function xt(...e){let[t,n,r]=e;if(typeof t==="string")return{message:t,code:"custom",input:n,inst:r};return{...t}}function Gl(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);if(r.get)Object.defineProperty(e,n,{...r,enumerable:!1});else gz(e,n,r.value)}}function Ze(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function jr(e,t,n){return Ze(e,t,n,!1)}function Wl(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return Ze(this,n,r(this))},set(o){Ze(this,n,o)}})}return t}function gz(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:Ze(this,t,n.bind(this))},set(r){Ze(this,t,r)}})}function wz(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}function P(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Vi!==e._zod){Vi=void 0;return}Vi=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,_z);let o=Ke;Ke=!1;try{let i=n(this);if(Ke)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:i});return Ke=Ke||o,i}catch(i){throw delete this[t],Ke=Ke||o,i}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function bz(e,t,n,r){let o=wz(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,i),i.value=n(this),Object.defineProperty(this,t,i),i.value},set(i){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:i})}})}function Kl(e){let t=()=>e;return t[yz]=!0,t}var Hi,Ul,Zl,Nr,Ki,hz,Vi,Ke=!1,_z,yz="~constantCatch";var re=v(()=>{kt();Hi="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};Ul=Ar(()=>{if(oe.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});Zl=new Set(["string","number","symbol"]);Nr=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Ki={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};hz=/[\uD800-\uDBFF]/;_z={configurable:!0,get(){Ke=!0;return}}});function zz(e){let t=Yl;if(t){let n=t.stackTraceLimit;if(typeof n==="number"){try{t.stackTraceLimit=0}catch{return Yl=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function y(e,t,n,r){let o={};function i(w){this.def=w,this.constr=g,this.traits=new Set}i.prototype=o;let s=n,a=s&&new WeakSet;function u(w,b){if(!w._zod){Yi.value=new i(b);try{Object.defineProperty(w,"_zod",Yi)}finally{Yi.value=void 0}}else if(w._zod.traits.has(e))return;if(w._zod.traits.add(e),t(w,b),a){let I=Object.getPrototypeOf(w),k=w._zod.constr.prototype,A=I;while(A&&A!==k)A=Object.getPrototypeOf(A);let ne=A??I;if(!a.has(ne))a.add(ne),Gl(ne,s)}let z=g.prototype;for(let I in z){if(!Object.prototype.hasOwnProperty.call(z,I))continue;if(!(I in w))w[I]=z[I].bind(w)}}let d=r?.Parent??Object;class p extends d{}Object.defineProperty(p,"name",{value:e});function g(w){let b=r?.Parent?zz(p):this;u(b,w);let z=b._zod.deferred;if(z){for(let k of z)k();b._zod.deferred=void 0}let I=globalThis.__zod_globalConfig?.postProcessor;if(I)I(b);return b}return Object.defineProperty(g,"init",{value:u}),Object.defineProperty(g,Symbol.hasInstance,{value:(w)=>{if(r?.Parent&&w instanceof r.Parent)return!0;return w?._zod?.traits?.has(e)}}),Object.defineProperty(g,"name",{value:e}),g}function ie(e){if(e)Object.assign(oe,e);return oe}var Jl,Ur,Yi,Yl,Ie,$n,oe;var kt=v(()=>{re();Ur=Object.freeze({status:"aborted"}),Yi={value:void 0,enumerable:!1},Yl="captureStackTrace"in Error?Error:null;Ie=class Ie extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$n=class $n extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}};(Jl=globalThis).__zod_globalConfig??(Jl.__zod_globalConfig={});oe=globalThis.__zod_globalConfig});function xz(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,vn,2)),e.message}function kz(e){this._zod.message=e}function vz(e,t,n){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0});else e[t]=n();return e[t]}function es(e,t=(n)=>n.message){let n={},r=[];for(let o of e.issues)if(o.path.length>0)vz(n,o.path[0],()=>[]).push(t(o));else r.push(t(o));return{formErrors:r,fieldErrors:n}}function ts(e,t=(n)=>n.message){let n={_errors:[]},r=(o,i=[])=>{for(let s of o.issues)if(s.code==="invalid_union"&&s.errors.length)s.errors.map((a)=>r({issues:a},[...i,...s.path]));else if(s.code==="invalid_key")r({issues:s.issues},[...i,...s.path]);else if(s.code==="invalid_element")r({issues:s.issues},[...i,...s.path]);else{let a=[...i,...s.path];if(a.length===0)n._errors.push(t(s));else{let u=n,d=0;while(d<a.length){let p=a[d],g=d===a.length-1;if(p==="_errors"){if(g)u._errors.push(t(s));d++;continue}if(!Object.prototype.hasOwnProperty.call(u,p))Object.defineProperty(u,p,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let w=u[p];if(g)w._errors.push(t(s));u=w,d++}}}};return r(e),n}var Sz,Qi,Xl,Ql=(e,t)=>{e.name="$ZodError",Qi.value=t,Object.defineProperty(e,"issues",Qi),Qi.value=void 0,Object.defineProperty(e,"message",Sz);let n=Object.getPrototypeOf(e);if(!Xl.has(n))Xl.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}})},ed,cT;var td=v(()=>{kt();re();Sz={get:xz,set:kz,enumerable:!0,configurable:!0},Qi={value:void 0,enumerable:!1},Xl=new WeakSet([Object.prototype,Error.prototype]),ed=y("$ZodError",Ql),cT=y("$ZodError",Ql,void 0,{Parent:Error})});function Zr(e,t){return{callee:t?.callee??e,Err:t?.Err}}function nd(e,t,n){let r;return{success:!1,get error(){if(!r)r=new e(t.map((o)=>Ee(o,n,ie()))),t=void 0,n=void 0;return r},set error(o){r=o,t=void 0,n=void 0}}}function Iz(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,i;if(o)r[Ez]=!0,i=o({value:t,issues:[]},r);else i=e._zod.run({value:t,issues:[]},r);if(i instanceof Promise)throw new Ie;return i.issues.length===0}var Br=(e)=>{let t=(n,r,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Ie;if(a.issues.length){let u=new(i?.Err??e)(a.issues.map((d)=>Ee(d,s,ie())));throw Hi(u,i?.callee??t),u}return a.value};return t},Fr=(e)=>{let t=async(n,r,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=n._zod.run({value:r,issues:[]},s);if(a instanceof Promise)a=await a;if(a.issues.length){let u=new(i?.Err??e)(a.issues.map((d)=>Ee(d,s,ie())));throw Hi(u,i?.callee??t),u}return a.value};return t},Vr=(e)=>(t,n,r)=>{let o=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)throw new Ie;return i.issues.length?nd(e,i.issues,o):{success:!0,data:i.value}},qr=(e)=>async(t,n,r)=>{let o=r?{...r,async:!0}:{async:!0},i=t._zod.run({value:n,issues:[]},o);if(i instanceof Promise)i=await i;return i.issues.length?nd(e,i.issues,o):{success:!0,data:i.value}},$z,Ez,ns=(e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==$z)return!0;if(r.definite===!0&&n===void 0)return!1}return Iz(e,t,n)},rs=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)o=await o;return o.issues.length===0},rd=(e)=>{let t=Br(e),n=(r,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return t(r,o,a,Zr(n,s))};return n},od=(e)=>{let t=Br(e),n=(r,o,i,s)=>t(r,o,i,Zr(n,s));return n},id=(e)=>{let t=Fr(e),n=async(r,o,i,s)=>{let a=i?{...i,direction:"backward"}:{direction:"backward"};return await t(r,o,a,Zr(n,s))};return n},sd=(e)=>{let t=Fr(e),n=async(r,o,i,s)=>await t(r,o,i,Zr(n,s));return n},ad=(e)=>(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return Vr(e)(t,n,o)},cd=(e)=>(t,n,r)=>Vr(e)(t,n,r),ud=(e)=>async(t,n,r)=>{let o=r?{...r,direction:"backward"}:{direction:"backward"};return qr(e)(t,n,o)},ld=(e)=>async(t,n,r)=>qr(e)(t,n,r);var dd=v(()=>{kt();re();$z=Symbol.for("zod.compile.invalid"),Ez=Symbol.for("zod.compile.fallback")});function _d(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}function xd(){return new RegExp(Cz,"u")}function Tz(e){return new RegExp(`^${e}$`)}function os(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function Od(e){return new RegExp(`^${os(e)}$`)}function Nd(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let n=`${os({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,r=e.local?`${n}|${os({precision:e.precision})}`:n;return new RegExp(`^${Ad}T(?:${r})$`)}var fd,pd,md,hd,gd,wd,bd,yd,is=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},zd,Cz="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$",kd,Sd,vd,$d,Ed,Id,Cd,Td,Ad="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Rd,Pd,ss,En,Ld,Md,Dd,jd;var In=v(()=>{fd=/^[cC][0-9a-z]{6,}$/,pd=/^[0-9a-z]+$/,md=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,hd=/^[0-9a-vA-V]{20}$/,gd=/^[A-Za-z0-9]{27}$/,wd=/^[a-zA-Z0-9_-]{21}$/;bd=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yd=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,zd=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;kd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Sd=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,vd=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,$d=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ed=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Id=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Cd=/^https?$/,Td=/^\+[1-9]\d{6,14}$/;Rd=Tz(Ad);Pd=/^[\s\S]{0,}$/,ss=/^-?\d+$/,En=/^-?\d+(?:\.\d+)?$/,Ld=/^(?:true|false)$/i,Md=/^null$/i,Dd=/^[^A-Z]*$/,jd=/^[^a-z]*$/});var J,as=(e)=>{let t=e.value;return!Nl(t)&&t.length!==void 0},Hr,cs,us,Ud,Zd,Bd,Fd,Vd,Cn,qd,Hd,Gd,Wd,Kd,Jd,Yd;var Gr=v(()=>{kt();In();re();J=y("$ZodCheck",(e,t)=>{var n;e._zod??(e._zod={}),e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Hr={number:"number",bigint:"bigint",object:"date"},cs=y("$ZodCheckLessThan",(e,t)=>{J.init(e,t);let n=Hr[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value<=t.value:r.value<t.value)return;r.issues.push({origin:Hr[typeof r.value]??n,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),us=y("$ZodCheckGreaterThan",(e,t)=>{J.init(e,t);let n=Hr[typeof t.value];e._zod.check=(r)=>{if(t.inclusive?r.value>=t.value:r.value>t.value)return;r.issues.push({origin:Hr[typeof r.value]??n,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ud=y("$ZodCheckMultipleOf",(e,t)=>{J.init(e,t),e._zod.check=(n)=>{if(typeof n.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof n.value==="bigint"?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Pl(n.value,t.value)===0)return;n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Zd=y("$ZodCheckNumberFormat",(e,t)=>{J.init(e,t),t.format=t.format||"float64";let n=t.format?.includes("int"),r=n?"int":"number",[o,i]=Nr[t.format];e._zod.check=(s)=>{let a=s.value;if(n){if(!Number.isInteger(a)){s.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});else s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}if(a<o)s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>i)s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:e,continue:!t.abort})}}),Bd=y("$ZodCheckMaxLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=as),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>t.maximum?Mr(o):i)<=t.maximum)return;let a=Dr(o);r.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Fd=y("$ZodCheckMinLength",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=as),e._zod.check=(r)=>{let o=r.value,i=o.length;if((typeof o==="string"&&i>=t.minimum&&i<t.minimum*2?Mr(o):i)>=t.minimum)return;let a=Dr(o);r.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Vd=y("$ZodCheckLengthEquals",(e,t)=>{var n;J.init(e,t),(n=e._zod.def).when??(n.when=as),e._zod.check=(r)=>{let o=r.value,i=o.length,s=typeof o==="string"&&i>=t.length&&i<=t.length*2?Mr(o):i;if(s===t.length)return;let a=Dr(o),u=s>t.length;r.issues.push({origin:a,...u?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:e,continue:!t.abort})}}),Cn=y("$ZodCheckStringFormat",(e,t)=>{var n,r;if(J.init(e,t),t.pattern)(n=e._zod).check??(n.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(r=e._zod).check??(r.check=()=>{})}),qd=y("$ZodCheckRegex",(e,t)=>{Cn.init(e,t),e._zod.check=(n)=>{if(t.pattern.lastIndex=0,t.pattern.test(n.value))return;n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Hd=y("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Dd),Cn.init(e,t)}),Gd=y("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=jd),Cn.init(e,t)}),Wd=y("$ZodCheckIncludes",(e,t)=>{J.init(e,t);let n=Je(t.includes),r=new RegExp(typeof t.position==="number"?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Kd=y("$ZodCheckStartsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`^${Je(t.prefix)}.*`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.startsWith(t.prefix))return;r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:e,continue:!t.abort})}}),Jd=y("$ZodCheckEndsWith",(e,t)=>{J.init(e,t);let n=new RegExp(`.*${Je(t.suffix)}$`);t.pattern??(t.pattern=n),e._zod.check=(r)=>{if(r.value.endsWith(t.suffix))return;r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:e,continue:!t.abort})}}),Yd=y("$ZodCheckOverwrite",(e,t)=>{J.init(e,t),e._zod.check=(n)=>{n.value=t.tx(n.value)}})});class ls{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
11
11
  `).filter((i)=>i),r=Math.min(...n.map((i)=>i.length-i.trimStart().length)),o=n.map((i)=>i.slice(r)).map((i)=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
12
12
  ${t.join(`
13
13
  `)}
14
- };`)(...Object.values(this.closed))}}var Od;var Qi=S(()=>{Od={major:4,minor:6,patch:7}});async function tz(e,t){let n={async:!0};return Vd(await e._zod.run({value:t,issues:[]},n),n)}function ts(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Vd(r,n)}catch(r){}return tz(e,t)},vendor:"zod",version:1}}function Kd(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function nz(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Kd(e)||Fr;return rz(e,t)}function rz(e,t){if(!t.normalize&&t.protocol?.source===ud.source&&!/^https?:\/\//i.test(e))return Wd;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??Fr}return new URL(e)}catch{return Fr}}function Nd(e){return e.replace(oz,"")}function iz(e,t){return t.lastIndex=0,t.test(e.hostname)}function sz(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}function up(e){if(!az.test(e))return!1;return Kd(`http://[${e}]`)}function cz(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);if(`${o}`!==r)return!1;if(o<0||o>128)return!1;return up(n)}function fp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function uz(e){if(!Hr.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return fp(n)}function lz(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}function dz(e,t){let n=Mi(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((i)=>i[0])),o=e._zod.parse;e._zod.parse=(i,s)=>{let a=t(i.value);if(a>r&&!s?.skipChecks&&s?.direction!=="backward"){for(let[l,d]of Mi(e._zod.def.checks))if(a>l&&d._zod.def.when(i)){let f=i.issues.length;return d._zod.check(i),i.issues[f].continue=!1,Tr(i.issues,f,e),i}}return o(i,s)}}function Pd(e,t,n){if(e.issues.length)t.issues.push(...Ye(n,e.issues));t.value[n]=e.value}function Vr(e,t,n,r,o,i){let s=n in r,a=i==="optional";if(!s&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!s)return;t.issues.push(...Ye(n,e.issues))}if(!s&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s||o==="defaulted"&&!a)t.value[n]=void 0}else t.value[n]=e.value}function Sp(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:fz,o=r.length?[...t,...r]:t;for(let s of o)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=xl(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function vp(e,t,n,r,o,i,s){let a=[],l=o.keySet,d=o.catchall._zod,f=d.def.type,{optin:g,optout:w}=d,b=0;for(let z in t){if(s&&n.issues.length!==b){if($e(n,b))break;b=n.issues.length}if(l.has(z))continue;if(z==="__proto__"){if(f==="never")a.push(z);continue}if(f==="never"){a.push(z);continue}let I=d.run({value:t[z],issues:[]},r);if(I instanceof Promise)e.push(I.then((E)=>Vr(E,n,z,t,g,w)));else Vr(I,n,z,t,g,w)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}function Ld(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!$e(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((i)=>i.issues.map((s)=>Ee(s,r,ie())))}),t}function es(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(wt(e)&&wt(t)){let n=Object.keys(t),r=Object.keys(e).filter((i)=>n.indexOf(i)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let i of r){if(i==="__proto__")continue;let s=es(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],s=es(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function Dd(e,t,n){let r=new Map,o,i=new Map,s=(d,f)=>{let g;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),g=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let w=String(d.path[0]);if(!i.has(w))i.set(w,d);g=[w]}else return!1;for(let w of g){if(!r.has(w))r.set(w,{});r.get(w)[f]=!0}return!0};for(let d of t.issues)if(!s(d,"l"))e.issues.push(d);for(let d of n.issues)if(!s(d,"r"))e.issues.push(d);let a=[...r].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){let d=o?a.filter((f)=>o.keys.includes(f)):[];if(d.length)e.issues.push({...o,keys:d});for(let f of a)if(!d.includes(f)&&i.has(f))e.issues.push(i.get(f))}let l=es(t.value,n.value);if(!l.valid){if($e(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`)}return e.value=l.data,e}function Md(e,t){return e.value=t.issues.length?void 0:t.value,e}function jd(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function Ud(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Zd(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>Ee(o,r,ie()))},input:e.value}),e}function Br(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}function Bd(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function Fd(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(_t(o))}}var U,Vd=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>Ee(n,t,ie()))}:{value:e.value},qr,Z,qd,Hd,Gd,Wd=1,Fr=2,oz,Jd,Yd,Xd,Qd,ep,tp,np,rp,op,ip,sp,ap,cp,az,lp,dp,pp,ns,mp,Hr,hp,gp,wp,rs,_p,bp,yp,zp,xp,pz=(e)=>Array.isArray(e)?e.length:-1,kp,fz,mz,$p,Ep,Ip,Cp,Tp,Ap,Rp,os,Op,Np,Pp,Lp,Dp,Mp,is,jp,Up,Zp;var ss=S(()=>{Zr();bt();zn();re();Qi();re();U=y("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Od;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let s of i._zod.onattach)s(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(a,l,d)=>{if(a.memo)return a;let f=$e(a),g;for(let w of l){if(w._zod.def.when){if(vl(a))continue;if(!w._zod.def.when(a))continue}else if(f)continue;let b=a.issues.length,z=w._zod.check(a);if(z instanceof Promise&&d?.async===!1)throw new Ie;if(g||z instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await z,a.issues.length===b)return;if(Tr(a.issues,b,e),!f)f=$e(a,b)});else{if(a.issues.length===b)continue;if(Tr(a.issues,b,e),!f)f=$e(a,b)}}if(g)return g.then(()=>a);return a},s=(a,l,d)=>{if($e(a))return a.aborted=!0,a;let f=i(l,o,d);if(f instanceof Promise){if(d.async===!1)throw new Ie;return f.then((g)=>e._zod.parse(g,d))}return e._zod.parse(f,d)};e._zod.run=(a,l)=>{if(l.skipChecks)return e._zod.parse(a,l);if(l.direction==="backward"){let f=e._zod.parse({value:a.value,issues:[]},{...l,skipChecks:!0});if(f instanceof Promise)return f.then((g)=>s(g,a,l));return s(f,a,l)}let d=e._zod.parse(a,l);if(d instanceof Promise){if(l.async===!1)throw new Ie;return d.then((f)=>i(f,o,l))}return i(d,o,l)}}},{get "~standard"(){return Or(this,"~standard",ts(this))},set "~standard"(e){Ue(this,"~standard",e)}});qr=y("$ZodString",(e,t)=>{U.init(e,t),e._zod.pattern=t.pattern??hd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Z=y("$ZodStringFormat",(e,t)=>{xn.init(e,t),qr.init(e,t)}),qd=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=ed),Z.init(e,t)}),Hd=y("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=Gi(r))}else t.pattern??(t.pattern=Gi());Z.init(e,t)}),Gd=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=td),Z.init(e,t)});oz=/[\t\n\r]/g;Jd=y("$ZodURL",(e,t)=>{Z.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),o=nz(r,t);if(o===Wd){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===Fr){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=Nd(r);return}if(t.hostname&&!iz(o,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!sz(o,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?o.href:Nd(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),Yd=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=nd()),Z.init(e,t)}),Xd=y("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?Yl:Xl(t.length)),Z.init(e,t)}),Qd=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Hl),Z.init(e,t)}),ep=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Gl),Z.init(e,t)}),tp=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Wl),Z.init(e,t)}),np=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=Kl),Z.init(e,t)}),rp=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=Jl),Z.init(e,t)}),op=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=md(t)),Z.init(e,t)}),ip=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=pd),Z.init(e,t)}),sp=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=fd(t)),Z.init(e,t)}),ap=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=Ql),Z.init(e,t)}),cp=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=rd),Z.init(e,t)}),az=/^[0-9a-fA-F:.]+$/;lp=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=od),Z.init(e,t),e._zod.check=(n)=>{if(!up(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),dp=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=id),Z.init(e,t)});pp=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=sd),Z.init(e,t),e._zod.check=(n)=>{if(!cz(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});ns=/^[0-9a-zA-Z+/]*={0,2}$/,mp=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ns),Z.init(e,t),e._zod.check=(n)=>{if(fp(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Hr=/^[A-Za-z0-9_-]*$/;hp=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hr),Z.init(e,t),e._zod.check=(n)=>{if(uz(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),gp=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=ld),Z.init(e,t)});wp=y("$ZodJWT",(e,t)=>{Z.init(e,t),e._zod.check=(n)=>{if(lz(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),rs=y("$ZodNumber",(e,t)=>{U.init(e,t),e._zod.pattern=yn,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),_p=y("$ZodNumberFormat",(e,t)=>{zd.init(e,t),rs.init(e,t)}),bp=y("$ZodBoolean",(e,t)=>{U.init(e,t),e._zod.pattern=gd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}let o=n.value;if(typeof o==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),yp=y("$ZodNull",(e,t)=>{U.init(e,t),e._zod.pattern=wd,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;if(o===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),zp=y("$ZodUnknown",(e,t)=>{U.init(e,t),e._zod.parse=(n)=>n}),xp=y("$ZodNever",(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});kp=y("$ZodArray",(e,t)=>{U.init(e,t);let n=oe.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=n?n.alloc(e,r,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let l=0;l<i.length;l++){let d=i[l],f=t.element._zod.run({value:d,issues:[]},o);if(f instanceof Promise)s.push(f.then((g)=>Pd(g,r,l)));else if(Pd(f,r,l),a&&f.issues.length!==0&&$e(f))break}if(s.length)return Promise.all(s).then(()=>r);return r},dz(e,pz)});fz=[];mz=y("$ZodObject",(e,t)=>{U.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let d=()=>{let f={...r};return Object.defineProperty(t,"shape",{value:f}),d.raw=f,f};d.raw=r,Object.defineProperty(t,"shape",{get:d})}let o=vr(()=>Sp(t));P(e,"propValues",(d)=>{let f=d.def.shape,g={};for(let w in f){let b=f[w]._zod;if(b.values){if(!Object.prototype.hasOwnProperty.call(g,w))_e(g,w,new Set);for(let z of b.values)g[w].add(z);if(b.optin!==void 0)g[w].add(void 0)}}return g});let i=gn,s=t.catchall,a,l=oe.memoizer;l?.attach(e),e._zod.parse=(d,f)=>{a??(a=o.value);let g=d.value;if(!i(g))return d.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),d;d.value=l?l.alloc(e,d,{},f):{};let w=[],b=a.shape,z=f?.abortEarly,I=d.issues.length;for(let E of a.allKeys){if(z&&d.issues.length!==I){if($e(d,I))break;I=d.issues.length}if(E==="__proto__")continue;let A=b[E],X=A._zod.optin,Fe=A._zod.optout,qt=A._zod.run({value:g[E],issues:[]},f);if(qt instanceof Promise)w.push(qt.then((G)=>Vr(G,d,E,g,X,Fe)));else Vr(qt,d,E,g,X,Fe)}if(!s)return w.length?Promise.all(w).then(()=>d):d;return vp(w,g,d,f,o.value,e,z===!0)}}),$p=y("$ZodObjectJIT",(e,t)=>{mz.init(e,t);let n=e._zod.parse,r=vr(()=>Sp(t)),o=oe.memoizer,i=(b)=>{let z=r.value,I=z.symbolKeys,E=new Xi(["payload","ctx"],{shape:b,inst:e,memo:o,syms:I}),A=(G)=>`shape[${G}]._zod.run({ value: input[${G}], issues: [] }, ctx)`,X=(G,j)=>`
15
- let ${G}_ab = false;
16
- for (let i = 0; i < ${G}.issues.length; i++) {
17
- const iss = ${G}.issues[i];
18
- iss.path = iss.path ? [${j}, ...iss.path] : [${j}];
14
+ };`)(...Object.values(this.closed))}}var Qd;var ds=v(()=>{Qd={major:4,minor:6,patch:7}});async function Az(e,t){let n={async:!0};return df(await e._zod.run({value:t,issues:[]},n),n)}function ps(e){return{validate:(t)=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return df(r,n)}catch(r){}return Az(e,t)},vendor:"zod",version:1}}function gf(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function Rz(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return gf(e)||Kr;return Oz(e,t)}function Oz(e,t){if(!t.normalize&&t.protocol?.source===Cd.source&&!/^https?:\/\//i.test(e))return hf;try{if(typeof URL<"u"){let n=URL;if(typeof n.parse==="function")return n.parse(e)??Kr}return new URL(e)}catch{return Kr}}function ef(e){return e.replace(Nz,"")}function Pz(e,t){return t.lastIndex=0,t.test(e.hostname)}function Lz(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}function Tf(e){if(!Mz.test(e))return!1;return gf(`http://[${e}]`)}function Dz(e){let t=e.split("/");if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let o=Number(r);if(`${o}`!==r)return!1;if(o<0||o>128)return!1;return Tf(n)}function Nf(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}function jz(e){if(!Xr.test(e))return!1;let t=e.replace(/[-_]/g,(r)=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Nf(n)}function Uz(e,t=null){try{let n=e.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}function Zz(e,t){let n=Ji(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map((i)=>i[0])),o=e._zod.parse;e._zod.parse=(i,s)=>{let a=t(i.value);if(a>r&&!s?.skipChecks&&s?.direction!=="backward"){for(let[u,d]of Ji(e._zod.def.checks))if(a>u&&d._zod.def.when(i)){let p=i.issues.length;return d._zod.check(i),i.issues[p].continue=!1,Lr(i.issues,p,e),i}}return o(i,s)}}function tf(e,t,n){if(e.issues.length)t.issues.push(...Ye(n,e.issues));t.value[n]=e.value}function Jr(e,t,n,r,o,i){let s=n in r,a=i==="optional";if(!s&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!s)return;t.issues.push(...Ye(n,e.issues))}if(!s&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}if(e.value===void 0){if(s||o==="defaulted"&&!a)t.value[n]=void 0}else t.value[n]=e.value}function qf(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Fz,o=r.length?[...t,...r]:t;for(let s of o)if(!e.shape?.[s]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=Bl(e.shape);return{...e,allKeys:o,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(i)}}function Hf(e,t,n,r,o,i,s){let a=[],u=o.keySet,d=o.catchall._zod,p=d.def.type,{optin:g,optout:w}=d,b=0;for(let z in t){if(s&&n.issues.length!==b){if($e(n,b))break;b=n.issues.length}if(u.has(z))continue;if(z==="__proto__"){if(p==="never")a.push(z);continue}if(p==="never"){a.push(z);continue}let I=d.run({value:t[z],issues:[]},r);if(I instanceof Promise)e.push(I.then((k)=>Jr(k,n,z,t,g,w)));else Jr(I,n,z,t,g,w)}if(a.length)n.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:i,continue:!0});if(!e.length)return n;return Promise.all(e).then(()=>n)}function nf(e,t,n,r){for(let i of e)if(i.issues.length===0)return t.value=i.value,t;let o=e.filter((i)=>!$e(i));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map((i)=>i.issues.map((s)=>Ee(s,r,ie())))}),t}function fs(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(zt(e)&&zt(t)){let n=Object.keys(t),r=Object.keys(e).filter((i)=>n.indexOf(i)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let i of r){if(i==="__proto__")continue;let s=fs(e[i],t[i]);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};o[i]=s.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let o=e[r],i=t[r],s=fs(o,i);if(!s.valid)return{valid:!1,mergeErrorPath:[r,...s.mergeErrorPath]};n.push(s.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function rf(e,t,n){let r=new Map,o,i=new Map,s=(d,p)=>{let g;if(d.code==="unrecognized_keys"&&!d.path?.length)o??(o=d),g=d.keys;else if(d.code==="invalid_key"&&d.origin==="record"&&d.path?.length===1){let w=String(d.path[0]);if(!i.has(w))i.set(w,d);g=[w]}else return!1;for(let w of g){if(!r.has(w))r.set(w,{});r.get(w)[p]=!0}return!0};for(let d of t.issues)if(!s(d,"l"))e.issues.push(d);for(let d of n.issues)if(!s(d,"r"))e.issues.push(d);let a=[...r].filter(([,d])=>d.l&&d.r).map(([d])=>d);if(a.length){let d=o?a.filter((p)=>o.keys.includes(p)):[];if(d.length)e.issues.push({...o,keys:d});for(let p of a)if(!d.includes(p)&&i.has(p))e.issues.push(i.get(p))}let u=fs(t.value,n.value);if(!u.valid){if($e(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(u.mergeErrorPath)}`)}return e.value=u.data,e}function of(e,t){return e.value=t.issues.length?void 0:t.value,e}function sf(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}function af(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function cf(e,t,n,r){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>Ee(o,r,ie()))},input:e.value}),e}function Wr(e,t,n){if(e.issues.some((r)=>r.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},n)}function uf(e){if(!e.memo)e.value=Object.freeze(e.value);return e}function lf(e,t,n,r){if(!e){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};if(r._zod.def.params)o.params=r._zod.def.params;t.issues.push(xt(o))}}var U,df=(e,t)=>e.issues.length?{issues:e.issues.map((n)=>Ee(n,t,ie()))}:{value:e.value},Yr,Z,ff,pf,mf,hf=1,Kr=2,Nz,wf,_f,bf,yf,zf,xf,kf,Sf,vf,$f,Ef,If,Cf,Mz,Af,Rf,Of,ms,Pf,Xr,Lf,Mf,Df,hs,jf,Uf,Zf,Bf,Ff,Bz=(e)=>Array.isArray(e)?e.length:-1,Vf,Fz,Vz,Gf,Wf,Kf,Jf,Yf,Xf,Qf,gs,ep,tp,np,rp,op,ip,ws,sp,ap,cp;var _s=v(()=>{Gr();kt();In();re();ds();re();U=y("$ZodType",(e,t)=>{var n;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Qd;let r=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let s of i._zod.onattach)s(e);if(o.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let i=(a,u,d)=>{if(a.memo)return a;let p=$e(a),g;for(let w of u){if(w._zod.def.when){if(ql(a))continue;if(!w._zod.def.when(a))continue}else if(p)continue;let b=a.issues.length,z=w._zod.check(a);if(z instanceof Promise&&d?.async===!1)throw new Ie;if(g||z instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await z,a.issues.length===b)return;if(Lr(a.issues,b,e),!p)p=$e(a,b)});else{if(a.issues.length===b)continue;if(Lr(a.issues,b,e),!p)p=$e(a,b)}}if(g)return g.then(()=>a);return a},s=(a,u,d)=>{if($e(a))return a.aborted=!0,a;let p=i(u,o,d);if(p instanceof Promise){if(d.async===!1)throw new Ie;return p.then((g)=>e._zod.parse(g,d))}return e._zod.parse(p,d)};e._zod.run=(a,u)=>{if(u.skipChecks)return e._zod.parse(a,u);if(u.direction==="backward"){let p=e._zod.parse({value:a.value,issues:[]},{...u,skipChecks:!0});if(p instanceof Promise)return p.then((g)=>s(g,a,u));return s(p,a,u)}let d=e._zod.parse(a,u);if(d instanceof Promise){if(u.async===!1)throw new Ie;return d.then((p)=>i(p,o,u))}return i(d,o,u)}}},{get "~standard"(){return jr(this,"~standard",ps(this))},set "~standard"(e){Ze(this,"~standard",e)}});Yr=y("$ZodString",(e,t)=>{U.init(e,t),e._zod.pattern=t.pattern??Pd,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch(o){}if(typeof n.value==="string")return n;return n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:e}),n}}),Z=y("$ZodStringFormat",(e,t)=>{Cn.init(e,t),Yr.init(e,t)}),ff=y("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=yd),Z.init(e,t)}),pf=y("$ZodUUID",(e,t)=>{if(t.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=is(r))}else t.pattern??(t.pattern=is());Z.init(e,t)}),mf=y("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=zd),Z.init(e,t)});Nz=/[\t\n\r]/g;wf=y("$ZodURL",(e,t)=>{Z.init(e,t),e._zod.check=(n)=>{try{let r=n.value.trim(),o=Rz(r,t);if(o===hf){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:e,continue:!t.abort});return}if(o===Kr){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort});return}if(o===!0){n.value=ef(r);return}if(t.hostname&&!Pz(o,t.hostname))n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort});if(t.protocol&&!Lz(o,t.protocol))n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort});n.value=t.normalize?o.href:ef(r);return}catch(r){n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:e,continue:!t.abort})}}}),_f=y("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=xd()),Z.init(e,t)}),bf=y("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?wd:_d(t.length)),Z.init(e,t)}),yf=y("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=fd),Z.init(e,t)}),zf=y("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=pd),Z.init(e,t)}),xf=y("$ZodULID",(e,t)=>{t.pattern??(t.pattern=md),Z.init(e,t)}),kf=y("$ZodXID",(e,t)=>{t.pattern??(t.pattern=hd),Z.init(e,t)}),Sf=y("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=gd),Z.init(e,t)}),vf=y("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Nd(t)),Z.init(e,t)}),$f=y("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=Rd),Z.init(e,t)}),Ef=y("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=Od(t)),Z.init(e,t)}),If=y("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=bd),Z.init(e,t)}),Cf=y("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=kd),Z.init(e,t)}),Mz=/^[0-9a-fA-F:.]+$/;Af=y("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=Sd),Z.init(e,t),e._zod.check=(n)=>{if(!Tf(n.value))n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:e,continue:!t.abort})}}),Rf=y("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=vd),Z.init(e,t)});Of=y("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=$d),Z.init(e,t),e._zod.check=(n)=>{if(!Dz(n.value))n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:e,continue:!t.abort})}});ms=/^[0-9a-zA-Z+/]*={0,2}$/,Pf=y("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=ms),Z.init(e,t),e._zod.check=(n)=>{if(Nf(n.value))return;n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:e,continue:!t.abort})}}),Xr=/^[A-Za-z0-9_-]*$/;Lf=y("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Xr),Z.init(e,t),e._zod.check=(n)=>{if(jz(n.value))return;n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:e,continue:!t.abort})}}),Mf=y("$ZodE164",(e,t)=>{t.pattern??(t.pattern=Td),Z.init(e,t)});Df=y("$ZodJWT",(e,t)=>{Z.init(e,t),e._zod.check=(n)=>{if(Uz(n.value,t.alg))return;n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:e,continue:!t.abort})}}),hs=y("$ZodNumber",(e,t)=>{U.init(e,t),e._zod.pattern=En,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch(s){}let o=n.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let i=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...i?{received:i}:{}}),n}}),jf=y("$ZodNumberFormat",(e,t)=>{Zd.init(e,t),hs.init(e,t)}),Uf=y("$ZodBoolean",(e,t)=>{U.init(e,t),e._zod.pattern=Ld,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Boolean(n.value)}catch(i){}let o=n.value;if(typeof o==="boolean")return n;return n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),n}}),Zf=y("$ZodNull",(e,t)=>{U.init(e,t),e._zod.pattern=Md,e._zod.values=new Set([null]),e._zod.parse=(n,r)=>{let o=n.value;if(o===null)return n;return n.issues.push({expected:"null",code:"invalid_type",input:o,inst:e}),n}}),Bf=y("$ZodUnknown",(e,t)=>{U.init(e,t),e._zod.parse=(n)=>n}),Ff=y("$ZodNever",(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:e}),n)});Vf=y("$ZodArray",(e,t)=>{U.init(e,t);let n=oe.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:e}),r;r.value=n?n.alloc(e,r,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let u=0;u<i.length;u++){let d=i[u],p=t.element._zod.run({value:d,issues:[]},o);if(p instanceof Promise)s.push(p.then((g)=>tf(g,r,u)));else if(tf(p,r,u),a&&p.issues.length!==0&&$e(p))break}if(s.length)return Promise.all(s).then(()=>r);return r},Zz(e,Bz)});Fz=[];Vz=y("$ZodObject",(e,t)=>{U.init(e,t);let n=Object.getOwnPropertyDescriptor(t,"shape"),r=n?.get?n.get.raw:t.shape??{};if(r){let d=()=>{let p={...r};return Object.defineProperty(t,"shape",{value:p}),d.raw=p,p};d.raw=r,Object.defineProperty(t,"shape",{get:d})}let o=Ar(()=>qf(t));P(e,"propValues",(d)=>{let p=d.def.shape,g={};for(let w in p){let b=p[w]._zod;if(b.values){if(!Object.prototype.hasOwnProperty.call(g,w))_e(g,w,new Set);for(let z of b.values)g[w].add(z);if(b.optin!==void 0)g[w].add(void 0)}}return g});let i=kn,s=t.catchall,a,u=oe.memoizer;u?.attach(e),e._zod.parse=(d,p)=>{a??(a=o.value);let g=d.value;if(!i(g))return d.issues.push({expected:"object",code:"invalid_type",input:g,inst:e}),d;d.value=u?u.alloc(e,d,{},p):{};let w=[],b=a.shape,z=p?.abortEarly,I=d.issues.length;for(let k of a.allKeys){if(z&&d.issues.length!==I){if($e(d,I))break;I=d.issues.length}if(k==="__proto__")continue;let A=b[k],ne=A._zod.optin,tt=A._zod.optout,nt=A._zod.run({value:g[k],issues:[]},p);if(nt instanceof Promise)w.push(nt.then((V)=>Jr(V,d,k,g,ne,tt)));else Jr(nt,d,k,g,ne,tt)}if(!s)return w.length?Promise.all(w).then(()=>d):d;return Hf(w,g,d,p,o.value,e,z===!0)}}),Gf=y("$ZodObjectJIT",(e,t)=>{Vz.init(e,t);let n=e._zod.parse,r=Ar(()=>qf(t)),o=oe.memoizer,i=(b)=>{let z=r.value,I=z.symbolKeys,k=new ls(["payload","ctx"],{shape:b,inst:e,memo:o,syms:I}),A=(V)=>`shape[${V}]._zod.run({ value: input[${V}], issues: [] }, ctx)`,ne=(V,M)=>`
15
+ let ${V}_ab = false;
16
+ for (let i = 0; i < ${V}.issues.length; i++) {
17
+ const iss = ${V}.issues[i];
18
+ iss.path = iss.path ? [${M}, ...iss.path] : [${M}];
19
19
  payload.issues.push(iss);
20
- if (iss.continue !== true) ${G}_ab = true;
20
+ if (iss.continue !== true) ${V}_ab = true;
21
21
  }
22
- if (${G}_ab && ctx && ctx.abortEarly) {
22
+ if (${V}_ab && ctx && ctx.abortEarly) {
23
23
  payload.value = newResult;
24
24
  return payload;
25
- }`;E.write("const input = payload.value;");let Fe=Object.create(null),qt=0;for(let G of z.allKeys)Fe[G]=`key_${qt++}`;E.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let G of z.allKeys){if(G==="__proto__")continue;let j=Fe[G],ze=typeof G==="symbol"?`syms[${I.indexOf(G)}]`:_l(G),vo=`${ze} in input`,Ja=b[G],$o=Ja?._zod?.optin,Ya=$o!==void 0,dg=Ja?._zod?.optout==="optional";if(E.write(`const ${j} = ${A(ze)};`),Ya&&dg){let pg=$o==="optional"?`${j}_present`:`${j}.value !== undefined || ${j}_present`;E.write(`
26
- const ${j}_present = ${vo};
27
- if (!${j}.issues.length || ${j}_present) {
28
- if (${j}.issues.length) {${X(j,ze)}
25
+ }`;k.write("const input = payload.value;");let tt=Object.create(null),nt=0;for(let V of z.allKeys)tt[V]=`key_${nt++}`;k.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let V of z.allKeys){if(V==="__proto__")continue;let M=tt[V],se=typeof V==="symbol"?`syms[${I.indexOf(V)}]`:Dl(V),Ao=`${se} in input`,cc=b[V],Ro=cc?._zod?.optin,uc=Ro!==void 0,Ag=cc?._zod?.optout==="optional";if(k.write(`const ${M} = ${A(se)};`),uc&&Ag){let Rg=Ro==="optional"?`${M}_present`:`${M}.value !== undefined || ${M}_present`;k.write(`
26
+ const ${M}_present = ${Ao};
27
+ if (!${M}.issues.length || ${M}_present) {
28
+ if (${M}.issues.length) {${ne(M,se)}
29
29
  }
30
30
 
31
- if (${pg}) {
32
- newResult[${ze}] = ${j}.value;
31
+ if (${Rg}) {
32
+ newResult[${se}] = ${M}.value;
33
33
  }
34
34
  }
35
35
 
36
- `)}else if(!Ya)E.write(`
37
- const ${j}_present = ${vo};
38
- if (${j}.issues.length) {${X(j,ze)}
36
+ `)}else if(!uc)k.write(`
37
+ const ${M}_present = ${Ao};
38
+ if (${M}.issues.length) {${ne(M,se)}
39
39
  }
40
- if (!${j}_present && !${j}.issues.length) {
40
+ if (!${M}_present && !${M}.issues.length) {
41
41
  payload.issues.push({
42
42
  code: "invalid_type",
43
43
  expected: "nonoptional",
44
44
  input: undefined,
45
- path: [${ze}]
45
+ path: [${se}]
46
46
  });
47
47
  if (ctx && ctx.abortEarly) {
48
48
  payload.value = newResult;
@@ -50,54 +50,56 @@ ${t.join(`
50
50
  }
51
51
  }
52
52
 
53
- if (${j}_present) {
54
- newResult[${ze}] = ${j}.value;
53
+ if (${M}_present) {
54
+ newResult[${se}] = ${M}.value;
55
55
  }
56
56
 
57
- `);else if(E.write(`
58
- if (${j}.issues.length) {${X(j,ze)}
57
+ `);else if(k.write(`
58
+ if (${M}.issues.length) {${ne(M,se)}
59
59
  }
60
- `),$o==="defaulted")E.write(`newResult[${ze}] = ${j}.value;`);else E.write(`
61
- if (${j}.value !== undefined || ${vo}) {
62
- newResult[${ze}] = ${j}.value;
60
+ `),Ro==="defaulted")k.write(`newResult[${se}] = ${M}.value;`);else k.write(`
61
+ if (${M}.value !== undefined || ${Ao}) {
62
+ newResult[${se}] = ${M}.value;
63
63
  }
64
- `)}return E.write("payload.value = newResult;"),E.write("return payload;"),E.compile()},s,a=gn,l=!oe.jitless,f=l&&yl.value,g=t.catchall,w;e._zod.parse=(b,z)=>{w??(w=r.value);let I=b.value;if(!a(I))return b.issues.push({expected:"object",code:"invalid_type",input:I,inst:e}),b;if(l&&f&&z?.async===!1&&z.jitless!==!0){if(!s)s=i(t.shape);if(b=s(b,z),!g)return b;return vp([],I,b,z,w,e,z?.abortEarly===!0)}return n(b,z)}});Ep=y("$ZodUnion",(e,t)=>{U.init(e,t),P(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),P(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),P(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),P(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((i)=>i._zod.pattern);return new RegExp(`^(${o.map((i)=>$r(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of t.options){let l=a._zod.run({value:r.value,issues:[]},o);if(l instanceof Promise)s.push(l),i=!0;else{if(l.issues.length===0)return l;s.push(l)}}if(!i)return Ld(s,r,e,o);return Promise.all(s).then((a)=>Ld(a,r,e,o))}}),Ip=y("$ZodIntersection",(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([l,d])=>Dd(n,l,d));return Dd(n,i,s)}});Cp=y("$ZodRecord",(e,t)=>{U.init(e,t);let n=oe.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!wt(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let l=new Set;for(let f of a)if(typeof f==="string"||typeof f==="number"||typeof f==="symbol"){if(l.add(typeof f==="number"?f.toString():f),f==="__proto__")continue;let g=t.keyType._zod.run({value:f,issues:[]},o);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(g.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map((z)=>Ee(z,o,ie())),input:f,path:[f],inst:e});continue}let w=g.value;if(w==="__proto__")continue;let b=t.valueType._zod.run({value:i[f],issues:[]},o);if(b instanceof Promise)s.push(b.then((z)=>{if(z.issues.length)r.issues.push(...Ye(f,z.issues));r.value[w]=z.value}));else{if(b.issues.length)r.issues.push(...Ye(f,b.issues));r.value[w]=b.value}}let d;for(let f in i)if(!l.has(f))if(t.mode==="loose"){if(f==="__proto__")continue;r.value[f]=i[f]}else d=d??[],d.push(f);if(d&&d.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let l;for(let d of Reflect.ownKeys(i)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,d))continue;let f=t.keyType._zod.run({value:d,issues:[]},o);if(f instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&yn.test(d)&&f.issues.length){let z=t.keyType._zod.run({value:Number(d),issues:[]},o);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length===0)f=z}if(f.issues.length){if(t.mode==="loose")r.value[d]=i[d];else if(a)l=l??[],l.push(d);else r.issues.push({code:"invalid_key",origin:"record",issues:f.issues.map((z)=>Ee(z,o,ie())),input:d,path:[d],inst:e});continue}let w=f.value;if(w==="__proto__")continue;let b=t.valueType._zod.run({value:i[d],issues:[]},o);if(b instanceof Promise)s.push(b.then((z)=>{if(z.issues.length)r.issues.push(...Ye(d,z.issues));r.value[w]=z.value}));else{if(b.issues.length)r.issues.push(...Ye(d,b.issues));r.value[w]=b.value}}if(l&&l.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:l,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}}),Tp=y("$ZodEnum",(e,t)=>{U.init(e,t);let n=wn(t.entries),r=new Set(n);e._zod.values=r,P(e,"pattern",(o)=>{let i=wn(o.def.entries).filter((s)=>zl.has(typeof s));return new RegExp(i.length?`^(${i.map((s)=>Je(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),Ap=y("$ZodLiteral",(e,t)=>{U.init(e,t);let n=new Set(t.values);e._zod.values=n,P(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((i)=>typeof i==="string"?Je(i):i?Je(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let i=r.value;if(n.has(i))return r;return r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Rp=y("$ZodTransform",(e,t)=>{U.init(e,t),e._zod.optin="optional",oe.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new bn(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(n.value=s,n));if(o instanceof Promise)throw new Ie;return n.value=o,n}});os=y("$ZodOptional",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",P(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),P(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${$r(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>Md(n,i));return Md(n,o)}return t.innerType._zod.run(n,r)}}),Op=y("$ZodExactOptional",(e,t)=>{os.init(e,t),P(e,"values",(n)=>n.def.innerType._zod.values),P(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),Np=y("$ZodNullable",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin),P(e,"optout",(n)=>n.def.innerType._zod.optout),P(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${$r(r.source)}|null)$`):void 0}),P(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),Pp=y("$ZodDefault",(e,t)=>{U.init(e,t),e._zod.optin="defaulted",P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>jd(i,t));return jd(o,t)}});Lp=y("$ZodPrefault",(e,t)=>{U.init(e,t),e._zod.optin="defaulted",P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),Dp=y("$ZodNonOptional",(e,t)=>{U.init(e,t),P(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>Ud(i,e));return Ud(o,e)}});Mp=y("$ZodCatch",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),P(e,"optout",(n)=>n.def.innerType._zod.optout),P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>Zd(n,i,t,r));return Zd(n,o,t,r)}}),is=y("$ZodPipe",(e,t)=>{U.init(e,t),P(e,"values",(n)=>n.def.in._zod.values),P(e,"optin",(n)=>n.def.in._zod.optin),P(e,"optout",(n)=>n.def.out._zod.optout),P(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let i=t.out._zod.run(n,r);if(i instanceof Promise)return i.then((s)=>Br(s,t.in,r));return Br(i,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>Br(i,t.out,r));return Br(o,t.out,r)}});jp=y("$ZodPreprocess",(e,t)=>{is.init(e,t)}),Up=y("$ZodReadonly",(e,t)=>{U.init(e,t),P(e,"propValues",(n)=>n.def.innerType._zod.propValues),P(e,"values",(n)=>n.def.innerType._zod.values),P(e,"optin",(n)=>n.def.innerType?._zod?.optin),P(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(Bd);return Bd(o)}});Zp=y("$ZodCustom",(e,t)=>{J.init(e,t),U.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((i)=>Fd(i,n,r,e));Fd(o,n,r,e);return}})});function Vp(e){return e!==null&&typeof e==="object"}function as(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}function Jr(e,t,n){let r=qp.get(e);if(r!==void 0)return r?Sn:kn;if(t.has(e))return Sn;t.add(e);let o=kn,i=(f)=>{if(o!==Sn&&f?._zod){let g=Jr(f,t,n);if(g>o)o=g}},s=(f,g)=>{let w=kn;for(let b of Reflect.ownKeys(f)){let z=Object.getOwnPropertyDescriptor(f,b);if(g&&!z.enumerable)continue;let I=z.get?Kr:z.value?._zod?Jr(z.value,t,n):kn;if(I>w)w=I}return w},a=(f)=>{if(f>o)o=f},l=e._zod.def,d=l.type;switch(d){case"object":{let f=Er(l);a(f?s(f,!0):Kr),i(l.catchall);break}case"array":i(l.element);break;case"tuple":for(let f of l.items)i(f);i(l.rest);break;case"record":case"map":i(l.keyType),i(l.valueType);break;case"set":i(l.valueType);break;case"union":for(let f of l.options)i(f);break;case"intersection":i(l.left),i(l.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(l.innerType);break;case"pipe":i(l.in),i(l.out);break;case"function":i(l.input),i(l.output);break;case"lazy":{let f=l._cachedInner??(n?e._zod.innerType:void 0);a(f?Jr(f,t,!1):Kr);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let f in l){let g=Object.getOwnPropertyDescriptor(l,f);if(!g||g.get)continue;let w=g.value;if(!w||typeof w!=="object")continue;if(w._zod)i(w);else if(Array.isArray(w))for(let b of w)i(b)}}return t.delete(e),hz(e,o)}function hz(e,t){if(t!==Kr)qp.set(e,t===Sn);return t}function gz(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}function us(){return wz}function _z(e,t){let n=e[cs]?.backEdges;return n!==void 0&&Vp(t)&&n.has(t)}var Fp,cs="~memo",Bp,qp,kn=0,Kr=1,Sn=2,Gr,Wr,wz;var Hp=S(()=>{re();Fp=class Fp extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}};Bp=[];qp=new WeakMap;Wr=[],wz={alloc(e,t,n){let r=Gr;if(!r)return n;Gr=void 0;let o={value:n,issues:null};return r.set(t.value,o),Wr.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,i)=>{if(i.direction!=="backward"&&_z(i,o.value))throw new Fp;return n(o,i)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(l,d)=>{if(n===void 0){let A=Jr(e,new Set,!1);if(A===kn){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(l,d)}if(A===Sn||r)n=!0;else r=!0}let f=l.value;if(!Vp(f))return s(l,d);let g=d[cs];if(!g)g={buckets:new WeakMap,backEdges:void 0},d[cs]=g;let w;if(o===d)w=i;else w=gz(g,e),o=d,i=w;let b=w.get(f);if(b){if(l.value=b.value,b.issues){if(b.issues.length)l.issues.push(...as(b.issues))}else l.memo=!0,g.backEdges??(g.backEdges=new WeakSet),g.backEdges.add(b.value);return l}Gr=w;let z=Wr.length,I=s(l,d);Gr=void 0;let E=Wr.length>z?Wr.pop():void 0;if(I instanceof Promise)return I.then((A)=>{if(E)E.issues=A.issues.length?as(A.issues):Bp;return A});if(E)E.issues=I.issues.length?as(I.issues):Bp;return I};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}}});function ls(){return{localeError:bz()}}var bz=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return e[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,s){if(i==="number"&&typeof s==="number"&&!Number.isFinite(s))return String(s);return r[i]??i}return(i)=>{switch(i.code){case"invalid_type":{let s=o(i.expected),a=$l(i.input),l=o(a,i.input);return`Invalid input: expected ${s}, received ${l}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${Li(i.values[0])}`;return`Invalid option: expected one of ${Oi(i.values,"|")}`;case"too_big":{let s=i.exact?"exactly ":i.inclusive?"<=":"<",a=t(i.origin);if(a)return`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.exact?"exactly ":i.inclusive?">=":">",a=t(i.origin);if(a)return`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`;return`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Oi(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0)return`Invalid discriminator value. Expected ${i.options.map((a)=>`'${a}'`).join(" | ")}`;if(i.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};var Gp=S(()=>{re()});var ds=()=>{};class Jp{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function Yp(){return new Jp}var Kp,Xe;var ps=S(()=>{(Kp=globalThis).__zod_globalRegistry??(Kp.__zod_globalRegistry=Yp());Xe=globalThis.__zod_globalRegistry});var Xp=()=>{};function Qp(e){if(e.checks)e.checks=[...e.checks];return e}function ef(e,t){return new e(Qp({type:"string",...v(t)}))}function tf(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...v(t)})}function nf(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...v(t)})}function rf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...v(t)})}function of(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...v(t)})}function sf(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...v(t)})}function af(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...v(t)})}function fs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...v(t)})}function cf(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...v(t)})}function uf(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...v(t)})}function lf(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...v(t)})}function df(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...v(t)})}function pf(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...v(t)})}function ff(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...v(t)})}function mf(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...v(t)})}function hf(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...v(t)})}function gf(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...v(t)})}function wf(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...v(t)})}function _f(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...v(t)})}function bf(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...v(t)})}function yf(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...v(t)})}function zf(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...v(t)})}function xf(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...v(t)})}function kf(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...v(t)})}function Sf(e,t){return new e({type:"string",format:"date",check:"string_format",...v(t)})}function vf(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...v(t)})}function $f(e,t){return new e({type:"string",format:"duration",check:"string_format",...v(t)})}function Ef(e,t){return new e(Qp({type:"number",checks:[],...v(t)}))}function If(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...v(t)})}function Cf(e,t){return new e({type:"boolean",...v(t)})}function Tf(e,t){return new e({type:"null",...v(t)})}function Af(e){return new e({type:"unknown"})}function Rf(e,t){return new e({type:"never",...v(t)})}function Yr(e,t){return new Ji({check:"less_than",...v(t),value:e,inclusive:!1})}function vn(e,t){return new Ji({check:"less_than",...v(t),value:e,inclusive:!0})}function Xr(e,t){return new Yi({check:"greater_than",...v(t),value:e,inclusive:!1})}function $n(e,t){return new Yi({check:"greater_than",...v(t),value:e,inclusive:!0})}function Qr(e,t){return new yd({check:"multiple_of",...v(t),value:e})}function eo(e,t){return new xd({check:"max_length",...v(t),maximum:e})}function jt(e,t){return new kd({check:"min_length",...v(t),minimum:e})}function to(e,t){return new Sd({check:"length_equals",...v(t),length:e})}function ms(e,t){return new vd({check:"string_format",format:"regex",...v(t),pattern:e})}function hs(e){return new $d({check:"string_format",format:"lowercase",...v(e)})}function gs(e){return new Ed({check:"string_format",format:"uppercase",...v(e)})}function ws(e,t){return new Id({check:"string_format",format:"includes",...v(t),includes:e})}function _s(e,t){return new Cd({check:"string_format",format:"starts_with",...v(t),prefix:e})}function bs(e,t){return new Td({check:"string_format",format:"ends_with",...v(t),suffix:e})}function Qe(e){return new Ad({check:"overwrite",tx:e})}function ys(e){return Qe((t)=>t.normalize(e))}function zs(){return Qe((e)=>e.trim())}function xs(){return Qe((e)=>e.toLowerCase())}function ks(){return Qe((e)=>e.toUpperCase())}function Ss(){return Qe((e)=>bl(e))}function Of(e,t,n){return new e({type:"array",element:t,...v(n)})}function Nf(e,t,n){return new e({type:"custom",check:"custom",fn:t,...v(n)})}function Pf(e,t){let n=yz((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(_t(o,r.value,n._zod.def));else{let i=o;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(_t(i))}},e(r.value,r)),t);return n}function yz(e,t){let n=new J({check:"custom",...v(t)});return n._zod.check=e,n}var Lf=S(()=>{Zr();re()});function En(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))_e(e,r,n[r]);return e}function $s(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Xe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ze(e,t,n,r,o){let i=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw Error(o);return Object.assign(n,i),!0}function q(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,n.schemaPath.includes(e))i.cycle=n.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let f={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,f);else{let w=s.schema,b=t.processors[o.type];if(!b)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);b(e,t,w,f)}let g=e._zod.parent;if(g){if(!s.ref)s.ref=g;q(g,t,f),t.seen.get(g).isParent=!0}}let l=t.metadataRegistry.get(e);if(l)En(s.schema,l);if(t.io==="input"&&te(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function Df(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function Es(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let l=r.get(a);if(l&&l!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let o=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let g=e.external.registry.get(s[0])?.id,w=e.external.uri??((z)=>z);if(g)return{ref:w(g)};let b=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=b,{defId:b,ref:`${w("__shared")}#/${a}/${Df(b)}`}}let l="#",d=`${l}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:l};let f=s[1].schema.id??`__schema${e.counter++}`;return{defId:f,ref:d+Df(f)}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:d}=o(s);if(a.def={...a.schema},d)a.defId=d;let f=a.schema;for(let g in f)delete f[g];f.$ref=l};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
64
+ `)}return k.write("payload.value = newResult;"),k.write("return payload;"),k.compile()},s,a=kn,u=!oe.jitless,p=u&&Ul.value,g=t.catchall,w;e._zod.parse=(b,z)=>{w??(w=r.value);let I=b.value;if(!a(I))return b.issues.push({expected:"object",code:"invalid_type",input:I,inst:e}),b;if(u&&p&&z?.async===!1&&z.jitless!==!0){if(!s)s=i(t.shape);if(b=s(b,z),!g)return b;return Hf([],I,b,z,w,e,z?.abortEarly===!0)}return n(b,z)}});Wf=y("$ZodUnion",(e,t)=>{U.init(e,t),P(e,"optin",(r)=>r.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),P(e,"optout",(r)=>r.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),P(e,"values",(r)=>{if(r.def.options.every((o)=>o._zod.values))return new Set(r.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),P(e,"pattern",(r)=>{if(r.def.options.every((o)=>o._zod.pattern)){let o=r.def.options.map((i)=>i._zod.pattern);return new RegExp(`^(${o.map((i)=>Rr(i.source)).join("|")})$`)}return});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,o)=>{if(n)return n(r,o);let i=!1,s=[];for(let a of t.options){let u=a._zod.run({value:r.value,issues:[]},o);if(u instanceof Promise)s.push(u),i=!0;else{if(u.issues.length===0)return u;s.push(u)}}if(!i)return nf(s,r,e,o);return Promise.all(s).then((a)=>nf(a,r,e,o))}}),Kf=y("$ZodIntersection",(e,t)=>{U.init(e,t),e._zod.parse=(n,r)=>{let o=n.value,i=t.left._zod.run({value:o,issues:[]},r),s=t.right._zod.run({value:o,issues:[]},r);if(i instanceof Promise||s instanceof Promise)return Promise.all([i,s]).then(([u,d])=>rf(n,u,d));return rf(n,i,s)}});Jf=y("$ZodRecord",(e,t)=>{U.init(e,t);let n=oe.memoizer;n?.attach(e),e._zod.parse=(r,o)=>{let i=r.value;if(!zt(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),r;let s=[],a=t.keyType._zod.values;if(a&&!t.partial){r.value=n?n.alloc(e,r,{},o):{};let u=new Set;for(let p of a)if(typeof p==="string"||typeof p==="number"||typeof p==="symbol"){if(u.add(typeof p==="number"?p.toString():p),p==="__proto__")continue;let g=t.keyType._zod.run({value:p,issues:[]},o);if(g instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(g.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:g.issues.map((z)=>Ee(z,o,ie())),input:p,path:[p],inst:e});continue}let w=g.value;if(w==="__proto__")continue;let b=t.valueType._zod.run({value:i[p],issues:[]},o);if(b instanceof Promise)s.push(b.then((z)=>{if(z.issues.length)r.issues.push(...Ye(p,z.issues));r.value[w]=z.value}));else{if(b.issues.length)r.issues.push(...Ye(p,b.issues));r.value[w]=b.value}}let d;for(let p in i)if(!u.has(p))if(t.mode==="loose"){if(p==="__proto__")continue;r.value[p]=i[p]}else d=d??[],d.push(p);if(d&&d.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:d,continue:!0})}else{r.value=n?n.alloc(e,r,{},o):{};let u;for(let d of Reflect.ownKeys(i)){if(d==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(i,d))continue;let p=t.keyType._zod.run({value:d,issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof d==="string"&&En.test(d)&&p.issues.length){let z=t.keyType._zod.run({value:Number(d),issues:[]},o);if(z instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(z.issues.length===0)p=z}if(p.issues.length){if(t.mode==="loose")r.value[d]=i[d];else if(a)u=u??[],u.push(d);else r.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((z)=>Ee(z,o,ie())),input:d,path:[d],inst:e});continue}let w=p.value;if(w==="__proto__")continue;let b=t.valueType._zod.run({value:i[d],issues:[]},o);if(b instanceof Promise)s.push(b.then((z)=>{if(z.issues.length)r.issues.push(...Ye(d,z.issues));r.value[w]=z.value}));else{if(b.issues.length)r.issues.push(...Ye(d,b.issues));r.value[w]=b.value}}if(u&&u.length>0)r.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:u,continue:!0})}if(s.length)return Promise.all(s).then(()=>r);return r}}),Yf=y("$ZodEnum",(e,t)=>{U.init(e,t);let n=Sn(t.entries),r=new Set(n);e._zod.values=r,P(e,"pattern",(o)=>{let i=Sn(o.def.entries).filter((s)=>Zl.has(typeof s));return new RegExp(i.length?`^(${i.map((s)=>Je(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,i)=>{let s=o.value;if(r.has(s))return o;return o.issues.push({code:"invalid_value",values:n,input:s,inst:e}),o}}),Xf=y("$ZodLiteral",(e,t)=>{U.init(e,t);let n=new Set(t.values);e._zod.values=n,P(e,"pattern",(r)=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map((i)=>typeof i==="string"?Je(i):i?Je(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(r,o)=>{let i=r.value;if(n.has(i))return r;return r.issues.push({code:"invalid_value",values:t.values,input:i,inst:e}),r}}),Qf=y("$ZodTransform",(e,t)=>{U.init(e,t),e._zod.optin="optional",oe.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new $n(e.constructor.name);let o=t.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then((s)=>(n.value=s,n));if(o instanceof Promise)throw new Ie;return n.value=o,n}});gs=y("$ZodOptional",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",P(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),P(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Rr(r.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(n.value===void 0){if(t.innerType._zod.optin!=="defaulted")return n;let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>of(n,i));return of(n,o)}return t.innerType._zod.run(n,r)}}),ep=y("$ZodExactOptional",(e,t)=>{gs.init(e,t),P(e,"values",(n)=>n.def.innerType._zod.values),P(e,"pattern",(n)=>n.def.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),tp=y("$ZodNullable",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin),P(e,"optout",(n)=>n.def.innerType._zod.optout),P(e,"pattern",(n)=>{let r=n.def.innerType._zod.pattern;return r?new RegExp(`^(${Rr(r.source)}|null)$`):void 0}),P(e,"values",(n)=>n.def.innerType._zod.values?new Set([...n.def.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>{if(n.value===null)return n;return t.innerType._zod.run(n,r)}}),np=y("$ZodDefault",(e,t)=>{U.init(e,t),e._zod.optin="defaulted",P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>sf(i,t));return sf(o,t)}});rp=y("$ZodPrefault",(e,t)=>{U.init(e,t),e._zod.optin="defaulted",P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)n.value=t.defaultValue;return t.innerType._zod.run(n,r)}}),op=y("$ZodNonOptional",(e,t)=>{U.init(e,t),P(e,"values",(n)=>{let r=n.def.innerType._zod.values;return r?new Set([...r].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(n,r)=>{let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>af(i,e));return af(o,e)}});ip=y("$ZodCatch",(e,t)=>{U.init(e,t),P(e,"optin",(n)=>n.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),P(e,"optout",(n)=>n.def.innerType._zod.optout),P(e,"values",(n)=>n.def.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run({value:n.value,issues:[]},r);if(o instanceof Promise)return o.then((i)=>cf(n,i,t,r));return cf(n,o,t,r)}}),ws=y("$ZodPipe",(e,t)=>{U.init(e,t),P(e,"values",(n)=>n.def.in._zod.values),P(e,"optin",(n)=>n.def.in._zod.optin),P(e,"optout",(n)=>n.def.out._zod.optout),P(e,"propValues",(n)=>n.def.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){let i=t.out._zod.run(n,r);if(i instanceof Promise)return i.then((s)=>Wr(s,t.in,r));return Wr(i,t.in,r)}let o=t.in._zod.run(n,r);if(o instanceof Promise)return o.then((i)=>Wr(i,t.out,r));return Wr(o,t.out,r)}});sp=y("$ZodPreprocess",(e,t)=>{ws.init(e,t)}),ap=y("$ZodReadonly",(e,t)=>{U.init(e,t),P(e,"propValues",(n)=>n.def.innerType._zod.propValues),P(e,"values",(n)=>n.def.innerType._zod.values),P(e,"optin",(n)=>n.def.innerType?._zod?.optin),P(e,"optout",(n)=>n.def.innerType?._zod?.optout),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);let o=t.innerType._zod.run(n,r);if(o instanceof Promise)return o.then(uf);return uf(o)}});cp=y("$ZodCustom",(e,t)=>{J.init(e,t),U.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=(n)=>{let r=n.value,o=t.fn(r);if(o instanceof Promise)return o.then((i)=>lf(i,n,r,e));lf(o,n,r,e);return}})});function dp(e){return e!==null&&typeof e==="object"}function bs(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}function no(e,t,n){let r=fp.get(e);if(r!==void 0)return r?An:Tn;if(t.has(e))return An;t.add(e);let o=Tn,i=(p)=>{if(o!==An&&p?._zod){let g=no(p,t,n);if(g>o)o=g}},s=(p,g)=>{let w=Tn;for(let b of Reflect.ownKeys(p)){let z=Object.getOwnPropertyDescriptor(p,b);if(g&&!z.enumerable)continue;let I=z.get?to:z.value?._zod?no(z.value,t,n):Tn;if(I>w)w=I}return w},a=(p)=>{if(p>o)o=p},u=e._zod.def,d=u.type;switch(d){case"object":{let p=Or(u);a(p?s(p,!0):to),i(u.catchall);break}case"array":i(u.element);break;case"tuple":for(let p of u.items)i(p);i(u.rest);break;case"record":case"map":i(u.keyType),i(u.valueType);break;case"set":i(u.valueType);break;case"union":for(let p of u.options)i(p);break;case"intersection":i(u.left),i(u.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":i(u.innerType);break;case"pipe":i(u.in),i(u.out);break;case"function":i(u.input),i(u.output);break;case"lazy":{let p=u._cachedInner??(n?e._zod.innerType:void 0);a(p?no(p,t,!1):to);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let p in u){let g=Object.getOwnPropertyDescriptor(u,p);if(!g||g.get)continue;let w=g.value;if(!w||typeof w!=="object")continue;if(w._zod)i(w);else if(Array.isArray(w))for(let b of w)i(b)}}return t.delete(e),qz(e,o)}function qz(e,t){if(t!==to)fp.set(e,t===An);return t}function Hz(e,t){let n=e.buckets.get(t);if(!n)n=new WeakMap,e.buckets.set(t,n);return n}function zs(){return Gz}function Wz(e,t){let n=e[ys]?.backEdges;return n!==void 0&&dp(t)&&n.has(t)}var lp,ys="~memo",up,fp,Tn=0,to=1,An=2,Qr,eo,Gz;var pp=v(()=>{re();lp=class lp extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}};up=[];fp=new WeakMap;eo=[],Gz={alloc(e,t,n){let r=Qr;if(!r)return n;Qr=void 0;let o={value:n,issues:null};return r.set(t.value,o),eo.push(o),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let n=e._zod.parse,r=(o,i)=>{if(i.direction!=="backward"&&Wz(i,o.value))throw new lp;return n(o,i)};if(e._zod.parse=r,e._zod.run===n)e._zod.run=r})},attach(e){var t;let n,r=!1,o,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let s=e._zod.parse,a=(u,d)=>{if(n===void 0){let A=no(e,new Set,!1);if(A===Tn){if(e._zod.parse=s,e._zod.run===a)e._zod.run=s;return s(u,d)}if(A===An||r)n=!0;else r=!0}let p=u.value;if(!dp(p))return s(u,d);let g=d[ys];if(!g)g={buckets:new WeakMap,backEdges:void 0},d[ys]=g;let w;if(o===d)w=i;else w=Hz(g,e),o=d,i=w;let b=w.get(p);if(b){if(u.value=b.value,b.issues){if(b.issues.length)u.issues.push(...bs(b.issues))}else u.memo=!0,g.backEdges??(g.backEdges=new WeakSet),g.backEdges.add(b.value);return u}Qr=w;let z=eo.length,I=s(u,d);Qr=void 0;let k=eo.length>z?eo.pop():void 0;if(I instanceof Promise)return I.then((A)=>{if(k)k.issues=A.issues.length?bs(A.issues):up;return A});if(k)k.issues=I.issues.length?bs(I.issues):up;return I};if(e._zod.parse=a,e._zod.run===s)e._zod.run=a})}}});function xs(){return{localeError:Kz()}}var Kz=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(i){return e[i]??null}let n={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,s){if(i==="number"&&typeof s==="number"&&!Number.isFinite(s))return String(s);return r[i]??i}return(i)=>{switch(i.code){case"invalid_type":{let s=o(i.expected),a=Hl(i.input),u=o(a,i.input);return`Invalid input: expected ${s}, received ${u}`}case"invalid_value":if(i.values.length===1)return`Invalid input: expected ${Wi(i.values[0])}`;return`Invalid option: expected one of ${qi(i.values,"|")}`;case"too_big":{let s=i.exact?"exactly ":i.inclusive?"<=":"<",a=t(i.origin);if(a)return`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.exact?"exactly ":i.inclusive?">=":">",a=t(i.origin);if(a)return`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`;return`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;if(s.format==="starts_with")return`Invalid string: must start with "${s.prefix}"`;if(s.format==="ends_with")return`Invalid string: must end with "${s.suffix}"`;if(s.format==="includes")return`Invalid string: must include "${s.includes}"`;if(s.format==="regex")return`Invalid string: must match pattern ${s.pattern}`;return`Invalid ${n[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${qi(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":if(i.options&&Array.isArray(i.options)&&i.options.length>0)return`Invalid discriminator value. Expected ${i.options.map((a)=>`'${a}'`).join(" | ")}`;if(i.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};var mp=v(()=>{re()});var ks=()=>{};class wp{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==="object"&&"id"in n)this._idmap.set(n.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function _p(){return new wp}var gp,Xe;var Ss=v(()=>{(gp=globalThis).__zod_globalRegistry??(gp.__zod_globalRegistry=_p());Xe=globalThis.__zod_globalRegistry});var bp=()=>{};function yp(e){if(e.checks)e.checks=[...e.checks];return e}function zp(e,t){return new e(yp({type:"string",...E(t)}))}function xp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...E(t)})}function kp(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...E(t)})}function Sp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...E(t)})}function vp(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...E(t)})}function $p(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...E(t)})}function Ep(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...E(t)})}function vs(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...E(t)})}function Ip(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...E(t)})}function Cp(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...E(t)})}function Tp(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...E(t)})}function Ap(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...E(t)})}function Rp(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...E(t)})}function Op(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...E(t)})}function Np(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...E(t)})}function Pp(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...E(t)})}function Lp(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...E(t)})}function Mp(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...E(t)})}function Dp(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...E(t)})}function jp(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...E(t)})}function Up(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...E(t)})}function Zp(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...E(t)})}function Bp(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...E(t)})}function Fp(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...E(t)})}function Vp(e,t){return new e({type:"string",format:"date",check:"string_format",...E(t)})}function qp(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...E(t)})}function Hp(e,t){return new e({type:"string",format:"duration",check:"string_format",...E(t)})}function Gp(e,t){return new e(yp({type:"number",checks:[],...E(t)}))}function Wp(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...E(t)})}function Kp(e,t){return new e({type:"boolean",...E(t)})}function Jp(e,t){return new e({type:"null",...E(t)})}function Yp(e){return new e({type:"unknown"})}function Xp(e,t){return new e({type:"never",...E(t)})}function ro(e,t){return new cs({check:"less_than",...E(t),value:e,inclusive:!1})}function Rn(e,t){return new cs({check:"less_than",...E(t),value:e,inclusive:!0})}function oo(e,t){return new us({check:"greater_than",...E(t),value:e,inclusive:!1})}function On(e,t){return new us({check:"greater_than",...E(t),value:e,inclusive:!0})}function io(e,t){return new Ud({check:"multiple_of",...E(t),value:e})}function so(e,t){return new Bd({check:"max_length",...E(t),maximum:e})}function qt(e,t){return new Fd({check:"min_length",...E(t),minimum:e})}function ao(e,t){return new Vd({check:"length_equals",...E(t),length:e})}function $s(e,t){return new qd({check:"string_format",format:"regex",...E(t),pattern:e})}function Es(e){return new Hd({check:"string_format",format:"lowercase",...E(e)})}function Is(e){return new Gd({check:"string_format",format:"uppercase",...E(e)})}function Cs(e,t){return new Wd({check:"string_format",format:"includes",...E(t),includes:e})}function Ts(e,t){return new Kd({check:"string_format",format:"starts_with",...E(t),prefix:e})}function As(e,t){return new Jd({check:"string_format",format:"ends_with",...E(t),suffix:e})}function Qe(e){return new Yd({check:"overwrite",tx:e})}function Rs(e){return Qe((t)=>t.normalize(e))}function Os(){return Qe((e)=>e.trim())}function Ns(){return Qe((e)=>e.toLowerCase())}function Ps(){return Qe((e)=>e.toUpperCase())}function Ls(){return Qe((e)=>jl(e))}function Qp(e,t,n){return new e({type:"array",element:t,...E(n)})}function em(e,t,n){return new e({type:"custom",check:"custom",fn:t,...E(n)})}function tm(e,t){let n=Jz((r)=>(r.addIssue=(o)=>{if(typeof o==="string")r.issues.push(xt(o,r.value,n._zod.def));else{let i=o;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(xt(i))}},e(r.value,r)),t);return n}function Jz(e,t){let n=new J({check:"custom",...E(t)});return n._zod.check=e,n}var nm=v(()=>{Gr();re()});function Nn(e,...t){for(let n of t)for(let r of Reflect.ownKeys(n))if(Object.prototype.propertyIsEnumerable.call(n,r))_e(e,r,n[r]);return e}function Ds(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??Xe,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Be(e,t,n,r,o){let i=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:r.path,message:o}):t.unrepresentable;if(i==="any")return!1;if(i===void 0||i==="throw")throw Error(o);return Object.assign(n,i),!0}function H(e,t,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,i=t.seen.get(e);if(i){if(i.count++,n.schemaPath.includes(e))i.cycle=n.path;return i.schema}let s={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,s),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)s.schema=a;else{let p={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,s.schema,p);else{let w=s.schema,b=t.processors[o.type];if(!b)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);b(e,t,w,p)}let g=e._zod.parent;if(g){if(!s.ref)s.ref=g;H(g,t,p),t.seen.get(g).isParent=!0}}let u=t.metadataRegistry.get(e);if(u)Nn(s.schema,u);if(t.io==="input"&&ee(e))delete s.schema.examples,delete s.schema.default;if(t.io==="input"&&"_prefault"in s.schema)(r=s.schema).default??(r.default=s.schema._prefault);return delete s.schema._prefault,t.seen.get(e).schema}function rm(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function js(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let s of e.seen.entries()){let a=e.metadataRegistry.get(s[0])?.id;if(a){let u=r.get(a);if(u&&u!==s[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(a,s[0])}}let o=(s)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let g=e.external.registry.get(s[0])?.id,w=e.external.uri??((z)=>z);if(g)return{ref:w(g)};let b=s[1].defId??s[1].schema.id??`schema${e.counter++}`;return s[1].defId=b,{defId:b,ref:`${w("__shared")}#/${a}/${rm(b)}`}}let u="#",d=`${u}/${a}/`;if(s[1]===n&&!s[1].schema.id)return{ref:u};let p=s[1].schema.id??`__schema${e.counter++}`;return{defId:p,ref:d+rm(p)}},i=(s)=>{if(s[1].schema.$ref)return;let a=s[1],{ref:u,defId:d}=o(s);if(a.def={...a.schema},d)a.defId=d;let p=a.schema;for(let g in p)delete p[g];p.$ref=u};if(e.cycles==="throw")for(let s of e.seen.entries()){let a=s[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
65
65
 
66
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref")i(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Uf(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;Uf(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let i=r.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!=="string")return;if(!n.includes(s))n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}function jf(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function vs(e){let t=[];for(let i of e){if(typeof i!=="object"||i.type!=="object")return null;for(let s in i)if(!Zf.has(s))return null;t.push(i)}let n={},r=new Set;for(let i of t){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;let a=[];for(let d of t){let f=d.properties?.[s]??jf(d);if(f===null||f===void 0)continue;if(!a.some((g)=>JSON.stringify(g)===JSON.stringify(f)))a.push(f)}let l=a.length===1?a[0]:vs(a)??{allOf:a};_e(n,s,l)}for(let s of i.required??[])r.add(s)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((i)=>i.additionalProperties===!1))o.additionalProperties=!1;else{let i=[];for(let s of t){let a=jf(s);if(a&&!i.some((l)=>JSON.stringify(l)===JSON.stringify(a)))i.push(a)}if(i.length===1)o.additionalProperties=i[0];else if(i.length>1)o.additionalProperties={allOf:i}}return o}function zz(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Zf)if(o in e)return;let n=t.filter((o)=>Mf.some((i)=>Array.isArray(o[i]))),r=null;if(!n.length)r=vs(t);else{let o=n[0],i=Mf.find((l)=>Array.isArray(o[l]));if(Object.keys(o).length!==1)return;let s=t.filter((l)=>l!==o),a=o[i].map((l)=>vs([...s,l]));if(a.some((l)=>!l))return;r={[i]:a}}if(!r)return;delete e.allOf,En(e,r)}function Is(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let l=e.seen.get(a);if(l.ref===null)return;let d=l.def??l.schema,f={...d},g=l.ref;if(l.ref=null,g){r(g);let b=e.seen.get(g),z=b.schema;if(z.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(z);else En(d,z);if(En(d,f),a._zod.parent===g)for(let E in d){if(E==="$ref"||E==="allOf")continue;if(!(E in f))delete d[E]}if(z.$ref&&b.def)for(let E in d){if(E==="$ref"||E==="allOf")continue;if(E in b.def&&JSON.stringify(d[E])===JSON.stringify(b.def[E]))delete d[E]}}let w=a._zod.parent;if(w&&w!==g){r(w);let b=e.seen.get(w);if(b?.schema.$ref){if(d.$ref=b.schema.$ref,b.def)for(let z in d){if(z==="$ref"||z==="allOf")continue;if(z in b.def&&JSON.stringify(d[z])===JSON.stringify(b.def[z]))delete d[z]}}}e.override({zodSchema:a,jsonSchema:d,path:l.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Uf(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let l of e.seen.values())for(let d of[l.schema,l.def]){let f=d?.allOf;if(!Array.isArray(f))continue;let g=a.get(f);if(g)g.push(d);else a.set(f,[d])}for(let l of e.intersections)for(let d of a.get(l)??[])zz(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}En(o,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let l=a[1];if(l.def&&l.defId){if(l.def.id===l.defId)delete l.def.id;_e(s,l.defId,l.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:In(t,"input",e.processors),output:In(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function te(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return te(r.element,n);if(r.type==="set")return te(r.valueType,n);if(r.type==="lazy")return te(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return te(r.innerType,n);if(r.type==="intersection")return te(r.left,n)||te(r.right,n);if(r.type==="record"||r.type==="map")return te(r.keyType,n)||te(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return te(r.in,n)||te(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(te(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(te(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(te(o,n))return!0;if(r.rest&&te(r.rest,n))return!0;return!1}return!1}var Zf,Mf,Bf=(e,t={})=>(n)=>{let r=$s({...n,processors:t});return q(e,r),Es(r,e),Is(r,e)},In=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:i}=r??{},s=$s({...o??{},target:i,io:t,processors:n});return q(e,s),Es(s,e),Is(s,e)};var no=S(()=>{ps();re();Zf=new Set(["type","properties","required","additionalProperties"]),Mf=["oneOf","anyOf"]});function pe(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let i of r)xz[i._zod.def.check]?.(t,i._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)Ut(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)Ut(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)Zt(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)Zt(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Gf(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)Kf(t,o.mime);for(let i of o.patterns??[])Wf(t,i);return t}function ro(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return ro(t.out);if(t.type==="catch")return ro(t.innerType);return e._zod.optin}function Cs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let z=e.get(t)?.def;if(!z)return t;let I=Cs(e,z,n);return I===z?t:I}for(let z of["anyOf","oneOf"]){let I=t[z];if(!Array.isArray(I))continue;let E=I.map((A)=>Cs(e,A,n));if(E.some((A,X)=>A!==I[X]))t={...t,[z]:E}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((z)=>z==="number"||z==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!i?.some((z)=>typeof z==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:l,exclusiveMaximum:d,multipleOf:f,format:g,id:w,...b}=t;if(b.enum)b.enum=b.enum.map((z)=>typeof z==="number"?String(z):z);else if(typeof b.const==="number")b.const=String(b.const);if(!o)return b;if(b.type="string",!i)b.pattern=(r.includes("number")?yn:Wi).source;return b}function vz(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of Ts.get(e)??[]){let o=e.seen.get(r),i=(o?.def??o?.schema)?.propertyNames;if(!i||i===!0||n.has(i))continue;let s=Cs(t,i,new Set);if(s!==i)n.set(i,s)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let i=o&&n.get(o.propertyNames);if(i)o.propertyNames=i}}function hm(e,t,n,r,o){let i=!1,s=JSON.stringify(e,(a,l)=>{if(typeof l!=="bigint")return l;return i=!0,null});if(!i)return JSON.parse(s);return Ze(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),As}var Ut=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Zt=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},Ff=(e,t)=>{Ut(e,"minimum",t),Zt(e,"maximum",t)},Gf=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Wf=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Kf=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},Jf=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Vf=(e,t)=>Ut(e,"minimum",t.minimum),qf=(e,t)=>Zt(e,"maximum",t.maximum),Hf=(e)=>(t,n)=>{Jf(t,n.format);let[r,o]=e[n.format];Ut(t,"minimum",r),Zt(t,"maximum",o)},xz,kz,Sz,Yf=(e)=>Sz.get(e)??e,Xf=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:l,contentEncoding:d,laxFormat:f}=pe(e);if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=kz[a]??a,o.format==="")delete o.format;if(a==="time"||f)delete o.format}if(d)o.contentEncoding=d;if(l&&l.size>0){let g=[...l].map(Yf);if(g.length===1)o.pattern=g[0].source;else if(g.length>1)o.allOf=[...g.map((w)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:w.source}))]}},Qf=(e,t,n,r)=>{let o=n,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:l,exclusiveMinimum:d,isInt:f}=pe(e);o.type=f?"integer":"number";let g=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),w=typeof l==="number"&&l<=(s??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";if(g)if(b)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(w)if(b)o.maximum=l,o.exclusiveMaximum=!0;else o.exclusiveMaximum=l;else if(typeof s==="number")o.maximum=s;if(a){let z=new Set;for(let A of a)if(Number.isFinite(A)&&A!==0)z.add(Math.abs(A));else Ze(e,t,o,r,`A multipleOf divisor of ${A} cannot be represented in JSON Schema`);let[I,...E]=z;if(I!==void 0)o.multipleOf=I;if(E.length)o.allOf=[...o.allOf??[],...E.map((A)=>({multipleOf:A}))]}},em=(e,t,n,r)=>{n.type="boolean"},tm=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},nm=(e,t,n,r)=>{n.not={}},rm=(e,t,n,r)=>{},om=(e,t,n,r)=>{let o=e._zod.def,i=wn(o.entries);if(i.length===0){n.not={};return}if(i.every((s)=>typeof s==="number"))n.type="number";if(i.every((s)=>typeof s==="string"))n.type="string";n.enum=i},im=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let i=[];for(let s of o.values)if(s===void 0){if(Ze(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==="bigint"){if(Ze(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(i.every((s)=>typeof s==="number"))n.type="number";if(i.every((s)=>typeof s==="string"))n.type="string";if(i.every((s)=>typeof s==="boolean"))n.type="boolean";if(i.every((s)=>s===null))n.type="null";n.enum=i}},sm=(e,t,n,r)=>{Ze(e,t,n,r,"Custom types cannot be represented in JSON Schema")},am=(e,t,n,r)=>{Ze(e,t,n,r,"Transforms cannot be represented in JSON Schema")},cm=(e,t,n,r)=>{let o=n,i=e._zod.def,{minimum:s,maximum:a}=pe(e);if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=q(i.element,t,{...r,path:[...r.path,"items"]})},um=(e,t,n,r)=>{let o=n,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Ze(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in s)_e(o.properties,d,q(s[d],t,{...r,path:[...r.path,"properties",d]}));let l=[];for(let d of Object.keys(s)){let f=i.shape[d];if(t.io==="input"?ro(f)===void 0:f._zod.optout===void 0)l.push(d)}if(l.length>0)o.required=l;if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=q(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},lm=(e,t,n,r)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,l)=>q(a,t,{...r,path:[...r.path,i?"oneOf":"anyOf",l]}));if(i)n.oneOf=s;else n.anyOf=s},dm=(e,t,n,r)=>{let o=e._zod.def,i=q(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=q(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,l=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=l,t.intersections.push(l)},Ts,pm=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object";let s=i.keyType,a=pe(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let f=q(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let g of a)_e(o.patternProperties,Yf(g).source,f)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=q(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});let f=Ts.get(t);if(!f)f=[],Ts.set(t,f),t.deferred.push(()=>vz(t));f.push(e)}o.additionalProperties=q(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let l=s._zod.values,d=t.io==="input"&&ro(i.valueType)!==void 0;if(l&&!i.partial&&!d){let f=[...l].filter((g)=>typeof g==="string"||typeof g==="number");if(f.length>0)o.required=f.map(String)}},fm=(e,t,n,r)=>{let o=e._zod.def,i=q(o.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,n.nullable=!0;else n.anyOf=[i,{type:"null"}]},mm=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},As,gm=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let s=hm(o.defaultValue,e,t,n,r);if(s!==As)n.default=s},wm=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);if(i.ref=o.innerType,t.io!=="input")return;let s=hm(o.defaultValue,e,t,n,r);if(s!==As)n._prefault=s},_m=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{Ze(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},bm=(e,t,n,r)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;q(s,t,r);let a=t.seen.get(e);a.ref=s},ym=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Rs=(e,t,n,r)=>{let o=e._zod.def;q(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType};var zm=S(()=>{zn();ss();no();re();xz={greater_than:(e,t)=>Ut(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Zt(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Gf(e,t.value),number_format:Hf(Ir),bigint_format:Hf(Di),min_length:Vf,max_length:qf,length_equals:(e,t)=>Ff(e,t.length),min_size:Vf,max_size:qf,size_equals:(e,t)=>Ff(e,t.size),string_format:(e,t)=>{if(Jf(e,t.format),t.pattern)Wf(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Kf(e,t.mime)};kz={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Sz=new Map([[ns,ad],[Hr,cd]]);Ts=new WeakMap;As=Symbol()});var xm=()=>{};var Ce=S(()=>{re();zn();ds();xm();bt();ql();Pl();ss();Hp();Zr();Qi();ps();Xp();Lf();no()});var Os=S(()=>{Ce()});function io(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var km,Oz=(e,t)=>{Nl.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(km.has(n))return;km.add(n),io(n,"format",(r)=>(o)=>Fi(r,o)),io(n,"flatten",(r)=>(o)=>Bi(r,o)),io(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,_n,2)}),io(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,_n,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},ae;var Ns=S(()=>{Ce();Ce();re();km=new WeakSet([Object.prototype,Error.prototype]);ae=y("ZodError",Oz,void 0,{Parent:Error})});var Sm,vm,$m,Em,Im,Cm,Tm,Am,Rm,Om,Nm,Pm;var Ps=S(()=>{Ce();Ns();Ce();Sm=Lr(ae),vm=Dr(ae),$m=Mr(ae),Em=jr(ae),Im=Dl(ae),Cm=Ml(ae),Tm=jl(ae),Am=Ul(ae),Rm=Zl(ae),Om=Bl(ae),Nm=Fl(ae),Pm=Vl(ae)});function Pz(){if(!oe.localeError)ie(ls())}function ao(){if(!oe.memoizer)ie({memoizer:us()})}function c(e){return ef(Lz,e)}function Bm(e){return fs(Zm,e)}function Be(e){return Ef(Fm,e)}function ce(e){return If(ox,e)}function H(e){return Cf(ix,e)}function co(e){return Tf(sx,e)}function m(){return Af(ax)}function ux(e){return Rf(cx,e)}function N(e,t){return Of(lx,e,t)}function p(e,t){let n={type:"object",shape:e??{},...v(t)};return new Vm(n)}function qm(e,t){return new Vm({type:"object",shape:e,catchall:m(),...v(t)})}function C(e,t){return new dx({type:"union",options:e,...v(t)})}function Te(e,t){return new px({type:"intersection",left:e,right:t})}function h(e,t,n){if(!t||!t._zod)return new Lm({type:"record",keyType:c(),valueType:e,...v(t)});return new Lm({type:"record",keyType:e,valueType:t,...v(n)})}function fx(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Ls({type:"enum",entries:n,...v(t)})}function _(e,t){return new mx({type:"literal",values:Array.isArray(e)?e:[e],...v(t)})}function Hm(e){return new hx({type:"transform",transform:e})}function Dm(e){return new Gm({type:"optional",innerType:e})}function gx(e){return new Wm({type:"optional",innerType:e})}function Mm(e){return new wx({type:"nullable",innerType:e})}function bx(e,t){return new _x({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Pi(t)}})}function zx(e,t){return new yx({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Pi(t)}})}function xx(e,t){return new Km({type:"nonoptional",innerType:e,...v(t)})}function Sx(e,t){return new kx({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Cl(t)})}function jm(e,t){return new Jm({type:"pipe",in:e,out:t})}function Ex(e){return new $x({type:"readonly",innerType:e})}function Cx(e,t={}){return Nf(Ix,e,t)}function Tx(e,t){return Pf(e,t)}function Ds(e,t){return new vx({type:"pipe",in:Hm(e),out:t})}var B,Um,Lz,F,Dz,Mz,jz,Uz,Zz,Bz,so,Zm,Fz,Vz,qz,Hz,Gz,Wz,Kz,Jz,Yz,Xz,Qz,ex,tx,nx,rx,Fm,ox,ix,sx,ax,cx,lx,Vm,dx,px,Lm,Ls,mx,hx,Gm,Wm,wx,_x,yx,Km,kx,Jm,vx,$x,Ix;var Ym=S(()=>{Ce();Ce();zm();no();Gp();Os();Ps();B=y("ZodType",(e,t)=>(Pz(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(se(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return be(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Cx(e,t))},superRefine(e,t){return this.check(Tx(e,t))},overwrite(e){return this.check(Qe(e))},optional(){return Dm(this)},exactOptional(){return gx(this)},nullable(){return Mm(this)},nullish(){return Dm(Mm(this))},nonoptional(e){return xx(this,e)},array(){return N(this)},or(e){return C([this,e])},and(e){return Te(this,e)},transform(e){return jm(this,Hm(e))},default(e){return bx(this,e)},prefault(e){return zx(this,e)},catch(e){return Sx(this,e)},pipe(e){return jm(this,e)},readonly(){return Ex(this)},describe(e){let t=this.clone();return Xe.add(t,{description:e}),t},meta(...e){if(e.length===0)return Xe.get(this);let t=this.clone();return Xe.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Or(this,"~standard",{...ts(this),jsonSchema:{input:In(this,"input"),output:In(this,"output")}})},set "~standard"(e){Ue(this,"~standard",e)},parse:function e(t,n){return Sm(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await vm(this,t,n,{callee:e})},safeParse(e,t){return $m(this,e,t)},async safeParseAsync(e,t){return Em(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ue(this,"spa",e)},validate(e,t){return Vi(this,e,t)},validateAsync(e,t){return qi(this,e,t)},encode:function e(t,n){return Im(this,t,n,{callee:e})},decode:function e(t,n){return Cm(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Tm(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Am(this,t,n,{callee:e})},safeEncode(e,t){return Rm(this,e,t)},safeDecode(e,t){return Om(this,e,t)},async safeEncodeAsync(e,t){return Nm(this,e,t)},async safeDecodeAsync(e,t){return Pm(this,e,t)},toJSONSchema(e){return Bf(this,{})(e)},get description(){return Xe.get(this)?.description},get _def(){return this._zod.def}}),Um=y("_ZodString",(e,t)=>{qr.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Xf(e,n,r,o)},Il({format:(e)=>pe(e).format??null,minLength:(e)=>pe(e).minimum??null,maxLength:(e)=>pe(e).maximum??null},{regex(...e){return this.check(ms(...e))},includes(...e){return this.check(ws(...e))},startsWith(...e){return this.check(_s(...e))},endsWith(...e){return this.check(bs(...e))},min(...e){return this.check(jt(...e))},max(...e){return this.check(eo(...e))},length(...e){return this.check(to(...e))},nonempty(...e){return this.check(jt(1,...e))},lowercase(e){return this.check(hs(e))},uppercase(e){return this.check(gs(e))},trim(){return this.check(zs())},normalize(...e){return this.check(ys(...e))},toLowerCase(){return this.check(xs())},toUpperCase(){return this.check(ks())},slugify(){return this.check(Ss())}})),Lz=y("ZodString",(e,t)=>{qr.init(e,t),Um.init(e,t)},{email(e){return this.check(tf(Zz,e))},url(e){return this.check(fs(Zm,e))},jwt(e){return this.check(xf(rx,e))},emoji(e){return this.check(cf(Fz,e))},guid(e){return this.check(nf(Bz,e))},uuid(e){return this.check(rf(so,e))},uuidv4(e){return this.check(of(so,e))},uuidv6(e){return this.check(sf(so,e))},uuidv7(e){return this.check(af(so,e))},nanoid(e){return this.check(uf(Vz,e))},cuid(e){return this.check(lf(qz,e))},cuid2(e){return this.check(df(Hz,e))},ulid(e){return this.check(pf(Gz,e))},base64(e){return this.check(bf(ex,e))},base64url(e){return this.check(yf(tx,e))},xid(e){return this.check(ff(Wz,e))},ksuid(e){return this.check(mf(Kz,e))},ipv4(e){return this.check(hf(Jz,e))},ipv6(e){return this.check(gf(Yz,e))},cidrv4(e){return this.check(wf(Xz,e))},cidrv6(e){return this.check(_f(Qz,e))},e164(e){return this.check(zf(nx,e))},datetime(e){return this.check(kf(Dz,e))},date(e){return this.check(Sf(Mz,e))},time(e){return this.check(vf(jz,e))},duration(e){return this.check($f(Uz,e))}});F=y("ZodStringFormat",(e,t)=>{Z.init(e,t),Um.init(e,t)}),Dz=y("ZodISODateTime",(e,t)=>{op.init(e,t),F.init(e,t)}),Mz=y("ZodISODate",(e,t)=>{ip.init(e,t),F.init(e,t)}),jz=y("ZodISOTime",(e,t)=>{sp.init(e,t),F.init(e,t)}),Uz=y("ZodISODuration",(e,t)=>{ap.init(e,t),F.init(e,t)}),Zz=y("ZodEmail",(e,t)=>{Gd.init(e,t),F.init(e,t)}),Bz=y("ZodGUID",(e,t)=>{qd.init(e,t),F.init(e,t)}),so=y("ZodUUID",(e,t)=>{Hd.init(e,t),F.init(e,t)}),Zm=y("ZodURL",(e,t)=>{Jd.init(e,t),F.init(e,t)});Fz=y("ZodEmoji",(e,t)=>{Yd.init(e,t),F.init(e,t)}),Vz=y("ZodNanoID",(e,t)=>{Xd.init(e,t),F.init(e,t)}),qz=y("ZodCUID",(e,t)=>{Qd.init(e,t),F.init(e,t)}),Hz=y("ZodCUID2",(e,t)=>{ep.init(e,t),F.init(e,t)}),Gz=y("ZodULID",(e,t)=>{tp.init(e,t),F.init(e,t)}),Wz=y("ZodXID",(e,t)=>{np.init(e,t),F.init(e,t)}),Kz=y("ZodKSUID",(e,t)=>{rp.init(e,t),F.init(e,t)}),Jz=y("ZodIPv4",(e,t)=>{cp.init(e,t),F.init(e,t)}),Yz=y("ZodIPv6",(e,t)=>{lp.init(e,t),F.init(e,t)}),Xz=y("ZodCIDRv4",(e,t)=>{dp.init(e,t),F.init(e,t)}),Qz=y("ZodCIDRv6",(e,t)=>{pp.init(e,t),F.init(e,t)}),ex=y("ZodBase64",(e,t)=>{mp.init(e,t),F.init(e,t)}),tx=y("ZodBase64URL",(e,t)=>{hp.init(e,t),F.init(e,t)}),nx=y("ZodE164",(e,t)=>{gp.init(e,t),F.init(e,t)}),rx=y("ZodJWT",(e,t)=>{wp.init(e,t),F.init(e,t)}),Fm=y("ZodNumber",(e,t)=>{rs.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Qf(e,n,r,o),e.isFinite=!0},Il({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=pe(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=pe(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=pe(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>pe(e).format??null},{gt(e,t){return this.check(Xr(e,t))},gte(e,t){return this.check($n(e,t))},min(e,t){return this.check($n(e,t))},lt(e,t){return this.check(Yr(e,t))},lte(e,t){return this.check(vn(e,t))},max(e,t){return this.check(vn(e,t))},int(e){return this.check(ce(e))},safe(e){return this.check(ce(e))},positive(e){return this.check(Xr(0,e))},nonnegative(e){return this.check($n(0,e))},negative(e){return this.check(Yr(0,e))},nonpositive(e){return this.check(vn(0,e))},multipleOf(e,t){return this.check(Qr(e,t))},step(e,t){return this.check(Qr(e,t))},finite(){return this}}));ox=y("ZodNumberFormat",(e,t)=>{_p.init(e,t),Fm.init(e,t)});ix=y("ZodBoolean",(e,t)=>{bp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>em(e,n,r,o)});sx=y("ZodNull",(e,t)=>{yp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>tm(e,n,r,o)});ax=y("ZodUnknown",(e,t)=>{zp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>rm(e,n,r,o)});cx=y("ZodNever",(e,t)=>{xp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>nm(e,n,r,o)});lx=y("ZodArray",(e,t)=>{ao(),kp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>cm(e,n,r,o),e.element=t.element},{min(e,t){return this.check(jt(e,t))},nonempty(e){return this.check(jt(1,e))},max(e,t){return this.check(eo(e,t))},length(e,t){return this.check(to(e,t))},unwrap(){return this.element}});Vm=y("ZodObject",(e,t)=>{ao(),$p.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>um(e,n,r,o),Fy(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return fx(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(se(this._zod.def,{catchall:e}))},passthrough(){return this.clone(se(this._zod.def,{catchall:m()}))},loose(){return this.clone(se(this._zod.def,{catchall:m()}))},strict(){return this.clone(se(this._zod.def,{catchall:ux()}))},strip(){return this.clone(se(this._zod.def,{catchall:void 0}))},extend(e){return Py(this,e)},safeExtend(e){return Ly(this,e)},merge(e){return Dy(this,e)},pick(e){return Oy(this,e)},omit(e){return Ny(this,e)},partial(...e){return Sl(Gm,this,e[0])},exactPartial(...e){return Sl(Wm,this,e[0],"exactPartial")},required(...e){return My(Km,this,e[0])}});dx=y("ZodUnion",(e,t)=>{Ep.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>lm(e,n,r,o),e.options=t.options});px=y("ZodIntersection",(e,t)=>{Ip.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>dm(e,n,r,o)});Lm=y("ZodRecord",(e,t)=>{ao(),Cp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>pm(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});Ls=y("ZodEnum",(e,t)=>{Tp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(r,o,i)=>om(e,r,o,i),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Ls({...t,checks:[],...v(o),entries:i})},e.exclude=(r,o)=>{let i={...t.entries};for(let s of r)if(n.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new Ls({...t,checks:[],...v(o),entries:i})}});mx=y("ZodLiteral",(e,t)=>{Ap.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>im(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});hx=y("ZodTransform",(e,t)=>{ao(),Rp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>am(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new bn(e.constructor.name);n.addIssue=(i)=>{if(typeof i==="string")n.issues.push(_t(i,n.value,t));else{let s=i;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=e),n.issues.push(_t(s))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((i)=>(n.value=i,n));return n.value=o,n}});Gm=y("ZodOptional",(e,t)=>{os.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Wm=y("ZodExactOptional",(e,t)=>{Op.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});wx=y("ZodNullable",(e,t)=>{Np.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>fm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});_x=y("ZodDefault",(e,t)=>{Pp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>gm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});yx=y("ZodPrefault",(e,t)=>{Lp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>wm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Km=y("ZodNonOptional",(e,t)=>{Dp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>mm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});kx=y("ZodCatch",(e,t)=>{Mp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_m(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});Jm=y("ZodPipe",(e,t)=>{is.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bm(e,n,r,o),e.in=t.in,e.out=t.out});vx=y("ZodPreprocess",(e,t)=>{Jm.init(e,t),jp.init(e,t)}),$x=y("ZodReadonly",(e,t)=>{Up.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ym(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Ix=y("ZodCustom",(e,t)=>{Zp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>sm(e,n,r,o)})});var Xm;var Qm=S(()=>{(function(e){})(Xm||(Xm={}))});var eh=()=>{};var th=()=>{};var nh=S(()=>{Ce();Ce();ds();eh();th();Ym();Os();Ns();Ps();Qm()});var rh=S(()=>{nh()});var uo=S(()=>{rh()});function u(e,t){return e.catch(t)}function Ae(e,t){let n=e.catch(t);return m().transform((r,o)=>{if(r!==void 0)return n.parse(r);return o.addIssue({code:"custom",message:"Required value is missing"}),Nr})}function ih(e,t){if(e===null||typeof e!=="object"||Array.isArray(e))return;let n=e[t];return typeof n==="string"?n:void 0}function yt(e,t,n){return e.superRefine((r,o)=>{let i=ih(r,t);if(i!==void 0&&n.includes(i))o.addIssue({code:"custom",path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function zt(e,t,n){return m().transform((r,o)=>{let i=e.safeParse(r);if(!i.success){for(let l of i.error.issues)o.addIssue({...l,input:r});return Nr}let s=i.data,a=ih(r,t);if(a!==void 0&&!n.includes(a)){let l=r;for(let[d,f]of Object.entries(l)){if(d==="__proto__")continue;if(!Object.hasOwn(s,d))s[d]=f}}return s})}function sh(e,t){return Ds((n)=>{if(n===null||typeof n!=="object"||Array.isArray(n))return n;let r=n,o=r[t];if(o===void 0||o===null||typeof o==="string")return n;let i={...r};return delete i[t],i},e)}function M(e){return N(e.catch(oh)).transform((t)=>t.filter((n)=>n!==oh))}function Y(e,t){return Ds((n)=>n===null?t():n,e)}function W(){return Be().refine(Number.isInteger,{error:"Invalid input: expected int, received number"})}var oh;var ah=S(()=>{uo();oh=Symbol("skippedItem")});var ye,D,Us,Zs,Bs,ch,uh,Ox,Tn,Nx,Px,Lx,Dx,Mx,jx,Ux,Zx,et,Bx,Fx,Bt,Vx,lh,dh,ph,fh,qx,Hx,Fs,mh,Vs,qs,Hs,Gs,Ws,An,Rn,Gx,Wx,hh,Ks,Js,Ys,Xs,Qs,gh,Kx,ea,Jx,Yx,ta,wh,na,ra,oa,_h,ia,bh,rR,yh,Xx,Qx,ek,tk,nk,rk,ok,ik,sk,ak,ck,uk,lk,dk,pk,fk,mk,hk,gk,wk,sa,_k,bk,yk,zh,xh,zk,aa,ca,xk,kk,Sk,vk,$k,Ek,kh,Sh,Ik,lo,Ck,po,vh,Tk,ua,$h,Ak,Rk,Ok,Nk,Pk,Ft,Lk,Dk,Mk,jk,Uk,Zk,Bk,Fk,Vk,qk,Hk,Gk,Wk,Kk,Jk,Yk,fo,Xk,Eh,Qk,Vt,oR,Cn,js,eS,tS,nS,Ih,rS,mo,oS,iS,sS,aS,cS,uS,lS,dS,pS,fS,mS,hS,gS,wS,_S,bS,yS,Ch,zS,xS,kS,SS,vS,la,da,pa,fa,ma,$S,ES,IS,CS,TS,ho,ha,ga,Th,iR,AS,RS,OS,NS,PS,LS,DS,MS,jS,US,ZS,BS,FS,go,wa,_a,ba,ya,za,xa,Ah,VS,qS,HS,GS,wo,WS,_o,ka,Sa,KS,va,$a,Ea,Ia,Ca,Ta,Aa,Ra,Oa,Na,Pa,La,sR,JS,YS,XS,QS,ev,tv,nv,rv,ov,iv,sv,av,Da,cv,uv,lv,aR,Ma,ja,cR,uR,dv,pv,lR,fv,mv,dR,hv,pR;var Ua=S(()=>{ah();uo();ye=C([W(),c()]).nullable(),D=c(),Us=p({sessionId:D,path:c(),content:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Zs=p({sessionId:D,path:c(),line:ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),limit:ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Bs=c(),ch=C([_("read"),_("edit"),_("delete"),_("move"),_("search"),_("execute"),_("think"),_("fetch"),_("switch_mode"),_("other")]),uh=C([_("pending"),_("in_progress"),_("completed"),_("failed")]),Ox=C([_("assistant"),_("user")]),Tn=p({audience:u(M(Ox).nullish(),()=>{return}),lastModified:u(c().nullish(),()=>{return}),priority:u(Be().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Nx=p({annotations:u(Tn.nullish(),()=>{return}),text:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Px=p({annotations:u(Tn.nullish(),()=>{return}),data:c(),mimeType:c(),uri:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Lx=p({annotations:u(Tn.nullish(),()=>{return}),data:c(),mimeType:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Dx=p({annotations:u(Tn.nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),mimeType:u(c().nullish(),()=>{return}),name:c(),size:u(W().nullish(),()=>{return}),title:u(c().nullish(),()=>{return}),uri:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Mx=p({mimeType:u(c().nullish(),()=>{return}),text:c(),uri:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),jx=p({blob:c(),mimeType:u(c().nullish(),()=>{return}),uri:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ux=C([Mx,jx]),Zx=p({annotations:u(Tn.nullish(),()=>{return}),resource:Ux,_meta:u(h(c(),m()).nullish(),()=>{return})}),et=C([Nx.and(p({type:_("text")})),Px.and(p({type:_("image")})),Lx.and(p({type:_("audio")})),Dx.and(p({type:_("resource_link")})),Zx.and(p({type:_("resource")}))]),Bx=p({content:et,_meta:u(h(c(),m()).nullish(),()=>{return})}),Fx=p({path:c(),oldText:u(c().nullish(),()=>{return}),newText:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Bt=c(),Vx=p({terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),lh=C([Bx.and(p({type:_("content")})),Fx.and(p({type:_("diff")})),Vx.and(p({type:_("terminal")}))]),dh=p({path:c(),line:u(ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),ph=p({toolCallId:Bs,kind:u(ch.nullish(),()=>{return}),status:u(uh.nullish(),()=>{return}),title:u(c().nullish(),()=>{return}),name:u(c().nullish(),()=>{return}),content:u(M(lh).nullish(),()=>{return}),locations:u(M(dh).nullish(),()=>{return}),rawInput:u(m().optional(),()=>{return}),rawOutput:u(m().optional(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),fh=c(),qx=C([_("allow_once"),_("allow_always"),_("reject_once"),_("reject_always")]),Hx=p({optionId:fh,name:c(),kind:qx,_meta:u(h(c(),m()).nullish(),()=>{return})}),Fs=p({sessionId:D,toolCall:ph,options:N(Hx),_meta:u(h(c(),m()).nullish(),()=>{return})}),mh=p({name:c(),value:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Vs=p({sessionId:D,command:c(),args:Y(N(c()),()=>[]).optional(),env:Y(N(mh),()=>[]).optional(),cwd:c().nullish(),outputByteLimit:W().gte(0).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),qs=p({sessionId:D,terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),Hs=p({sessionId:D,terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),Gs=p({sessionId:D,terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),Ws=p({sessionId:D,terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),An=p({sessionId:D,toolCallId:u(Bs.nullish(),()=>{return})}),Rn=p({requestId:ye}),Gx=_("object"),Wx=C([_("email"),_("uri"),_("date"),_("date-time")]),hh=p({const:c(),title:c(),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ks=p({title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),minLength:ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:c().nullish(),format:Wx.nullish(),default:u(c().nullish(),()=>{return}),enum:N(c()).nullish(),oneOf:N(hh).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Js=p({title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),minimum:Be().nullish(),maximum:Be().nullish(),default:u(Be().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ys=p({title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),minimum:W().nullish(),maximum:W().nullish(),default:u(W().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Xs=p({title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),default:u(H().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Qs=p({enum:N(c()),_meta:u(h(c(),m()).nullish(),()=>{return})}),gh=p({anyOf:N(hh),_meta:u(h(c(),m()).nullish(),()=>{return})}),Kx=zt(C([Qs.and(p({type:_("string")})),yt(p({type:c()}),"type",["string"]),gh]),"type",["string"]),ea=p({title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),minItems:W().gte(0).nullish(),maxItems:W().gte(0).nullish(),items:Kx,default:u(M(c()).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Jx=zt(C([Ks.and(p({type:_("string")})),Js.and(p({type:_("number")})),Ys.and(p({type:_("integer")})),Xs.and(p({type:_("boolean")})),ea.and(p({type:_("array")})),yt(p({type:c()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Yx=p({type:u(Gx.optional().default("object"),()=>"object"),title:u(c().nullish(),()=>{return}),properties:h(c(),Jx).optional().default({}),required:N(c()).nullish(),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),ta=Te(C([An,Rn]),p({requestedSchema:Yx})),wh=c(),na=Te(C([An,Rn]),p({elicitationId:wh,url:Bm()})),ra=zt(Te(C([ta.and(p({mode:_("form")})),na.and(p({mode:_("url")})),yt(Te(C([An,Rn]),p({mode:c()})),"mode",["form","url"])]),p({message:c(),_meta:u(h(c(),m()).nullish(),()=>{return})})),"mode",["form","url"]),oa=c(),_h=c(),ia=p({serverId:oa,requestId:_h,method:c(),params:h(c(),m()).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),bh=m(),rR=p({id:ye,method:c(),params:C([Us,Zs,Fs,Vs,qs,Hs,Gs,Ws,ra,ia,bh]).nullish()}),yh=ce().gte(0).lte(65535),Xx=p({image:u(H().optional().default(!1),()=>!1),audio:u(H().optional().default(!1),()=>!1),embeddedContext:u(H().optional().default(!1),()=>!1),_meta:u(h(c(),m()).nullish(),()=>{return})}),Qx=p({http:u(H().optional().default(!1),()=>!1),sse:u(H().optional().default(!1),()=>!1),acp:u(H().optional().default(!1),()=>!1),_meta:u(h(c(),m()).nullish(),()=>{return})}),ek=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),tk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),nk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),rk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ok=p({override:u(rk.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),ik=p({mode:u(ok.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),sk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ak=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ck=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),uk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),lk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),dk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),pk=p({list:u(ek.nullish(),()=>{return}),delete:u(tk.nullish(),()=>{return}),additionalDirectories:u(nk.nullish(),()=>{return}),systemPrompt:u(ik.nullish(),()=>{return}),fork:u(sk.nullish(),()=>{return}),archive:u(ak.nullish(),()=>{return}),status:u(ck.nullish(),()=>{return}),title:u(uk.nullish(),()=>{return}),resume:u(lk.nullish(),()=>{return}),close:u(dk.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),fk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),mk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),hk=p({status:u(fk.nullish(),()=>{return}),logout:u(mk.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),gk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),wk=p({loadSession:u(H().optional().default(!1),()=>!1),promptCapabilities:u(Xx.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:u(Qx.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:u(pk.optional().default({}),()=>({})),auth:u(hk.optional().default({}),()=>({})),providers:u(gk.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),sa=c(),_k=p({id:sa,name:c(),description:u(c().nullish(),()=>{return}),args:Y(N(c()),()=>[]).optional(),env:Y(h(c(),c()),()=>({})).optional(),_meta:u(h(c(),m()).nullish(),()=>{return})}),bk=p({id:sa,name:c(),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),yk=C([_k.and(p({type:_("terminal")})),bk]),zh=p({name:c(),title:u(c().nullish(),()=>{return}),version:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),xh=p({protocolVersion:yh,agentCapabilities:u(wk.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:u(M(yk).optional().default([]),()=>[]),agentInfo:u(zh.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),zk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),aa=c(),ca=C([_("anthropic"),_("openai"),_("azure"),_("vertex"),_("bedrock"),c()]),xk=p({apiType:ca,baseUrl:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),kk=p({providerId:aa,supported:Ae(M(ca),()=>[]),required:H(),current:xk.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Sk=p({providers:N(kk),_meta:u(h(c(),m()).nullish(),()=>{return})}),vk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),$k=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Ek=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),kh=C([_("authenticated"),_("unauthenticated"),_("not_required"),_("unknown"),c()]),Sh=p({label:c(),active:u(H().nullish(),()=>{return}),name:u(c().nullish(),()=>{return}),email:u(c().nullish(),()=>{return}),organization:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ik=p({state:kh,accounts:u(M(Sh).optional(),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),lo=c(),Ck=p({id:lo,name:c(),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),po=p({currentModeId:lo,availableModes:Ae(M(Ck),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),vh=c(),Tk=C([_("mode"),_("model"),_("model_config"),_("thought_level"),c()]),ua=c(),$h=p({value:ua,name:c(),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ak=c(),Rk=p({group:Ak,name:c(),options:Ae(M($h),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ok=C([N($h),N(Rk)]),Nk=p({currentValue:ua,options:Ok}),Pk=p({currentValue:H()}),Ft=Te(C([Nk.and(p({type:_("select")})),Pk.and(p({type:_("boolean")}))]),p({id:vh,name:c(),description:u(c().nullish(),()=>{return}),category:u(Tk.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})})),Lk=p({sessionId:D,modes:u(po.nullish(),()=>{return}),configOptions:u(M(Ft).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Dk=p({modes:u(po.nullish(),()=>{return}),configOptions:u(M(Ft).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Mk=p({sessionId:D,cwd:c(),additionalDirectories:u(M(c()).optional(),()=>[]),title:u(c().nullish(),()=>{return}),updatedAt:u(c().nullish(),()=>{return}),archived:u(H().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),jk=p({sessions:Ae(M(Mk),()=>[]),nextCursor:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Uk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Zk=p({sessionId:D,modes:u(po.nullish(),()=>{return}),configOptions:u(M(Ft).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Bk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Fk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Vk=C([_("open"),_("saved"),c()]),qk=p({status:Vk,_meta:u(h(c(),m()).nullish(),()=>{return})}),Hk=p({title:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Gk=p({modes:u(po.nullish(),()=>{return}),configOptions:u(M(Ft).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Wk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Kk=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Jk=p({configOptions:Ae(M(Ft),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),Yk=C([_("end_turn"),_("max_tokens"),_("max_turn_requests"),_("refusal"),_("cancelled")]),fo=p({totalTokens:W().gte(0),inputTokens:W().gte(0),outputTokens:W().gte(0),thoughtTokens:u(W().gte(0).nullish(),()=>{return}),cachedReadTokens:u(W().gte(0).nullish(),()=>{return}),cachedWriteTokens:u(W().gte(0).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Xk=p({stopReason:Yk,usage:u(fo.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Eh=m(),Qk=C([_(-32700),_(-32600),_(-32601),_(-32602),_(-32603),_(-32800),_(-32000),_(-32002),ce().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),Vt=p({code:Qk,message:c(),data:u(m().optional(),()=>{return})}),oR=C([p({id:ye,result:C([xh,zk,Sk,vk,$k,Ek,Ik,Lk,Dk,jk,Uk,Zk,Bk,Fk,qk,Hk,Gk,Wk,Kk,Jk,Xk,Eh])}),p({id:ye,error:Vt})]),Cn=c(),js=p({content:et,messageId:u(Cn.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),eS=p({toolCallId:Bs,title:c(),name:u(c().nullish(),()=>{return}),kind:u(ch.optional(),()=>{return}),status:u(uh.optional(),()=>{return}),content:u(M(lh).optional(),()=>[]),locations:u(M(dh).optional(),()=>[]),rawInput:u(m().optional(),()=>{return}),rawOutput:u(m().optional(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),tS=C([_("high"),_("medium"),_("low")]),nS=C([_("pending"),_("in_progress"),_("completed")]),Ih=p({content:c(),priority:tS,status:nS,_meta:u(h(c(),m()).nullish(),()=>{return})}),rS=p({entries:Ae(M(Ih),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),mo=c(),oS=p({planId:mo,entries:Ae(M(Ih),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),iS=p({planId:mo,uri:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),sS=p({planId:mo,content:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),aS=C([oS.and(p({type:_("items")})),iS.and(p({type:_("file")})),sS.and(p({type:_("markdown")}))]),cS=p({plan:aS,_meta:u(h(c(),m()).nullish(),()=>{return})}),uS=p({planId:mo,_meta:u(h(c(),m()).nullish(),()=>{return})}),lS=p({hint:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),dS=lS,pS=p({name:c(),description:c(),input:u(dS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),fS=p({availableCommands:Ae(M(pS),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),mS=p({currentModeId:lo,_meta:u(h(c(),m()).nullish(),()=>{return})}),hS=p({configOptions:Ae(M(Ft),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),gS=p({title:u(c().nullish(),()=>{return}),updatedAt:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),wS=p({amount:Be(),currency:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),_S=p({used:W().gte(0),size:W().gte(0),cost:u(wS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),bS=C([_("info"),_("warning"),_("error"),c()]),yS=p({severity:bS,title:c().min(1),description:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ch=c(),zS=C([_("in_progress"),_("completed"),_("failed"),_("cancelled"),c()]),xS=p({compactionId:Ch,status:zS,summary:u(M(et).nullish(),()=>{return}),error:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),kS=p({compactionId:Ch,content:et,_meta:u(h(c(),m()).nullish(),()=>{return})}),SS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),vS=p({cancel:u(SS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),la=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),da=p({error:u(Vt.nullish(),()=>{return})}),pa=sh(zt(Te(C([p({stopReason:_("end_turn")}),p({stopReason:_("max_tokens")}),p({stopReason:_("max_turn_requests")}),p({stopReason:_("refusal")}),p({stopReason:_("cancelled")}),da.and(p({stopReason:_("error")})),yt(p({stopReason:c()}),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),p({stopReason:co().optional()})]),p({usage:u(fo.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return}),stopReason:u(c().nullish(),()=>{return})})),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),"stopReason"),fa=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ma=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),$S=zt(C([la.and(p({state:_("running")})),pa.and(p({state:_("idle")})),fa.and(p({state:_("requires_action")})),ma.and(p({state:_("unknown")})),yt(p({state:c()}),"state",["idle","requires_action","running","unknown"])]),"state",["idle","requires_action","running","unknown"]),ES=p({sessionId:D,title:u(c().nullish(),()=>{return}),description:u(c().nullish(),()=>{return}),capabilities:u(vS.nullish(),()=>{return}),state:u($S.nullish(),()=>{return}),cwd:c().nullish(),additionalDirectories:N(c()).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),IS=p({messageId:Cn,senderSessionId:u(D.nullish(),()=>{return}),recipientSessionId:u(D.nullish(),()=>{return}),senderMessageId:u(Cn.nullish(),()=>{return}),recipientMessageId:u(Cn.nullish(),()=>{return}),content:u(M(et).nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),CS=p({messageId:Cn,content:et,_meta:u(h(c(),m()).nullish(),()=>{return})}),TS=C([js.and(p({sessionUpdate:_("user_message_chunk")})),js.and(p({sessionUpdate:_("agent_message_chunk")})),js.and(p({sessionUpdate:_("agent_thought_chunk")})),eS.and(p({sessionUpdate:_("tool_call")})),ph.and(p({sessionUpdate:_("tool_call_update")})),rS.and(p({sessionUpdate:_("plan")})),cS.and(p({sessionUpdate:_("plan_update")})),uS.and(p({sessionUpdate:_("plan_removed")})),fS.and(p({sessionUpdate:_("available_commands_update")})),mS.and(p({sessionUpdate:_("current_mode_update")})),hS.and(p({sessionUpdate:_("config_option_update")})),gS.and(p({sessionUpdate:_("session_info_update")})),_S.and(p({sessionUpdate:_("usage_update")})),yS.and(p({sessionUpdate:_("notice")})),xS.and(p({sessionUpdate:_("compaction_update")})),kS.and(p({sessionUpdate:_("compaction_summary_chunk")})),ES.and(p({sessionUpdate:_("subagent_update")})),IS.and(p({sessionUpdate:_("session_message")})),CS.and(p({sessionUpdate:_("session_message_chunk")}))]),ho=p({sessionId:D,update:TS,_meta:u(h(c(),m()).nullish(),()=>{return})}),ha=p({elicitationId:wh,_meta:u(h(c(),m()).nullish(),()=>{return})}),ga=p({state:kh,accounts:u(M(Sh).optional(),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),Th=m(),iR=p({method:c(),params:C([ho,ha,ga,Th]).nullish()}),AS=p({readTextFile:u(H().optional().default(!1),()=>!1),writeTextFile:u(H().optional().default(!1),()=>!1),_meta:u(h(c(),m()).nullish(),()=>{return})}),RS=h(c(),m()),OS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),NS=p({boolean:u(OS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),PS=h(c(),m()),LS=p({compaction:u(RS.nullish(),()=>{return}),configOptions:u(NS.nullish(),()=>{return}),notices:u(PS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),DS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),MS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),jS=p({terminal:u(H().optional().default(!1),()=>!1),_meta:u(h(c(),m()).nullish(),()=>{return})}),US=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ZS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),BS=p({form:u(US.nullish(),()=>{return}),url:u(ZS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),FS=p({fs:u(AS.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:u(H().optional().default(!1),()=>!1),session:u(LS.nullish(),()=>{return}),subagents:u(DS.nullish(),()=>{return}),plan:u(MS.nullish(),()=>{return}),auth:u(jS.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:u(BS.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),go=p({protocolVersion:yh,clientCapabilities:u(FS.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:u(zh.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),wa=p({methodId:sa,_meta:u(h(c(),m()).nullish(),()=>{return})}),_a=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),ba=p({providerId:aa,apiType:ca,baseUrl:c(),headers:h(c(),c()).optional(),_meta:u(h(c(),m()).nullish(),()=>{return})}),ya=p({providerId:aa,_meta:u(h(c(),m()).nullish(),()=>{return})}),za=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),xa=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),Ah=p({name:c(),value:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),VS=p({name:c(),url:c(),headers:Y(N(Ah),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),qS=p({name:c(),url:c(),headers:Y(N(Ah),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),HS=p({name:c(),serverId:oa,_meta:u(h(c(),m()).nullish(),()=>{return})}),GS=p({name:c(),command:c(),args:Y(N(c()),()=>[]),env:Y(N(mh),()=>[]),_meta:u(h(c(),m()).nullish(),()=>{return})}),wo=C([VS.and(p({type:_("http")})),qS.and(p({type:_("sse")})),HS.and(p({type:_("acp")})),GS]),WS=C([_("append"),_("override"),c()]),_o=p({mode:WS,content:N(et),_meta:u(h(c(),m()).nullish(),()=>{return})}),ka=p({cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(wo),()=>[]),systemPrompt:_o.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Sa=p({mcpServers:Y(N(wo),()=>[]),cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),sessionId:D,systemPrompt:_o.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),KS=C([_("exclude"),_("include"),_("only"),c()]),va=p({cwd:c().nullish(),cursor:c().nullish(),archived:KS.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),$a=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),Ea=p({sessionId:D,cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(wo),()=>[]).optional(),systemPrompt:_o.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ia=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),Ca=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),Ta=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),Aa=p({sessionId:D,title:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Ra=p({sessionId:D,cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(wo),()=>[]).optional(),systemPrompt:_o.nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),Oa=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),Na=p({sessionId:D,modeId:lo,_meta:u(h(c(),m()).nullish(),()=>{return})}),Pa=Te(C([p({type:_("boolean"),value:H()}),p({value:ua})]),p({sessionId:D,configId:vh,_meta:u(h(c(),m()).nullish(),()=>{return})})),La=p({sessionId:D,prompt:N(et),_meta:u(h(c(),m()).nullish(),()=>{return})}),sR=p({id:ye,method:c(),params:C([go,wa,_a,ba,ya,za,xa,ka,Sa,va,$a,Ea,Ia,Ca,Ta,Aa,Ra,Oa,Na,Pa,La,bh]).nullish()}),JS=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),YS=p({content:c(),_meta:u(h(c(),m()).nullish(),()=>{return})}),XS=p({optionId:fh,_meta:u(h(c(),m()).nullish(),()=>{return})}),QS=C([p({outcome:_("cancelled")}),XS.and(p({outcome:_("selected")}))]),ev=p({outcome:QS,_meta:u(h(c(),m()).nullish(),()=>{return})}),tv=p({terminalId:Bt,_meta:u(h(c(),m()).nullish(),()=>{return})}),nv=p({exitCode:u(ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),signal:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),rv=p({output:c(),truncated:H(),exitStatus:u(nv.nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),ov=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),iv=p({exitCode:u(ce().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),signal:u(c().nullish(),()=>{return}),_meta:u(h(c(),m()).nullish(),()=>{return})}),sv=p({_meta:u(h(c(),m()).nullish(),()=>{return})}),av=C([c(),W(),Be(),H(),N(c())]),Da=p({content:h(c(),av).nullish()}),cv=zt(Te(C([Da.and(p({action:_("accept")})),p({action:_("decline")}),p({action:_("cancel")}),yt(p({action:c()}),"action",["accept","cancel","decline"])]),p({_meta:u(h(c(),m()).nullish(),()=>{return})})),"action",["accept","cancel","decline"]),uv=qm({code:ce().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"}),message:c(),data:m().optional()}),lv=C([p({result:m(),_meta:u(h(c(),m()).nullish(),()=>{return})}),p({error:uv,_meta:u(h(c(),m()).nullish(),()=>{return})})]),aR=C([p({id:ye,result:C([JS,YS,ev,tv,rv,ov,iv,sv,cv,lv,Eh])}),p({id:ye,error:Vt})]),Ma=p({sessionId:D,_meta:u(h(c(),m()).nullish(),()=>{return})}),ja=p({serverId:oa,requestId:_h,method:c(),params:h(c(),m()).nullish(),_meta:u(h(c(),m()).nullish(),()=>{return})}),cR=p({method:c(),params:C([Ma,ja,Th]).nullish()}),uR=p({requestId:ye,_meta:u(h(c(),m()).nullish(),()=>{return})}),dv=go,pv=p({method:c(),params:m().optional(),_meta:u(h(c(),m()).nullish(),()=>{return})}),lR=p({id:ye,method:c(),params:C([dv,pv]).nullish()}),fv=xh,mv=m(),dR=C([p({id:ye,result:C([fv,mv])}),p({id:ye,error:Vt})]),hv=p({method:c(),params:m().optional(),_meta:u(h(c(),m()).nullish(),()=>{return})}),pR=p({method:c(),params:hv.nullish()})});var Oh=S(()=>{ge();Ii();mn()});var wR,_R,bR,yR,zR,xR,kR,SR,vR,$R,ER,IR,CR,TR,AR,RR,OR,NR,PR,LR,DR,MR,jR;var Nh=S(()=>{uo();Ua();wR=ta.and(p({mode:_("form")})).and(p({message:c()})),_R=na.and(p({mode:_("url")})).and(p({message:c()})),bR=C([An,Rn]).and(p({message:c()})),yR=Ks.and(p({type:_("string")})),zR=Js.and(p({type:_("number")})),xR=Ys.and(p({type:_("integer")})),kR=Xs.and(p({type:_("boolean")})),SR=ea.and(p({type:_("array")})),vR=Qs.and(p({type:_("string")})),$R=la.and(p({state:_("running")})),ER=pa.and(p({usage:fo.nullish()})).and(p({state:_("idle")})),IR=fa.and(p({state:_("requires_action")})),CR=ma.and(p({state:_("unknown")})),TR=p({stopReason:_("end_turn")}),AR=p({stopReason:_("max_tokens")}),RR=p({stopReason:_("max_turn_requests")}),OR=p({stopReason:_("refusal")}),NR=p({stopReason:_("cancelled")}),PR=da.and(p({error:Vt.nullish()})).and(p({stopReason:_("error")})),LR=p({stopReason:co().optional()}),DR=Da.and(p({action:_("accept")})),MR=p({action:_("decline")}),jR=p({action:_("cancel")})});function bo(e,t){if(!e)return t;if(typeof e==="function")return e(t);return e.parse(t)}function Ph(e,t,n,r,o,i){let s=async(a,l,d,f)=>{try{let g=await r(n(a,d,l.signal,l.id,f)),w=o?o(g):g;i?.beforeResponse(a,w,d),await l.respond(w)}catch(g){throw i?.onError(d,g),g}};if(t.method==="*")e.withFallbackHandler({handleMessage:async(a,l)=>{if(a.kind!=="request")return K.no(a);return await s(a.params,a.responder,l,a.method),K.yes()}});else e.onReceiveRequest(t.method,(a)=>bo(t.params,a),(a,l,d)=>s(a,l,d,t.method))}function Lh(e,t,n,r){if(t.method==="*")e.withFallbackHandler({handleMessage:async(o,i)=>{if(o.kind!=="notification")return K.no(o);return await r(n(o.params,i,i.signal,o.method)),K.yes()}});else e.onReceiveNotification(t.method,(o)=>bo(t.params,o),(o,i)=>r(n(o,i,i.signal,t.method)))}var Dh=S(()=>{ge()});var Mh;var Za=S(()=>{Mh=Symbol("connectionContextOf")});function gv(e){return{handleMessage(t,n){if(t.kind!=="request"||!e()||jh.has(n))return K.no(t);if(t.method!==k.initialize)return t.responder.respondWithError(T.invalidRequest(void 0,`ACP connection must be initialized before '${t.method}'`)).then(()=>K.yes());let{responder:r}=t;return K.no({...t,responder:new wr(r.id,(o)=>{if("result"in o)jh.add(n);return r.respondWithResult(o)},r.signal)})},describe:()=>"agent-initialization"}}function ne(e){return e??{}}function wv(e){return typeof e==="object"&&e!==null&&"readable"in e&&"writable"in e}function _v(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}class qa{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}}function bv(e,t=[]){return new Vh(e,t)}function yv(e,t=[]){return new qh(e,t)}class Hh{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();if(t)t.resolve(e);else this.values.push({kind:"value",value:e})}reject(e){if(this.failed)return;if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}clearErrors(){this.values=this.values.filter((e)=>e.kind==="value")}fail(e){if(this.failed)return;this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}next(){if(this.values.length>0){let e=this.values.shift();if(e.kind==="error")return Promise.reject(e.error);return Promise.resolve(e.value)}if(this.failed)return Promise.reject(this.failure);return new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}}function Uh(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}class yo{cx;request;constructor(e,t){this.cx=e,this.request=Uh(t)}static create(e,t){return new yo(e,t)}toRequest(){return Uh(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Fh](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}}function L(e,t,n){return{method:e,params:(r)=>bo(t,r??{}),mapResponse:n}}function On(e,t){return{method:e,params:t}}function zo(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}function Ev(e,t,n,r,o){return{method:o,params:e,requestId:r,signal:n,client:t}}function Iv(e,t,n,r){return{method:r,params:e,signal:n,client:t}}class Wh{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==O.session_update)return K.no(e);let t=ho.parse(e.params),n={kind:"session_update",notification:t,update:t.update},r=this.activeSessions.get(t.sessionId);if(r&&r.size>0)for(let o of r)o.enqueue(n);return K.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new cn(()=>{if(n.delete(t),n.size===0)this.activeSessions.delete(e.sessionId)})}}function Cv(e){let t=Zh.get(e);if(!t)t=new Wh,Zh.set(e,t);return t}function Ga(e,t){for(let n of t){let r;try{r=n(e)}catch(o){throw e.close(o),o}Promise.resolve(r).catch((o)=>{e.close(o)})}}function Kh(e){return new Jh(e)}var jh,xt,Fh,Fa,Nn,Va,Vh,qh,Ha,zv,xv,kv,Sv,Gh,vv,$v,tO,Zh,Bh,Ba,Tv,Jh,Wa;var Yh=S(()=>{sn();Ua();Oh();Nh();sn();ge();mn();Dh();Za();ge();jh=new WeakSet;xt={agent:{initialize:k.initialize,authenticate:k.authenticate,logout:k.logout,auth:{status:k.auth_status},providers:{list:k.providers_list,set:k.providers_set,disable:k.providers_disable},session:{new:k.session_new,load:k.session_load,list:k.session_list,delete:k.session_delete,fork:k.session_fork,archive:k.session_archive,unarchive:k.session_unarchive,status:k.session_status,setTitle:k.session_set_title,resume:k.session_resume,close:k.session_close,setMode:k.session_set_mode,setConfigOption:k.session_set_config_option,prompt:k.session_prompt,cancel:k.session_cancel},mcp:{message:k.mcp_message}},client:{session:{requestPermission:O.session_request_permission,update:O.session_update},fs:{writeTextFile:O.fs_write_text_file,readTextFile:O.fs_read_text_file},terminal:{create:O.terminal_create,output:O.terminal_output,release:O.terminal_release,waitForExit:O.terminal_wait_for_exit,kill:O.terminal_kill},mcp:{message:O.mcp_message},elicitation:{create:O.elicitation_create,complete:O.elicitation_complete},auth:{statusUpdate:O.auth_status_update}},protocol:{cancelRequest:_i.cancel_request}},Fh=Symbol("startActiveSession");Fa=class Fa{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}[Mh](){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}};Nn=class Nn extends Fa{constructor(e,t){super(e,t)}static create(e,t){return new Nn(e,t)}async createTerminal(e,t){let n=await this.request(O.terminal_create,e,t);return Wa.create(n.terminalId,e.sessionId,this.connectionContext)}request(e,t,n){let r=$v[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}};Va=class Va extends Fa{constructor(e,t){super(e,t)}static create(e,t){return new Va(e,t)}[Fh](e,t){return this.sendRequest(k.session_new,e,(n)=>this.attachSession(n),t)}buildSession(e){if(typeof e==="string")return yo.create(this,{cwd:e,mcpServers:[]});return yo.create(this,e)}attachSession(e){let t=new Hh,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error("ACP connection closed"))};if(n.aborted)r();else n.addEventListener("abort",r);let o=Cv(this.connectionContext).attach(e,t),i=new cn(()=>{n.removeEventListener("abort",r)});return Ha.create(this,e,t,[o,i])}request(e,t,n){let r=Gh[e];return Iu(e,this.sendRequest(e,t,r?.mapResponse,n),()=>r?.mapResponse?r.mapResponse({}):{})}notify(e,t){return this.sendNotification(e,t)}};Vh=class Vh extends qa{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e);this.connectHandlers=t,this.client=Nn.create(e.getContext())}startConnectHandlers(){if(this.didStartConnectHandlers)return;this.didStartConnectHandlers=!0,Ga(this,this.connectHandlers)}};qh=class qh extends qa{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e);this.connectHandlers=t,this.agent=Va.create(e.getContext())}startConnectHandlers(){if(this.didStartConnectHandlers)return;this.didStartConnectHandlers=!0,Ga(this,this.connectHandlers)}};Ha=class Ha{cx;sessionResponse;updates;registrations;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r}static create(e,t,n,r){return new Ha(e,t,n,r)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let n=this.cx.request(k.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return n.then((r)=>{this.updates.enqueue({kind:"stop",response:r,stopReason:r.stopReason})},(r)=>{this.updates.reject(r)}),n}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:n}=t;if(n.sessionUpdate==="agent_message_chunk"&&n.content.type==="text")e+=n.content.text}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){if(typeof e==="string")return[{type:"text",text:e}];if(Array.isArray(e))return e;return[e]}};zv={initialize:L(k.initialize,go),newSession:L(k.session_new,ka),loadSession:L(k.session_load,Sa,ne),unstable_forkSession:L(k.session_fork,Ea),listSessions:L(k.session_list,va),deleteSession:L(k.session_delete,$a,ne),unstable_archiveSession:L(k.session_archive,Ia,ne),unstable_unarchiveSession:L(k.session_unarchive,Ca,ne),unstable_sessionStatus:L(k.session_status,Ta),unstable_setSessionTitle:L(k.session_set_title,Aa),resumeSession:L(k.session_resume,Ra),closeSession:L(k.session_close,Oa,ne),setSessionMode:L(k.session_set_mode,Na,ne),setSessionConfigOption:L(k.session_set_config_option,Pa),authenticate:L(k.authenticate,wa,ne),unstable_listProviders:L(k.providers_list,_a),unstable_setProvider:L(k.providers_set,ba,ne),unstable_disableProvider:L(k.providers_disable,ya,ne),logout:L(k.logout,za,ne),unstable_authStatus:L(k.auth_status,xa),prompt:L(k.session_prompt,La)},xv={cancel:On(k.session_cancel,Ma),unstable_messageMcp:On(k.mcp_message,ja)},kv={requestPermission:L(O.session_request_permission,Fs),writeTextFile:L(O.fs_write_text_file,Us,ne),readTextFile:L(O.fs_read_text_file,Zs),createTerminal:L(O.terminal_create,Vs),terminalOutput:L(O.terminal_output,qs),releaseTerminal:L(O.terminal_release,Hs,ne),waitForTerminalExit:L(O.terminal_wait_for_exit,Gs),killTerminal:L(O.terminal_kill,Ws,ne),createElicitation:L(O.elicitation_create,ra),unstable_messageMcp:L(O.mcp_message,ia)},Sv={sessionUpdate:On(O.session_update,ho),completeElicitation:On(O.elicitation_complete,ha),unstable_authStatusUpdate:On(O.auth_status_update,ga)},Gh=zo(zv),vv=zo(xv),$v=zo(kv),tO=zo(Sv);Zh=new WeakMap;Bh=Symbol("appBuilder"),Ba=Symbol("runAgentConnectHandlers"),Tv=Symbol("runClientConnectHandlers");Jh=class Jh{builder=_r.builder();connectHandlers=[];fallbackKinds=new Set;hasInitializeHandler=!1;constructor(e={}){if(this.builder.withHandler(gv(()=>this.hasInitializeHandler)),e.name)this.builder.name(e.name)}[Bh](){return this.builder}[Ba](e){Ga(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(e==="*"){if(n)throw Error("Wildcard handlers receive raw params; omit the parser.");if(this.fallbackKinds.has("request"))throw Error("A request fallback is already registered.");return this.fallbackKinds.add("request"),this.request({method:e},t)}if(n)return this.request({method:e,params:t},n);let r=Gh[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);if(e===k.initialize)this.hasInitializeHandler=!0;return this.request(r,t)}onNotification(e,t,n){if(e==="*"){if(n)throw Error("Wildcard handlers receive raw params; omit the parser.");if(this.fallbackKinds.has("notification"))throw Error("A notification fallback is already registered.");return this.fallbackKinds.add("notification"),this.notification({method:e},t)}if(n)return this.notification({method:e,params:t},n);let r=vv[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return Ph(this.builder,e,(n,r,o,i,s)=>Ev(n,Nn.create(r,i),o,i,s),t,e.mapResponse),this}notification(e,t){return Lh(this.builder,e,(n,r,o,i)=>Iv(n,Nn.create(r),o,i),t),this}connectConnection(e,t={}){if(wv(e)){let a=this.openStreamConnection(e);if(!t.deferConnectHandlers)this[Ba](a.connection);return a}let[n,r]=_v(),o=e[Bh]().connect(r),i=yv(o),s=this.openStreamConnection(n);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{e[Tv](i),this[Ba](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:bv(t,this.connectHandlers)}}};Wa=class Wa{id;sessionId;connection;constructor(e,t,n){this.id=e,this.sessionId=t,this.connection=n}static create(e,t,n){return new Wa(e,t,n)}currentOutput(){return this.connection.sendRequest(O.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(O.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(O.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},ne)}release(){return this.connection.sendRequest(O.terminal_release,{sessionId:this.sessionId,terminalId:this.id},ne)}async[Symbol.asyncDispose](){await this.release()}}});var Xh=S(()=>{Za();ge()});var Qh=S(()=>{Xh()});var eg=S(()=>{sn();Yh();Qh()});import{randomUUID as Rv}from"node:crypto";function tg(e,t,n){let r=new Map,o=(i)=>{let s=r.get(i);r.delete(i),s?.turn?.abort(),s?.release()};return Kh({name:`nimblebrain-subscription-${e.id}`}).onRequest(xt.agent.initialize,()=>({protocolVersion:bi,agentCapabilities:{loadSession:!1,promptCapabilities:{embeddedContext:!0},mcpCapabilities:{acp:!0,http:!1},...e.takesSystemPrompt?{sessionCapabilities:{systemPrompt:{mode:{override:{}}}}}:{}},agentInfo:{name:`nimblebrain-subscription-${e.id}`,version:Pv},...n?{_meta:{[Nv]:n}}:{}})).onRequest(xt.agent.session.new,(i)=>{let s=i.params.mcpServers.find((g)=>("type"in g)&&g.type==="acp");if(!s||!("serverId"in s))throw T.invalidParams(void 0,"the session names no acp MCP server");let{url:a,release:l}=t.bind(i.client,s.serverId),d=Rv(),f=i.params.systemPrompt?.content.map((g)=>g.type==="text"?g.text:"").join(`
66
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of e.seen.entries()){let a=s[1];if(t===s[0]){i(s);continue}if(e.external){let d=e.external.registry.get(s[0])?.id;if(t!==s[0]&&d){i(s);continue}}if(e.metadataRegistry.get(s[0])?.id){i(s);continue}if(a.cycle){i(s);continue}if(a.count>1){if(e.reused==="ref")i(s)}}if(e.external)e.sharedDefsExtractedFor=e.external}function sm(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let r of t){if(!r||typeof r!=="object")return;sm(r);let o=Object.keys(r);if(o.length!==1||o[0]!=="type")return;let i=r.type;for(let s of Array.isArray(i)?i:[i]){if(typeof s!=="string")return;if(!n.includes(s))n.push(s)}}delete e.anyOf,e.type=n.length===1?n[0]:n}function im(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function Ms(e){let t=[];for(let i of e){if(typeof i!=="object"||i.type!=="object")return null;for(let s in i)if(!am.has(s))return null;t.push(i)}let n={},r=new Set;for(let i of t){for(let s in i.properties){if(Object.prototype.hasOwnProperty.call(n,s))continue;let a=[];for(let d of t){let p=d.properties?.[s]??im(d);if(p===null||p===void 0)continue;if(!a.some((g)=>JSON.stringify(g)===JSON.stringify(p)))a.push(p)}let u=a.length===1?a[0]:Ms(a)??{allOf:a};_e(n,s,u)}for(let s of i.required??[])r.add(s)}let o={type:"object",properties:n};if(r.size)o.required=[...r];if(t.every((i)=>i.additionalProperties===!1))o.additionalProperties=!1;else{let i=[];for(let s of t){let a=im(s);if(a&&!i.some((u)=>JSON.stringify(u)===JSON.stringify(a)))i.push(a)}if(i.length===1)o.additionalProperties=i[0];else if(i.length>1)o.additionalProperties={allOf:i}}return o}function Yz(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of am)if(o in e)return;let n=t.filter((o)=>om.some((i)=>Array.isArray(o[i]))),r=null;if(!n.length)r=Ms(t);else{let o=n[0],i=om.find((u)=>Array.isArray(o[u]));if(Object.keys(o).length!==1)return;let s=t.filter((u)=>u!==o),a=o[i].map((u)=>Ms([...s,u]));if(a.some((u)=>!u))return;r={[i]:a}}if(!r)return;delete e.allOf,Nn(e,r)}function Us(e,t){let n=e.seen.get(t);if(!n)throw Error("Unprocessed schema. This is a bug in Zod.");let r=(a)=>{let u=e.seen.get(a);if(u.ref===null)return;let d=u.def??u.schema,p={...d},g=u.ref;if(u.ref=null,g){r(g);let b=e.seen.get(g),z=b.schema;if(z.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))d.allOf=d.allOf??[],d.allOf.push(z);else Nn(d,z);if(Nn(d,p),a._zod.parent===g)for(let k in d){if(k==="$ref"||k==="allOf")continue;if(!(k in p))delete d[k]}if(z.$ref&&b.def)for(let k in d){if(k==="$ref"||k==="allOf")continue;if(k in b.def&&JSON.stringify(d[k])===JSON.stringify(b.def[k]))delete d[k]}}let w=a._zod.parent;if(w&&w!==g){r(w);let b=e.seen.get(w);if(b?.schema.$ref){if(d.$ref=b.schema.$ref,b.def)for(let z in d){if(z==="$ref"||z==="allOf")continue;if(z in b.def&&JSON.stringify(d[z])===JSON.stringify(b.def[z]))delete d[z]}}}e.override({zodSchema:a,jsonSchema:d,path:u.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())r(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())sm(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let u of e.seen.values())for(let d of[u.schema,u.def]){let p=d?.allOf;if(!Array.isArray(p))continue;let g=a.get(p);if(g)g.push(d);else a.set(p,[d])}for(let u of e.intersections)for(let d of a.get(u)??[])Yz(d)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Nn(o,n.defId?n.schema:n.def??n.schema);let i=e.metadataRegistry.get(t)?.id;if(i!==void 0&&o.id===i)delete o.id;let s=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let u=a[1];if(u.def&&u.defId){if(u.def.id===u.defId)delete u.def.id;_e(s,u.defId,u.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(s).length>0)if(e.target==="draft-2020-12")o.$defs=s;else o.definitions=s;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Pn(t,"input",e.processors),output:Pn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function ee(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return ee(r.element,n);if(r.type==="set")return ee(r.valueType,n);if(r.type==="lazy")return ee(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault"||r.type==="catch")return ee(r.innerType,n);if(r.type==="intersection")return ee(r.left,n)||ee(r.right,n);if(r.type==="record"||r.type==="map")return ee(r.keyType,n)||ee(r.valueType,n);if(r.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return ee(r.in,n)||ee(r.out,n)}if(r.type==="object"){for(let o in r.shape)if(ee(r.shape[o],n))return!0;return!1}if(r.type==="union"){for(let o of r.options)if(ee(o,n))return!0;return!1}if(r.type==="tuple"){for(let o of r.items)if(ee(o,n))return!0;if(r.rest&&ee(r.rest,n))return!0;return!1}return!1}var am,om,cm=(e,t={})=>(n)=>{let r=Ds({...n,processors:t});return H(e,r),js(r,e),Us(r,e)},Pn=(e,t,n={})=>(r)=>{let{libraryOptions:o,target:i}=r??{},s=Ds({...o??{},target:i,io:t,processors:n});return H(e,s),js(s,e),Us(s,e)};var co=v(()=>{Ss();re();am=new Set(["type","properties","required","additionalProperties"]),om=["oneOf","anyOf"]});function pe(e){let t={},n=e._zod.def,r=e._zod.traits.has("$ZodCheck")?[e,...n.checks??[]]:n.checks??[];for(let i of r)Xz[i._zod.def.check]?.(t,i._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)Ht(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)Ht(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)Gt(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)Gt(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)pm(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)hm(t,o.mime);for(let i of o.patterns??[])mm(t,i);return t}function uo(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return uo(t.out);if(t.type==="catch")return uo(t.innerType);return e._zod.optin}function Zs(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let z=e.get(t)?.def;if(!z)return t;let I=Zs(e,z,n);return I===z?t:I}for(let z of["anyOf","oneOf"]){let I=t[z];if(!Array.isArray(I))continue;let k=I.map((A)=>Zs(e,A,n));if(k.some((A,ne)=>A!==I[ne]))t={...t,[z]:k}}let r=Array.isArray(t.type)?t.type:[t.type],o=!r.includes("string")&&r.some((z)=>z==="number"||z==="integer"),i=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!i?.some((z)=>typeof z==="number"))return t;let{minimum:s,maximum:a,exclusiveMinimum:u,exclusiveMaximum:d,multipleOf:p,format:g,id:w,...b}=t;if(b.enum)b.enum=b.enum.map((z)=>typeof z==="number"?String(z):z);else if(typeof b.const==="number")b.const=String(b.const);if(!o)return b;if(b.type="string",!i)b.pattern=(r.includes("number")?En:ss).source;return b}function tx(e){let t=new Map;for(let r of e.seen.values())if(r.def&&!t.has(r.schema))t.set(r.schema,r);let n=new Map;for(let r of Bs.get(e)??[]){let o=e.seen.get(r),i=(o?.def??o?.schema)?.propertyNames;if(!i||i===!0||n.has(i))continue;let s=Zs(t,i,new Set);if(s!==i)n.set(i,s)}if(!n.size)return;for(let r of e.seen.values())for(let o of[r.schema,r.def]){let i=o&&n.get(o.propertyNames);if(i)o.propertyNames=i}}function Pm(e,t,n,r,o){let i=!1,s=JSON.stringify(e,(a,u)=>{if(typeof u!=="bigint")return u;return i=!0,null});if(!i)return JSON.parse(s);return Be(t,n,r,o,"BigInt defaults cannot be represented in JSON Schema"),Fs}var Ht=(e,t,n)=>{if(e[t]===void 0||n>e[t])e[t]=n},Gt=(e,t,n)=>{if(e[t]===void 0||n<e[t])e[t]=n},um=(e,t)=>{Ht(e,"minimum",t),Gt(e,"maximum",t)},pm=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},mm=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},hm=(e,t)=>{e.mime=e.mime?e.mime.filter((n)=>t.includes(n)):[...t]},gm=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},lm=(e,t)=>Ht(e,"minimum",t.minimum),dm=(e,t)=>Gt(e,"maximum",t.maximum),fm=(e)=>(t,n)=>{gm(t,n.format);let[r,o]=e[n.format];Ht(t,"minimum",r),Gt(t,"maximum",o)},Xz,Qz,ex,wm=(e)=>ex.get(e)??e,_m=(e,t,n,r)=>{let o=n;o.type="string";let{minimum:i,maximum:s,format:a,patterns:u,contentEncoding:d,laxFormat:p}=pe(e);if(typeof i==="number")o.minLength=i;if(typeof s==="number")o.maxLength=s;if(a){if(o.format=Qz[a]??a,o.format==="")delete o.format;if(a==="time"||p)delete o.format}if(d)o.contentEncoding=d;if(u&&u.size>0){let g=[...u].map(wm);if(g.length===1)o.pattern=g[0].source;else if(g.length>1)o.allOf=[...g.map((w)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:w.source}))]}},bm=(e,t,n,r)=>{let o=n,{minimum:i,maximum:s,multipleOf:a,exclusiveMaximum:u,exclusiveMinimum:d,isInt:p}=pe(e);o.type=p?"integer":"number";let g=typeof d==="number"&&d>=(i??Number.NEGATIVE_INFINITY),w=typeof u==="number"&&u<=(s??Number.POSITIVE_INFINITY),b=t.target==="draft-04"||t.target==="openapi-3.0";if(g)if(b)o.minimum=d,o.exclusiveMinimum=!0;else o.exclusiveMinimum=d;else if(typeof i==="number")o.minimum=i;if(w)if(b)o.maximum=u,o.exclusiveMaximum=!0;else o.exclusiveMaximum=u;else if(typeof s==="number")o.maximum=s;if(a){let z=new Set;for(let A of a)if(Number.isFinite(A)&&A!==0)z.add(Math.abs(A));else Be(e,t,o,r,`A multipleOf divisor of ${A} cannot be represented in JSON Schema`);let[I,...k]=z;if(I!==void 0)o.multipleOf=I;if(k.length)o.allOf=[...o.allOf??[],...k.map((A)=>({multipleOf:A}))]}},ym=(e,t,n,r)=>{n.type="boolean"},zm=(e,t,n,r)=>{if(t.target==="openapi-3.0")n.type="string",n.nullable=!0,n.enum=[null];else n.type="null"},xm=(e,t,n,r)=>{n.not={}},km=(e,t,n,r)=>{},Sm=(e,t,n,r)=>{let o=e._zod.def,i=Sn(o.entries);if(i.length===0){n.not={};return}if(i.every((s)=>typeof s==="number"))n.type="number";if(i.every((s)=>typeof s==="string"))n.type="string";n.enum=i},vm=(e,t,n,r)=>{let o=e._zod.def;if(o.values.length===0){n.not={};return}let i=[];for(let s of o.values)if(s===void 0){if(Be(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof s==="bigint"){if(Be(e,t,n,r,"BigInt literals cannot be represented in JSON Schema"))return;i.push(Number(s))}else i.push(s);if(i.length===0);else if(i.length===1){let s=i[0];if(n.type=s===null?"null":typeof s,t.target==="draft-04"||t.target==="openapi-3.0")n.enum=[s];else n.const=s}else{if(i.every((s)=>typeof s==="number"))n.type="number";if(i.every((s)=>typeof s==="string"))n.type="string";if(i.every((s)=>typeof s==="boolean"))n.type="boolean";if(i.every((s)=>s===null))n.type="null";n.enum=i}},$m=(e,t,n,r)=>{Be(e,t,n,r,"Custom types cannot be represented in JSON Schema")},Em=(e,t,n,r)=>{Be(e,t,n,r,"Transforms cannot be represented in JSON Schema")},Im=(e,t,n,r)=>{let o=n,i=e._zod.def,{minimum:s,maximum:a}=pe(e);if(typeof s==="number")o.minItems=s;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=H(i.element,t,{...r,path:[...r.path,"items"]})},Cm=(e,t,n,r)=>{let o=n,i=e._zod.def,s=i.shape;if(Object.getOwnPropertySymbols(s).length&&Be(e,t,o,r,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let d in s)_e(o.properties,d,H(s[d],t,{...r,path:[...r.path,"properties",d]}));let u=[];for(let d of Object.keys(s)){let p=i.shape[d];if(t.io==="input"?uo(p)===void 0:p._zod.optout===void 0)u.push(d)}if(u.length>0)o.required=u;if(i.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!i.catchall){if(t.io==="output")o.additionalProperties=!1}else if(i.catchall)o.additionalProperties=H(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})},Tm=(e,t,n,r)=>{let o=e._zod.def,i=o.inclusive===!1,s=o.options.map((a,u)=>H(a,t,{...r,path:[...r.path,i?"oneOf":"anyOf",u]}));if(i)n.oneOf=s;else n.anyOf=s},Am=(e,t,n,r)=>{let o=e._zod.def,i=H(o.left,t,{...r,path:[...r.path,"allOf",0]}),s=H(o.right,t,{...r,path:[...r.path,"allOf",1]}),a=(d)=>("allOf"in d)&&Object.keys(d).length===1,u=[...a(i)?i.allOf:[i],...a(s)?s.allOf:[s]];n.allOf=u,t.intersections.push(u)},Bs,Rm=(e,t,n,r)=>{let o=n,i=e._zod.def;o.type="object";let s=i.keyType,a=pe(s).patterns;if(i.mode==="loose"&&a&&a.size>0){let p=H(i.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});o.patternProperties={};for(let g of a)_e(o.patternProperties,wm(g).source,p)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=H(i.keyType,t,{...r,path:[...r.path,"propertyNames"]});let p=Bs.get(t);if(!p)p=[],Bs.set(t,p),t.deferred.push(()=>tx(t));p.push(e)}o.additionalProperties=H(i.valueType,t,{...r,path:[...r.path,"additionalProperties"]})}let u=s._zod.values,d=t.io==="input"&&uo(i.valueType)!==void 0;if(u&&!i.partial&&!d){let p=[...u].filter((g)=>typeof g==="string"||typeof g==="number");if(p.length>0)o.required=p.map(String)}},Om=(e,t,n,r)=>{let o=e._zod.def,i=H(o.innerType,t,r),s=t.seen.get(e);if(t.target==="openapi-3.0")s.ref=o.innerType,n.nullable=!0;else n.anyOf=[i,{type:"null"}]},Nm=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType},Fs,Lm=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let s=Pm(o.defaultValue,e,t,n,r);if(s!==Fs)n.default=s},Mm=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);if(i.ref=o.innerType,t.io!=="input")return;let s=Pm(o.defaultValue,e,t,n,r);if(s!==Fs)n._prefault=s},Dm=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType;let s;try{s=o.catchValue(void 0)}catch{Be(e,t,n,r,"Dynamic catch values are not supported in JSON Schema");return}n.default=s},jm=(e,t,n,r)=>{let o=e._zod.def,i=o.in._zod.traits.has("$ZodTransform"),s=t.io==="input"?i?o.out:o.in:o.out;H(s,t,r);let a=t.seen.get(e);a.ref=s},Um=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType,n.readOnly=!0},Vs=(e,t,n,r)=>{let o=e._zod.def;H(o.innerType,t,r);let i=t.seen.get(e);i.ref=o.innerType};var Zm=v(()=>{In();_s();co();re();Xz={greater_than:(e,t)=>Ht(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>Gt(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>pm(e,t.value),number_format:fm(Nr),bigint_format:fm(Ki),min_length:lm,max_length:dm,length_equals:(e,t)=>um(e,t.length),min_size:lm,max_size:dm,size_equals:(e,t)=>um(e,t.size),string_format:(e,t)=>{if(gm(e,t.format),t.pattern)mm(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>hm(e,t.mime)};Qz={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},ex=new Map([[ms,Ed],[Xr,Id]]);Bs=new WeakMap;Fs=Symbol()});var Bm=()=>{};var Ce=v(()=>{re();In();ks();Bm();kt();dd();td();_s();pp();Gr();ds();Ss();bp();nm();co()});var qs=v(()=>{Ce()});function fo(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let r=n(this);return Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,t,{value:r,configurable:!0,writable:!0})}})}var Fm,ux=(e,t)=>{ed.init(e,t),e.name="ZodError";let n=Object.getPrototypeOf(e);if(Fm.has(n))return;Fm.add(n),fo(n,"format",(r)=>(o)=>ts(r,o)),fo(n,"flatten",(r)=>(o)=>es(r,o)),fo(n,"addIssue",(r)=>(o)=>{r.issues.push(o),r.message=JSON.stringify(r.issues,vn,2)}),fo(n,"addIssues",(r)=>(o)=>{r.issues.push(...o),r.message=JSON.stringify(r.issues,vn,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})},ce;var Hs=v(()=>{Ce();Ce();re();Fm=new WeakSet([Object.prototype,Error.prototype]);ce=y("ZodError",ux,void 0,{Parent:Error})});var Vm,qm,Hm,Gm,Wm,Km,Jm,Ym,Xm,Qm,eh,th;var Gs=v(()=>{Ce();Hs();Ce();Vm=Br(ce),qm=Fr(ce),Hm=Vr(ce),Gm=qr(ce),Wm=rd(ce),Km=od(ce),Jm=id(ce),Ym=sd(ce),Xm=ad(ce),Qm=cd(ce),eh=ud(ce),th=ld(ce)});function dx(){if(!oe.localeError)ie(xs())}function mo(){if(!oe.memoizer)ie({memoizer:zs()})}function c(e){return zp(fx,e)}function ch(e){return vs(ah,e)}function Fe(e){return Gp(uh,e)}function ue(e){return Wp(Nx,e)}function G(e){return Kp(Px,e)}function ho(e){return Jp(Lx,e)}function m(){return Yp(Mx)}function jx(e){return Xp(Dx,e)}function N(e,t){return Qp(Ux,e,t)}function f(e,t){let n={type:"object",shape:e??{},...E(t)};return new lh(n)}function dh(e,t){return new lh({type:"object",shape:e,catchall:m(),...E(t)})}function C(e,t){return new Zx({type:"union",options:e,...E(t)})}function Te(e,t){return new Bx({type:"intersection",left:e,right:t})}function h(e,t,n){if(!t||!t._zod)return new nh({type:"record",keyType:c(),valueType:e,...E(t)});return new nh({type:"record",keyType:e,valueType:t,...E(n)})}function Fx(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map((r)=>[r,r])):e;return new Ws({type:"enum",entries:n,...E(t)})}function _(e,t){return new Vx({type:"literal",values:Array.isArray(e)?e:[e],...E(t)})}function fh(e){return new qx({type:"transform",transform:e})}function rh(e){return new ph({type:"optional",innerType:e})}function Hx(e){return new mh({type:"optional",innerType:e})}function oh(e){return new Gx({type:"nullable",innerType:e})}function Kx(e,t){return new Wx({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Gi(t)}})}function Yx(e,t){return new Jx({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Gi(t)}})}function Xx(e,t){return new hh({type:"nonoptional",innerType:e,...E(t)})}function ek(e,t){return new Qx({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Kl(t)})}function ih(e,t){return new gh({type:"pipe",in:e,out:t})}function rk(e){return new nk({type:"readonly",innerType:e})}function ik(e,t={}){return em(ok,e,t)}function sk(e,t){return tm(e,t)}function Ks(e,t){return new tk({type:"pipe",in:fh(e),out:t})}var B,sh,fx,F,px,mx,hx,gx,wx,_x,po,ah,bx,yx,zx,xx,kx,Sx,vx,$x,Ex,Ix,Cx,Tx,Ax,Rx,Ox,uh,Nx,Px,Lx,Mx,Dx,Ux,lh,Zx,Bx,nh,Ws,Vx,qx,ph,mh,Gx,Wx,Jx,hh,Qx,gh,tk,nk,ok;var wh=v(()=>{Ce();Ce();Zm();co();mp();qs();Gs();B=y("ZodType",(e,t)=>(dx(),U.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ae(t,{checks:[...t.checks??[],...e.map((n)=>typeof n==="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return be(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(ik(e,t))},superRefine(e,t){return this.check(sk(e,t))},overwrite(e){return this.check(Qe(e))},optional(){return rh(this)},exactOptional(){return Hx(this)},nullable(){return oh(this)},nullish(){return rh(oh(this))},nonoptional(e){return Xx(this,e)},array(){return N(this)},or(e){return C([this,e])},and(e){return Te(this,e)},transform(e){return ih(this,fh(e))},default(e){return Kx(this,e)},prefault(e){return Yx(this,e)},catch(e){return ek(this,e)},pipe(e){return ih(this,e)},readonly(){return rk(this)},describe(e){let t=this.clone();return Xe.add(t,{description:e}),t},meta(...e){if(e.length===0)return Xe.get(this);let t=this.clone();return Xe.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return jr(this,"~standard",{...ps(this),jsonSchema:{input:Pn(this,"input"),output:Pn(this,"output")}})},set "~standard"(e){Ze(this,"~standard",e)},parse:function e(t,n){return Vm(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await qm(this,t,n,{callee:e})},safeParse(e,t){return Hm(this,e,t)},async safeParseAsync(e,t){return Gm(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Ze(this,"spa",e)},validate(e,t){return ns(this,e,t)},validateAsync(e,t){return rs(this,e,t)},encode:function e(t,n){return Wm(this,t,n,{callee:e})},decode:function e(t,n){return Km(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Jm(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Ym(this,t,n,{callee:e})},safeEncode(e,t){return Xm(this,e,t)},safeDecode(e,t){return Qm(this,e,t)},async safeEncodeAsync(e,t){return eh(this,e,t)},async safeDecodeAsync(e,t){return th(this,e,t)},toJSONSchema(e){return cm(this,{})(e)},get description(){return Xe.get(this)?.description},get _def(){return this._zod.def}}),sh=y("_ZodString",(e,t)=>{Yr.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>_m(e,n,r,o)},Wl({format:(e)=>pe(e).format??null,minLength:(e)=>pe(e).minimum??null,maxLength:(e)=>pe(e).maximum??null},{regex(...e){return this.check($s(...e))},includes(...e){return this.check(Cs(...e))},startsWith(...e){return this.check(Ts(...e))},endsWith(...e){return this.check(As(...e))},min(...e){return this.check(qt(...e))},max(...e){return this.check(so(...e))},length(...e){return this.check(ao(...e))},nonempty(...e){return this.check(qt(1,...e))},lowercase(e){return this.check(Es(e))},uppercase(e){return this.check(Is(e))},trim(){return this.check(Os())},normalize(...e){return this.check(Rs(...e))},toLowerCase(){return this.check(Ns())},toUpperCase(){return this.check(Ps())},slugify(){return this.check(Ls())}})),fx=y("ZodString",(e,t)=>{Yr.init(e,t),sh.init(e,t)},{email(e){return this.check(xp(wx,e))},url(e){return this.check(vs(ah,e))},jwt(e){return this.check(Bp(Ox,e))},emoji(e){return this.check(Ip(bx,e))},guid(e){return this.check(kp(_x,e))},uuid(e){return this.check(Sp(po,e))},uuidv4(e){return this.check(vp(po,e))},uuidv6(e){return this.check($p(po,e))},uuidv7(e){return this.check(Ep(po,e))},nanoid(e){return this.check(Cp(yx,e))},cuid(e){return this.check(Tp(zx,e))},cuid2(e){return this.check(Ap(xx,e))},ulid(e){return this.check(Rp(kx,e))},base64(e){return this.check(jp(Tx,e))},base64url(e){return this.check(Up(Ax,e))},xid(e){return this.check(Op(Sx,e))},ksuid(e){return this.check(Np(vx,e))},ipv4(e){return this.check(Pp($x,e))},ipv6(e){return this.check(Lp(Ex,e))},cidrv4(e){return this.check(Mp(Ix,e))},cidrv6(e){return this.check(Dp(Cx,e))},e164(e){return this.check(Zp(Rx,e))},datetime(e){return this.check(Fp(px,e))},date(e){return this.check(Vp(mx,e))},time(e){return this.check(qp(hx,e))},duration(e){return this.check(Hp(gx,e))}});F=y("ZodStringFormat",(e,t)=>{Z.init(e,t),sh.init(e,t)}),px=y("ZodISODateTime",(e,t)=>{vf.init(e,t),F.init(e,t)}),mx=y("ZodISODate",(e,t)=>{$f.init(e,t),F.init(e,t)}),hx=y("ZodISOTime",(e,t)=>{Ef.init(e,t),F.init(e,t)}),gx=y("ZodISODuration",(e,t)=>{If.init(e,t),F.init(e,t)}),wx=y("ZodEmail",(e,t)=>{mf.init(e,t),F.init(e,t)}),_x=y("ZodGUID",(e,t)=>{ff.init(e,t),F.init(e,t)}),po=y("ZodUUID",(e,t)=>{pf.init(e,t),F.init(e,t)}),ah=y("ZodURL",(e,t)=>{wf.init(e,t),F.init(e,t)});bx=y("ZodEmoji",(e,t)=>{_f.init(e,t),F.init(e,t)}),yx=y("ZodNanoID",(e,t)=>{bf.init(e,t),F.init(e,t)}),zx=y("ZodCUID",(e,t)=>{yf.init(e,t),F.init(e,t)}),xx=y("ZodCUID2",(e,t)=>{zf.init(e,t),F.init(e,t)}),kx=y("ZodULID",(e,t)=>{xf.init(e,t),F.init(e,t)}),Sx=y("ZodXID",(e,t)=>{kf.init(e,t),F.init(e,t)}),vx=y("ZodKSUID",(e,t)=>{Sf.init(e,t),F.init(e,t)}),$x=y("ZodIPv4",(e,t)=>{Cf.init(e,t),F.init(e,t)}),Ex=y("ZodIPv6",(e,t)=>{Af.init(e,t),F.init(e,t)}),Ix=y("ZodCIDRv4",(e,t)=>{Rf.init(e,t),F.init(e,t)}),Cx=y("ZodCIDRv6",(e,t)=>{Of.init(e,t),F.init(e,t)}),Tx=y("ZodBase64",(e,t)=>{Pf.init(e,t),F.init(e,t)}),Ax=y("ZodBase64URL",(e,t)=>{Lf.init(e,t),F.init(e,t)}),Rx=y("ZodE164",(e,t)=>{Mf.init(e,t),F.init(e,t)}),Ox=y("ZodJWT",(e,t)=>{Df.init(e,t),F.init(e,t)}),uh=y("ZodNumber",(e,t)=>{hs.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>bm(e,n,r,o),e.isFinite=!0},Wl({minValue:(e)=>{let{minimum:t,exclusiveMinimum:n}=pe(e);return Math.max(t??Number.NEGATIVE_INFINITY,n??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:n}=pe(e);return Math.min(t??Number.POSITIVE_INFINITY,n??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:n}=pe(e);return!!t||!!n?.some(Number.isSafeInteger)},format:(e)=>pe(e).format??null},{gt(e,t){return this.check(oo(e,t))},gte(e,t){return this.check(On(e,t))},min(e,t){return this.check(On(e,t))},lt(e,t){return this.check(ro(e,t))},lte(e,t){return this.check(Rn(e,t))},max(e,t){return this.check(Rn(e,t))},int(e){return this.check(ue(e))},safe(e){return this.check(ue(e))},positive(e){return this.check(oo(0,e))},nonnegative(e){return this.check(On(0,e))},negative(e){return this.check(ro(0,e))},nonpositive(e){return this.check(Rn(0,e))},multipleOf(e,t){return this.check(io(e,t))},step(e,t){return this.check(io(e,t))},finite(){return this}}));Nx=y("ZodNumberFormat",(e,t)=>{jf.init(e,t),uh.init(e,t)});Px=y("ZodBoolean",(e,t)=>{Uf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>ym(e,n,r,o)});Lx=y("ZodNull",(e,t)=>{Zf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>zm(e,n,r,o)});Mx=y("ZodUnknown",(e,t)=>{Bf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>km(e,n,r,o)});Dx=y("ZodNever",(e,t)=>{Ff.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>xm(e,n,r,o)});Ux=y("ZodArray",(e,t)=>{mo(),Vf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Im(e,n,r,o),e.element=t.element},{min(e,t){return this.check(qt(e,t))},nonempty(e){return this.check(qt(1,e))},max(e,t){return this.check(so(e,t))},length(e,t){return this.check(ao(e,t))},unwrap(){return this.element}});lh=y("ZodObject",(e,t)=>{mo(),Gf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Cm(e,n,r,o),bz(e,"shape",(n)=>n._zod.def.shape,!1)},{keyof(){return Fx(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ae(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ae(this._zod.def,{catchall:m()}))},loose(){return this.clone(ae(this._zod.def,{catchall:m()}))},strict(){return this.clone(ae(this._zod.def,{catchall:jx()}))},strip(){return this.clone(ae(this._zod.def,{catchall:void 0}))},extend(e){return dz(this,e)},safeExtend(e){return fz(this,e)},merge(e){return pz(this,e)},pick(e){return uz(this,e)},omit(e){return lz(this,e)},partial(...e){return Vl(ph,this,e[0])},exactPartial(...e){return Vl(mh,this,e[0],"exactPartial")},required(...e){return mz(hh,this,e[0])}});Zx=y("ZodUnion",(e,t)=>{Wf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Tm(e,n,r,o),e.options=t.options});Bx=y("ZodIntersection",(e,t)=>{Kf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Am(e,n,r,o)});nh=y("ZodRecord",(e,t)=>{mo(),Jf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Rm(e,n,r,o),e.keyType=t.keyType,e.valueType=t.valueType});Ws=y("ZodEnum",(e,t)=>{Yf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(r,o,i)=>Sm(e,r,o,i),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(r,o)=>{let i={};for(let s of r)if(n.has(s))i[s]=t.entries[s];else throw Error(`Key ${s} not found in enum`);return new Ws({...t,checks:[],...E(o),entries:i})},e.exclude=(r,o)=>{let i={...t.entries};for(let s of r)if(n.has(s))delete i[s];else throw Error(`Key ${s} not found in enum`);return new Ws({...t,checks:[],...E(o),entries:i})}});Vx=y("ZodLiteral",(e,t)=>{Xf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>vm(e,n,r,o),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});qx=y("ZodTransform",(e,t)=>{mo(),Qf.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Em(e,n,r,o),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new $n(e.constructor.name);n.addIssue=(i)=>{if(typeof i==="string")n.issues.push(xt(i,n.value,t));else{let s=i;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=e),n.issues.push(xt(s))}};let o=t.transform(n.value,n);if(o instanceof Promise)return o.then((i)=>(n.value=i,n));return n.value=o,n}});ph=y("ZodOptional",(e,t)=>{gs.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});mh=y("ZodExactOptional",(e,t)=>{ep.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Vs(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Gx=y("ZodNullable",(e,t)=>{tp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Om(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Wx=y("ZodDefault",(e,t)=>{np.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Lm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});Jx=y("ZodPrefault",(e,t)=>{rp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Mm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});hh=y("ZodNonOptional",(e,t)=>{op.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Nm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});Qx=y("ZodCatch",(e,t)=>{ip.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Dm(e,n,r,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});gh=y("ZodPipe",(e,t)=>{ws.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>jm(e,n,r,o),e.in=t.in,e.out=t.out});tk=y("ZodPreprocess",(e,t)=>{gh.init(e,t),sp.init(e,t)}),nk=y("ZodReadonly",(e,t)=>{ap.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>Um(e,n,r,o),e.unwrap=()=>e._zod.def.innerType});ok=y("ZodCustom",(e,t)=>{cp.init(e,t),B.init(e,t),e._zod.processJSONSchema=(n,r,o)=>$m(e,n,r,o)})});var _h;var bh=v(()=>{(function(e){})(_h||(_h={}))});var yh=()=>{};var zh=()=>{};var xh=v(()=>{Ce();Ce();ks();yh();zh();wh();qs();Hs();Gs();bh()});var kh=v(()=>{xh()});var go=v(()=>{kh()});function l(e,t){return e.catch(t)}function Ae(e,t){let n=e.catch(t);return m().transform((r,o)=>{if(r!==void 0)return n.parse(r);return o.addIssue({code:"custom",message:"Required value is missing"}),Ur})}function vh(e,t){if(e===null||typeof e!=="object"||Array.isArray(e))return;let n=e[t];return typeof n==="string"?n:void 0}function St(e,t,n){return e.superRefine((r,o)=>{let i=vh(r,t);if(i!==void 0&&n.includes(i))o.addIssue({code:"custom",path:[t],message:`${t} ${JSON.stringify(i)} is reserved by a known variant, but the value does not match that variant's schema`})})}function vt(e,t,n){return m().transform((r,o)=>{let i=e.safeParse(r);if(!i.success){for(let u of i.error.issues)o.addIssue({...u,input:r});return Ur}let s=i.data,a=vh(r,t);if(a!==void 0&&!n.includes(a)){let u=r;for(let[d,p]of Object.entries(u)){if(d==="__proto__")continue;if(!Object.hasOwn(s,d))s[d]=p}}return s})}function $h(e,t){return Ks((n)=>{if(n===null||typeof n!=="object"||Array.isArray(n))return n;let r=n,o=r[t];if(o===void 0||o===null||typeof o==="string")return n;let i={...r};return delete i[t],i},e)}function j(e){return N(e.catch(Sh)).transform((t)=>t.filter((n)=>n!==Sh))}function Y(e,t){return Ks((n)=>n===null?t():n,e)}function W(){return Fe().refine(Number.isInteger,{error:"Invalid input: expected int, received number"})}var Sh;var Eh=v(()=>{go();Sh=Symbol("skippedItem")});var ye,D,Xs,Qs,ea,Ih,Ch,uk,Mn,lk,dk,fk,pk,mk,hk,gk,wk,et,_k,bk,Wt,yk,Th,Ah,Rh,Oh,zk,xk,ta,Nh,na,ra,oa,ia,sa,Dn,jn,kk,Sk,Ph,aa,ca,ua,la,da,Lh,vk,fa,$k,Ek,pa,Mh,ma,ha,ga,Dh,wa,jh,YR,Uh,Ik,Ck,Tk,Ak,Rk,Ok,Nk,Pk,Lk,Mk,Dk,jk,Uk,Zk,Bk,Fk,Vk,qk,Hk,Gk,_a,Wk,Kk,Jk,Zh,Bh,Yk,ba,ya,Xk,Qk,eS,tS,nS,rS,Fh,Vh,oS,wo,iS,_o,qh,sS,za,Hh,aS,cS,uS,lS,dS,Kt,fS,pS,mS,hS,gS,wS,_S,bS,yS,zS,xS,kS,SS,vS,$S,ES,bo,IS,Gh,CS,Jt,XR,Ln,Ys,TS,AS,RS,Wh,OS,yo,NS,PS,LS,MS,DS,jS,US,ZS,BS,FS,VS,qS,HS,GS,WS,KS,JS,Kh,YS,XS,QS,ev,tv,xa,ka,Sa,va,$a,nv,rv,ov,iv,sv,zo,Ea,Ia,Jh,QR,av,cv,uv,lv,dv,fv,pv,mv,hv,gv,wv,_v,bv,xo,Ca,Ta,Aa,Ra,Oa,Na,Yh,yv,zv,xv,kv,ko,Sv,So,Pa,La,vv,Ma,Da,ja,Ua,Za,Ba,Fa,Va,qa,Ha,Ga,Wa,eO,$v,Ev,Iv,Cv,Tv,Av,Rv,Ov,Nv,Pv,Lv,Mv,Ka,Dv,jv,Uv,tO,Ja,Ya,nO,rO,Zv,Bv,oO,Fv,Vv,iO,qv,sO;var Xa=v(()=>{Eh();go();ye=C([W(),c()]).nullable(),D=c(),Xs=f({sessionId:D,path:c(),content:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Qs=f({sessionId:D,path:c(),line:ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),limit:ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),ea=c(),Ih=C([_("read"),_("edit"),_("delete"),_("move"),_("search"),_("execute"),_("think"),_("fetch"),_("switch_mode"),_("other")]),Ch=C([_("pending"),_("in_progress"),_("completed"),_("failed")]),uk=C([_("assistant"),_("user")]),Mn=f({audience:l(j(uk).nullish(),()=>{return}),lastModified:l(c().nullish(),()=>{return}),priority:l(Fe().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),lk=f({annotations:l(Mn.nullish(),()=>{return}),text:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),dk=f({annotations:l(Mn.nullish(),()=>{return}),data:c(),mimeType:c(),uri:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),fk=f({annotations:l(Mn.nullish(),()=>{return}),data:c(),mimeType:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),pk=f({annotations:l(Mn.nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),mimeType:l(c().nullish(),()=>{return}),name:c(),size:l(W().nullish(),()=>{return}),title:l(c().nullish(),()=>{return}),uri:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),mk=f({mimeType:l(c().nullish(),()=>{return}),text:c(),uri:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),hk=f({blob:c(),mimeType:l(c().nullish(),()=>{return}),uri:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),gk=C([mk,hk]),wk=f({annotations:l(Mn.nullish(),()=>{return}),resource:gk,_meta:l(h(c(),m()).nullish(),()=>{return})}),et=C([lk.and(f({type:_("text")})),dk.and(f({type:_("image")})),fk.and(f({type:_("audio")})),pk.and(f({type:_("resource_link")})),wk.and(f({type:_("resource")}))]),_k=f({content:et,_meta:l(h(c(),m()).nullish(),()=>{return})}),bk=f({path:c(),oldText:l(c().nullish(),()=>{return}),newText:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Wt=c(),yk=f({terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),Th=C([_k.and(f({type:_("content")})),bk.and(f({type:_("diff")})),yk.and(f({type:_("terminal")}))]),Ah=f({path:c(),line:l(ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Rh=f({toolCallId:ea,kind:l(Ih.nullish(),()=>{return}),status:l(Ch.nullish(),()=>{return}),title:l(c().nullish(),()=>{return}),name:l(c().nullish(),()=>{return}),content:l(j(Th).nullish(),()=>{return}),locations:l(j(Ah).nullish(),()=>{return}),rawInput:l(m().optional(),()=>{return}),rawOutput:l(m().optional(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Oh=c(),zk=C([_("allow_once"),_("allow_always"),_("reject_once"),_("reject_always")]),xk=f({optionId:Oh,name:c(),kind:zk,_meta:l(h(c(),m()).nullish(),()=>{return})}),ta=f({sessionId:D,toolCall:Rh,options:N(xk),_meta:l(h(c(),m()).nullish(),()=>{return})}),Nh=f({name:c(),value:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),na=f({sessionId:D,command:c(),args:Y(N(c()),()=>[]).optional(),env:Y(N(Nh),()=>[]).optional(),cwd:c().nullish(),outputByteLimit:W().gte(0).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),ra=f({sessionId:D,terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),oa=f({sessionId:D,terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),ia=f({sessionId:D,terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),sa=f({sessionId:D,terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),Dn=f({sessionId:D,toolCallId:l(ea.nullish(),()=>{return})}),jn=f({requestId:ye}),kk=_("object"),Sk=C([_("email"),_("uri"),_("date"),_("date-time")]),Ph=f({const:c(),title:c(),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),aa=f({title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),minLength:ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:c().nullish(),format:Sk.nullish(),default:l(c().nullish(),()=>{return}),enum:N(c()).nullish(),oneOf:N(Ph).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),ca=f({title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),minimum:Fe().nullish(),maximum:Fe().nullish(),default:l(Fe().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),ua=f({title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),minimum:W().nullish(),maximum:W().nullish(),default:l(W().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),la=f({title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),default:l(G().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),da=f({enum:N(c()),_meta:l(h(c(),m()).nullish(),()=>{return})}),Lh=f({anyOf:N(Ph),_meta:l(h(c(),m()).nullish(),()=>{return})}),vk=vt(C([da.and(f({type:_("string")})),St(f({type:c()}),"type",["string"]),Lh]),"type",["string"]),fa=f({title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),minItems:W().gte(0).nullish(),maxItems:W().gte(0).nullish(),items:vk,default:l(j(c()).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),$k=vt(C([aa.and(f({type:_("string")})),ca.and(f({type:_("number")})),ua.and(f({type:_("integer")})),la.and(f({type:_("boolean")})),fa.and(f({type:_("array")})),St(f({type:c()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),Ek=f({type:l(kk.optional().default("object"),()=>"object"),title:l(c().nullish(),()=>{return}),properties:h(c(),$k).optional().default({}),required:N(c()).nullish(),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),pa=Te(C([Dn,jn]),f({requestedSchema:Ek})),Mh=c(),ma=Te(C([Dn,jn]),f({elicitationId:Mh,url:ch()})),ha=vt(Te(C([pa.and(f({mode:_("form")})),ma.and(f({mode:_("url")})),St(Te(C([Dn,jn]),f({mode:c()})),"mode",["form","url"])]),f({message:c(),_meta:l(h(c(),m()).nullish(),()=>{return})})),"mode",["form","url"]),ga=c(),Dh=c(),wa=f({serverId:ga,requestId:Dh,method:c(),params:h(c(),m()).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),jh=m(),YR=f({id:ye,method:c(),params:C([Xs,Qs,ta,na,ra,oa,ia,sa,ha,wa,jh]).nullish()}),Uh=ue().gte(0).lte(65535),Ik=f({image:l(G().optional().default(!1),()=>!1),audio:l(G().optional().default(!1),()=>!1),embeddedContext:l(G().optional().default(!1),()=>!1),_meta:l(h(c(),m()).nullish(),()=>{return})}),Ck=f({http:l(G().optional().default(!1),()=>!1),sse:l(G().optional().default(!1),()=>!1),acp:l(G().optional().default(!1),()=>!1),_meta:l(h(c(),m()).nullish(),()=>{return})}),Tk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Ak=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Rk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Ok=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Nk=f({override:l(Ok.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Pk=f({mode:l(Nk.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Lk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Mk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Dk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),jk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Uk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Zk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Bk=f({list:l(Tk.nullish(),()=>{return}),delete:l(Ak.nullish(),()=>{return}),additionalDirectories:l(Rk.nullish(),()=>{return}),systemPrompt:l(Pk.nullish(),()=>{return}),fork:l(Lk.nullish(),()=>{return}),archive:l(Mk.nullish(),()=>{return}),status:l(Dk.nullish(),()=>{return}),title:l(jk.nullish(),()=>{return}),resume:l(Uk.nullish(),()=>{return}),close:l(Zk.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Fk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Vk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),qk=f({status:l(Fk.nullish(),()=>{return}),logout:l(Vk.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Hk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Gk=f({loadSession:l(G().optional().default(!1),()=>!1),promptCapabilities:l(Ik.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:l(Ck.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:l(Bk.optional().default({}),()=>({})),auth:l(qk.optional().default({}),()=>({})),providers:l(Hk.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),_a=c(),Wk=f({id:_a,name:c(),description:l(c().nullish(),()=>{return}),args:Y(N(c()),()=>[]).optional(),env:Y(h(c(),c()),()=>({})).optional(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Kk=f({id:_a,name:c(),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Jk=C([Wk.and(f({type:_("terminal")})),Kk]),Zh=f({name:c(),title:l(c().nullish(),()=>{return}),version:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Bh=f({protocolVersion:Uh,agentCapabilities:l(Gk.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:l(j(Jk).optional().default([]),()=>[]),agentInfo:l(Zh.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Yk=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),ba=c(),ya=C([_("anthropic"),_("openai"),_("azure"),_("vertex"),_("bedrock"),c()]),Xk=f({apiType:ya,baseUrl:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Qk=f({providerId:ba,supported:Ae(j(ya),()=>[]),required:G(),current:Xk.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),eS=f({providers:N(Qk),_meta:l(h(c(),m()).nullish(),()=>{return})}),tS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),nS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),rS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Fh=C([_("authenticated"),_("unauthenticated"),_("not_required"),_("unknown"),c()]),Vh=f({label:c(),active:l(G().nullish(),()=>{return}),name:l(c().nullish(),()=>{return}),email:l(c().nullish(),()=>{return}),organization:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),oS=f({state:Fh,accounts:l(j(Vh).optional(),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),wo=c(),iS=f({id:wo,name:c(),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),_o=f({currentModeId:wo,availableModes:Ae(j(iS),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),qh=c(),sS=C([_("mode"),_("model"),_("model_config"),_("thought_level"),c()]),za=c(),Hh=f({value:za,name:c(),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),aS=c(),cS=f({group:aS,name:c(),options:Ae(j(Hh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),uS=C([N(Hh),N(cS)]),lS=f({currentValue:za,options:uS}),dS=f({currentValue:G()}),Kt=Te(C([lS.and(f({type:_("select")})),dS.and(f({type:_("boolean")}))]),f({id:qh,name:c(),description:l(c().nullish(),()=>{return}),category:l(sS.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})})),fS=f({sessionId:D,modes:l(_o.nullish(),()=>{return}),configOptions:l(j(Kt).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),pS=f({modes:l(_o.nullish(),()=>{return}),configOptions:l(j(Kt).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),mS=f({sessionId:D,cwd:c(),additionalDirectories:l(j(c()).optional(),()=>[]),title:l(c().nullish(),()=>{return}),updatedAt:l(c().nullish(),()=>{return}),archived:l(G().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),hS=f({sessions:Ae(j(mS),()=>[]),nextCursor:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),gS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),wS=f({sessionId:D,modes:l(_o.nullish(),()=>{return}),configOptions:l(j(Kt).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),_S=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),bS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),yS=C([_("open"),_("saved"),c()]),zS=f({status:yS,_meta:l(h(c(),m()).nullish(),()=>{return})}),xS=f({title:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),kS=f({modes:l(_o.nullish(),()=>{return}),configOptions:l(j(Kt).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),SS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),vS=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),$S=f({configOptions:Ae(j(Kt),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),ES=C([_("end_turn"),_("max_tokens"),_("max_turn_requests"),_("refusal"),_("cancelled")]),bo=f({totalTokens:W().gte(0),inputTokens:W().gte(0),outputTokens:W().gte(0),thoughtTokens:l(W().gte(0).nullish(),()=>{return}),cachedReadTokens:l(W().gte(0).nullish(),()=>{return}),cachedWriteTokens:l(W().gte(0).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),IS=f({stopReason:ES,usage:l(bo.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Gh=m(),CS=C([_(-32700),_(-32600),_(-32601),_(-32602),_(-32603),_(-32800),_(-32000),_(-32002),ue().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),Jt=f({code:CS,message:c(),data:l(m().optional(),()=>{return})}),XR=C([f({id:ye,result:C([Bh,Yk,eS,tS,nS,rS,oS,fS,pS,hS,gS,wS,_S,bS,zS,xS,kS,SS,vS,$S,IS,Gh])}),f({id:ye,error:Jt})]),Ln=c(),Ys=f({content:et,messageId:l(Ln.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),TS=f({toolCallId:ea,title:c(),name:l(c().nullish(),()=>{return}),kind:l(Ih.optional(),()=>{return}),status:l(Ch.optional(),()=>{return}),content:l(j(Th).optional(),()=>[]),locations:l(j(Ah).optional(),()=>[]),rawInput:l(m().optional(),()=>{return}),rawOutput:l(m().optional(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),AS=C([_("high"),_("medium"),_("low")]),RS=C([_("pending"),_("in_progress"),_("completed")]),Wh=f({content:c(),priority:AS,status:RS,_meta:l(h(c(),m()).nullish(),()=>{return})}),OS=f({entries:Ae(j(Wh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),yo=c(),NS=f({planId:yo,entries:Ae(j(Wh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),PS=f({planId:yo,uri:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),LS=f({planId:yo,content:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),MS=C([NS.and(f({type:_("items")})),PS.and(f({type:_("file")})),LS.and(f({type:_("markdown")}))]),DS=f({plan:MS,_meta:l(h(c(),m()).nullish(),()=>{return})}),jS=f({planId:yo,_meta:l(h(c(),m()).nullish(),()=>{return})}),US=f({hint:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),ZS=US,BS=f({name:c(),description:c(),input:l(ZS.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),FS=f({availableCommands:Ae(j(BS),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),VS=f({currentModeId:wo,_meta:l(h(c(),m()).nullish(),()=>{return})}),qS=f({configOptions:Ae(j(Kt),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),HS=f({title:l(c().nullish(),()=>{return}),updatedAt:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),GS=f({amount:Fe(),currency:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),WS=f({used:W().gte(0),size:W().gte(0),cost:l(GS.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),KS=C([_("info"),_("warning"),_("error"),c()]),JS=f({severity:KS,title:c().min(1),description:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Kh=c(),YS=C([_("in_progress"),_("completed"),_("failed"),_("cancelled"),c()]),XS=f({compactionId:Kh,status:YS,summary:l(j(et).nullish(),()=>{return}),error:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),QS=f({compactionId:Kh,content:et,_meta:l(h(c(),m()).nullish(),()=>{return})}),ev=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),tv=f({cancel:l(ev.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),xa=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),ka=f({error:l(Jt.nullish(),()=>{return})}),Sa=$h(vt(Te(C([f({stopReason:_("end_turn")}),f({stopReason:_("max_tokens")}),f({stopReason:_("max_turn_requests")}),f({stopReason:_("refusal")}),f({stopReason:_("cancelled")}),ka.and(f({stopReason:_("error")})),St(f({stopReason:c()}),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),f({stopReason:ho().optional()})]),f({usage:l(bo.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return}),stopReason:l(c().nullish(),()=>{return})})),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),"stopReason"),va=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),$a=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),nv=vt(C([xa.and(f({state:_("running")})),Sa.and(f({state:_("idle")})),va.and(f({state:_("requires_action")})),$a.and(f({state:_("unknown")})),St(f({state:c()}),"state",["idle","requires_action","running","unknown"])]),"state",["idle","requires_action","running","unknown"]),rv=f({sessionId:D,title:l(c().nullish(),()=>{return}),description:l(c().nullish(),()=>{return}),capabilities:l(tv.nullish(),()=>{return}),state:l(nv.nullish(),()=>{return}),cwd:c().nullish(),additionalDirectories:N(c()).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),ov=f({messageId:Ln,senderSessionId:l(D.nullish(),()=>{return}),recipientSessionId:l(D.nullish(),()=>{return}),senderMessageId:l(Ln.nullish(),()=>{return}),recipientMessageId:l(Ln.nullish(),()=>{return}),content:l(j(et).nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),iv=f({messageId:Ln,content:et,_meta:l(h(c(),m()).nullish(),()=>{return})}),sv=C([Ys.and(f({sessionUpdate:_("user_message_chunk")})),Ys.and(f({sessionUpdate:_("agent_message_chunk")})),Ys.and(f({sessionUpdate:_("agent_thought_chunk")})),TS.and(f({sessionUpdate:_("tool_call")})),Rh.and(f({sessionUpdate:_("tool_call_update")})),OS.and(f({sessionUpdate:_("plan")})),DS.and(f({sessionUpdate:_("plan_update")})),jS.and(f({sessionUpdate:_("plan_removed")})),FS.and(f({sessionUpdate:_("available_commands_update")})),VS.and(f({sessionUpdate:_("current_mode_update")})),qS.and(f({sessionUpdate:_("config_option_update")})),HS.and(f({sessionUpdate:_("session_info_update")})),WS.and(f({sessionUpdate:_("usage_update")})),JS.and(f({sessionUpdate:_("notice")})),XS.and(f({sessionUpdate:_("compaction_update")})),QS.and(f({sessionUpdate:_("compaction_summary_chunk")})),rv.and(f({sessionUpdate:_("subagent_update")})),ov.and(f({sessionUpdate:_("session_message")})),iv.and(f({sessionUpdate:_("session_message_chunk")}))]),zo=f({sessionId:D,update:sv,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ea=f({elicitationId:Mh,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ia=f({state:Fh,accounts:l(j(Vh).optional(),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),Jh=m(),QR=f({method:c(),params:C([zo,Ea,Ia,Jh]).nullish()}),av=f({readTextFile:l(G().optional().default(!1),()=>!1),writeTextFile:l(G().optional().default(!1),()=>!1),_meta:l(h(c(),m()).nullish(),()=>{return})}),cv=h(c(),m()),uv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),lv=f({boolean:l(uv.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),dv=h(c(),m()),fv=f({compaction:l(cv.nullish(),()=>{return}),configOptions:l(lv.nullish(),()=>{return}),notices:l(dv.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),pv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),mv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),hv=f({terminal:l(G().optional().default(!1),()=>!1),_meta:l(h(c(),m()).nullish(),()=>{return})}),gv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),wv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),_v=f({form:l(gv.nullish(),()=>{return}),url:l(wv.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),bv=f({fs:l(av.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:l(G().optional().default(!1),()=>!1),session:l(fv.nullish(),()=>{return}),subagents:l(pv.nullish(),()=>{return}),plan:l(mv.nullish(),()=>{return}),auth:l(hv.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:l(_v.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),xo=f({protocolVersion:Uh,clientCapabilities:l(bv.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:l(Zh.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Ca=f({methodId:_a,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ta=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Aa=f({providerId:ba,apiType:ya,baseUrl:c(),headers:h(c(),c()).optional(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Ra=f({providerId:ba,_meta:l(h(c(),m()).nullish(),()=>{return})}),Oa=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Na=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Yh=f({name:c(),value:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),yv=f({name:c(),url:c(),headers:Y(N(Yh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),zv=f({name:c(),url:c(),headers:Y(N(Yh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),xv=f({name:c(),serverId:ga,_meta:l(h(c(),m()).nullish(),()=>{return})}),kv=f({name:c(),command:c(),args:Y(N(c()),()=>[]),env:Y(N(Nh),()=>[]),_meta:l(h(c(),m()).nullish(),()=>{return})}),ko=C([yv.and(f({type:_("http")})),zv.and(f({type:_("sse")})),xv.and(f({type:_("acp")})),kv]),Sv=C([_("append"),_("override"),c()]),So=f({mode:Sv,content:N(et),_meta:l(h(c(),m()).nullish(),()=>{return})}),Pa=f({cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(ko),()=>[]),systemPrompt:So.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),La=f({mcpServers:Y(N(ko),()=>[]),cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),sessionId:D,systemPrompt:So.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),vv=C([_("exclude"),_("include"),_("only"),c()]),Ma=f({cwd:c().nullish(),cursor:c().nullish(),archived:vv.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Da=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),ja=f({sessionId:D,cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(ko),()=>[]).optional(),systemPrompt:So.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Ua=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),Za=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ba=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),Fa=f({sessionId:D,title:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Va=f({sessionId:D,cwd:c(),additionalDirectories:Y(N(c()),()=>[]).optional(),mcpServers:Y(N(ko),()=>[]).optional(),systemPrompt:So.nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),qa=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ha=f({sessionId:D,modeId:wo,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ga=Te(C([f({type:_("boolean"),value:G()}),f({value:za})]),f({sessionId:D,configId:qh,_meta:l(h(c(),m()).nullish(),()=>{return})})),Wa=f({sessionId:D,prompt:N(et),_meta:l(h(c(),m()).nullish(),()=>{return})}),eO=f({id:ye,method:c(),params:C([xo,Ca,Ta,Aa,Ra,Oa,Na,Pa,La,Ma,Da,ja,Ua,Za,Ba,Fa,Va,qa,Ha,Ga,Wa,jh]).nullish()}),$v=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Ev=f({content:c(),_meta:l(h(c(),m()).nullish(),()=>{return})}),Iv=f({optionId:Oh,_meta:l(h(c(),m()).nullish(),()=>{return})}),Cv=C([f({outcome:_("cancelled")}),Iv.and(f({outcome:_("selected")}))]),Tv=f({outcome:Cv,_meta:l(h(c(),m()).nullish(),()=>{return})}),Av=f({terminalId:Wt,_meta:l(h(c(),m()).nullish(),()=>{return})}),Rv=f({exitCode:l(ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),signal:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Ov=f({output:c(),truncated:G(),exitStatus:l(Rv.nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Nv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Pv=f({exitCode:l(ue().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{return}),signal:l(c().nullish(),()=>{return}),_meta:l(h(c(),m()).nullish(),()=>{return})}),Lv=f({_meta:l(h(c(),m()).nullish(),()=>{return})}),Mv=C([c(),W(),Fe(),G(),N(c())]),Ka=f({content:h(c(),Mv).nullish()}),Dv=vt(Te(C([Ka.and(f({action:_("accept")})),f({action:_("decline")}),f({action:_("cancel")}),St(f({action:c()}),"action",["accept","cancel","decline"])]),f({_meta:l(h(c(),m()).nullish(),()=>{return})})),"action",["accept","cancel","decline"]),jv=dh({code:ue().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"}),message:c(),data:m().optional()}),Uv=C([f({result:m(),_meta:l(h(c(),m()).nullish(),()=>{return})}),f({error:jv,_meta:l(h(c(),m()).nullish(),()=>{return})})]),tO=C([f({id:ye,result:C([$v,Ev,Tv,Av,Ov,Nv,Pv,Lv,Dv,Uv,Gh])}),f({id:ye,error:Jt})]),Ja=f({sessionId:D,_meta:l(h(c(),m()).nullish(),()=>{return})}),Ya=f({serverId:ga,requestId:Dh,method:c(),params:h(c(),m()).nullish(),_meta:l(h(c(),m()).nullish(),()=>{return})}),nO=f({method:c(),params:C([Ja,Ya,Jh]).nullish()}),rO=f({requestId:ye,_meta:l(h(c(),m()).nullish(),()=>{return})}),Zv=xo,Bv=f({method:c(),params:m().optional(),_meta:l(h(c(),m()).nullish(),()=>{return})}),oO=f({id:ye,method:c(),params:C([Zv,Bv]).nullish()}),Fv=Bh,Vv=m(),iO=C([f({id:ye,result:C([Fv,Vv])}),f({id:ye,error:Jt})]),qv=f({method:c(),params:m().optional(),_meta:l(h(c(),m()).nullish(),()=>{return})}),sO=f({method:c(),params:qv.nullish()})});var Qh=v(()=>{ge();Ui();zn()});var dO,fO,pO,mO,hO,gO,wO,_O,bO,yO,zO,xO,kO,SO,vO,$O,EO,IO,CO,TO,AO,RO,OO;var eg=v(()=>{go();Xa();dO=pa.and(f({mode:_("form")})).and(f({message:c()})),fO=ma.and(f({mode:_("url")})).and(f({message:c()})),pO=C([Dn,jn]).and(f({message:c()})),mO=aa.and(f({type:_("string")})),hO=ca.and(f({type:_("number")})),gO=ua.and(f({type:_("integer")})),wO=la.and(f({type:_("boolean")})),_O=fa.and(f({type:_("array")})),bO=da.and(f({type:_("string")})),yO=xa.and(f({state:_("running")})),zO=Sa.and(f({usage:bo.nullish()})).and(f({state:_("idle")})),xO=va.and(f({state:_("requires_action")})),kO=$a.and(f({state:_("unknown")})),SO=f({stopReason:_("end_turn")}),vO=f({stopReason:_("max_tokens")}),$O=f({stopReason:_("max_turn_requests")}),EO=f({stopReason:_("refusal")}),IO=f({stopReason:_("cancelled")}),CO=ka.and(f({error:Jt.nullish()})).and(f({stopReason:_("error")})),TO=f({stopReason:ho().optional()}),AO=Ka.and(f({action:_("accept")})),RO=f({action:_("decline")}),OO=f({action:_("cancel")})});function vo(e,t){if(!e)return t;if(typeof e==="function")return e(t);return e.parse(t)}function tg(e,t,n,r,o,i){let s=async(a,u,d,p)=>{try{let g=await r(n(a,d,u.signal,u.id,p)),w=o?o(g):g;i?.beforeResponse(a,w,d),await u.respond(w)}catch(g){throw i?.onError(d,g),g}};if(t.method==="*")e.withFallbackHandler({handleMessage:async(a,u)=>{if(a.kind!=="request")return K.no(a);return await s(a.params,a.responder,u,a.method),K.yes()}});else e.onReceiveRequest(t.method,(a)=>vo(t.params,a),(a,u,d)=>s(a,u,d,t.method))}function ng(e,t,n,r){if(t.method==="*")e.withFallbackHandler({handleMessage:async(o,i)=>{if(o.kind!=="notification")return K.no(o);return await r(n(o.params,i,i.signal,o.method)),K.yes()}});else e.onReceiveNotification(t.method,(o)=>vo(t.params,o),(o,i)=>r(n(o,i,i.signal,t.method)))}var rg=v(()=>{ge()});var og;var Qa=v(()=>{og=Symbol("connectionContextOf")});function Hv(e){return{handleMessage(t,n){if(t.kind!=="request"||!e()||ig.has(n))return K.no(t);if(t.method!==S.initialize)return t.responder.respondWithError(T.invalidRequest(void 0,`ACP connection must be initialized before '${t.method}'`)).then(()=>K.yes());let{responder:r}=t;return K.no({...t,responder:new kr(r.id,(o)=>{if("result"in o)ig.add(n);return r.respondWithResult(o)},r.signal)})},describe:()=>"agent-initialization"}}function te(e){return e??{}}function Gv(e){return typeof e==="object"&&e!==null&&"readable"in e&&"writable"in e}function Wv(){let e=new TransformStream,t=new TransformStream;return[{readable:t.readable,writable:e.writable},{readable:e.readable,writable:t.writable}]}class rc{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}}function Kv(e,t=[]){return new lg(e,t)}function Jv(e,t=[]){return new dg(e,t)}class fg{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();if(t)t.resolve(e);else this.values.push({kind:"value",value:e})}reject(e){if(this.failed)return;if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}clearErrors(){this.values=this.values.filter((e)=>e.kind==="value")}fail(e){if(this.failed)return;this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}next(){if(this.values.length>0){let e=this.values.shift();if(e.kind==="error")return Promise.reject(e.error);return Promise.resolve(e.value)}if(this.failed)return Promise.reject(this.failure);return new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}}function sg(e){return{...e,additionalDirectories:e.additionalDirectories?[...e.additionalDirectories]:void 0,mcpServers:[...e.mcpServers]}}class $o{cx;request;constructor(e,t){this.cx=e,this.request=sg(t)}static create(e,t){return new $o(e,t)}toRequest(){return sg(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[ug](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}}function L(e,t,n){return{method:e,params:(r)=>vo(t,r??{}),mapResponse:n}}function Un(e,t){return{method:e,params:t}}function Eo(e){let t={};for(let n of Object.values(e))t[n.method]=n;return t}function r$(e,t,n,r,o){return{method:o,params:e,requestId:r,signal:n,client:t}}function o$(e,t,n,r){return{method:r,params:e,signal:n,client:t}}class mg{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==O.session_update)return K.no(e);let t=zo.parse(e.params),n={kind:"session_update",notification:t,update:t.update},r=this.activeSessions.get(t.sessionId);if(r&&r.size>0)for(let o of r)o.enqueue(n);return K.no(e)}attach(e,t){let n=this.activeSessions.get(e.sessionId)??new Set;return n.add(t),this.activeSessions.set(e.sessionId,n),new hn(()=>{if(n.delete(t),n.size===0)this.activeSessions.delete(e.sessionId)})}}function i$(e){let t=ag.get(e);if(!t)t=new mg,ag.set(e,t);return t}function ic(e,t){for(let n of t){let r;try{r=n(e)}catch(o){throw e.close(o),o}Promise.resolve(r).catch((o)=>{e.close(o)})}}function hg(e){return new gg(e)}var ig,$t,ug,tc,Zn,nc,lg,dg,oc,Yv,Xv,Qv,e$,pg,t$,n$,KO,ag,cg,ec,s$,gg,sc;var wg=v(()=>{pn();Xa();Qh();eg();pn();ge();zn();rg();Qa();ge();ig=new WeakSet;$t={agent:{initialize:S.initialize,authenticate:S.authenticate,logout:S.logout,auth:{status:S.auth_status},providers:{list:S.providers_list,set:S.providers_set,disable:S.providers_disable},session:{new:S.session_new,load:S.session_load,list:S.session_list,delete:S.session_delete,fork:S.session_fork,archive:S.session_archive,unarchive:S.session_unarchive,status:S.session_status,setTitle:S.session_set_title,resume:S.session_resume,close:S.session_close,setMode:S.session_set_mode,setConfigOption:S.session_set_config_option,prompt:S.session_prompt,cancel:S.session_cancel},mcp:{message:S.mcp_message}},client:{session:{requestPermission:O.session_request_permission,update:O.session_update},fs:{writeTextFile:O.fs_write_text_file,readTextFile:O.fs_read_text_file},terminal:{create:O.terminal_create,output:O.terminal_output,release:O.terminal_release,waitForExit:O.terminal_wait_for_exit,kill:O.terminal_kill},mcp:{message:O.mcp_message},elicitation:{create:O.elicitation_create,complete:O.elicitation_complete},auth:{statusUpdate:O.auth_status_update}},protocol:{cancelRequest:Ti.cancel_request}},ug=Symbol("startActiveSession");tc=class tc{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}[og](){return this.cx}sendRequest(e,t,n,r){return this.cx.sendRequest(e,t,n,r)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}};Zn=class Zn extends tc{constructor(e,t){super(e,t)}static create(e,t){return new Zn(e,t)}async createTerminal(e,t){let n=await this.request(O.terminal_create,e,t);return sc.create(n.terminalId,e.sessionId,this.connectionContext)}request(e,t,n){let r=n$[e];return this.sendRequest(e,t,r?.mapResponse,n)}notify(e,t){return this.sendNotification(e,t)}};nc=class nc extends tc{constructor(e,t){super(e,t)}static create(e,t){return new nc(e,t)}[ug](e,t){return this.sendRequest(S.session_new,e,(n)=>this.attachSession(n),t)}buildSession(e){if(typeof e==="string")return $o.create(this,{cwd:e,mcpServers:[]});return $o.create(this,e)}attachSession(e){let t=new fg,n=this.connectionContext.signal,r=()=>{t.fail(n.reason??Error("ACP connection closed"))};if(n.aborted)r();else n.addEventListener("abort",r);let o=i$(this.connectionContext).attach(e,t),i=new hn(()=>{n.removeEventListener("abort",r)});return oc.create(this,e,t,[o,i])}request(e,t,n){let r=pg[e];return Wu(e,this.sendRequest(e,t,r?.mapResponse,n),()=>r?.mapResponse?r.mapResponse({}):{})}notify(e,t){return this.sendNotification(e,t)}};lg=class lg extends rc{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e);this.connectHandlers=t,this.client=Zn.create(e.getContext())}startConnectHandlers(){if(this.didStartConnectHandlers)return;this.didStartConnectHandlers=!0,ic(this,this.connectHandlers)}};dg=class dg extends rc{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e);this.connectHandlers=t,this.agent=nc.create(e.getContext())}startConnectHandlers(){if(this.didStartConnectHandlers)return;this.didStartConnectHandlers=!0,ic(this,this.connectHandlers)}};oc=class oc{cx;sessionResponse;updates;registrations;constructor(e,t,n,r){this.cx=e,this.sessionResponse=t,this.updates=n,this.registrations=r}static create(e,t,n,r){return new oc(e,t,n,r)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let n=this.cx.request(S.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return n.then((r)=>{this.updates.enqueue({kind:"stop",response:r,stopReason:r.stopReason})},(r)=>{this.updates.reject(r)}),n}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:n}=t;if(n.sessionUpdate==="agent_message_chunk"&&n.content.type==="text")e+=n.content.text}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){if(typeof e==="string")return[{type:"text",text:e}];if(Array.isArray(e))return e;return[e]}};Yv={initialize:L(S.initialize,xo),newSession:L(S.session_new,Pa),loadSession:L(S.session_load,La,te),unstable_forkSession:L(S.session_fork,ja),listSessions:L(S.session_list,Ma),deleteSession:L(S.session_delete,Da,te),unstable_archiveSession:L(S.session_archive,Ua,te),unstable_unarchiveSession:L(S.session_unarchive,Za,te),unstable_sessionStatus:L(S.session_status,Ba),unstable_setSessionTitle:L(S.session_set_title,Fa),resumeSession:L(S.session_resume,Va),closeSession:L(S.session_close,qa,te),setSessionMode:L(S.session_set_mode,Ha,te),setSessionConfigOption:L(S.session_set_config_option,Ga),authenticate:L(S.authenticate,Ca,te),unstable_listProviders:L(S.providers_list,Ta),unstable_setProvider:L(S.providers_set,Aa,te),unstable_disableProvider:L(S.providers_disable,Ra,te),logout:L(S.logout,Oa,te),unstable_authStatus:L(S.auth_status,Na),prompt:L(S.session_prompt,Wa)},Xv={cancel:Un(S.session_cancel,Ja),unstable_messageMcp:Un(S.mcp_message,Ya)},Qv={requestPermission:L(O.session_request_permission,ta),writeTextFile:L(O.fs_write_text_file,Xs,te),readTextFile:L(O.fs_read_text_file,Qs),createTerminal:L(O.terminal_create,na),terminalOutput:L(O.terminal_output,ra),releaseTerminal:L(O.terminal_release,oa,te),waitForTerminalExit:L(O.terminal_wait_for_exit,ia),killTerminal:L(O.terminal_kill,sa,te),createElicitation:L(O.elicitation_create,ha),unstable_messageMcp:L(O.mcp_message,wa)},e$={sessionUpdate:Un(O.session_update,zo),completeElicitation:Un(O.elicitation_complete,Ea),unstable_authStatusUpdate:Un(O.auth_status_update,Ia)},pg=Eo(Yv),t$=Eo(Xv),n$=Eo(Qv),KO=Eo(e$);ag=new WeakMap;cg=Symbol("appBuilder"),ec=Symbol("runAgentConnectHandlers"),s$=Symbol("runClientConnectHandlers");gg=class gg{builder=Sr.builder();connectHandlers=[];fallbackKinds=new Set;hasInitializeHandler=!1;constructor(e={}){if(this.builder.withHandler(Hv(()=>this.hasInitializeHandler)),e.name)this.builder.name(e.name)}[cg](){return this.builder}[ec](e){ic(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:n,connection:r}=this.connectConnection(e);return n.runUntil(()=>t(r.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,n){if(e==="*"){if(n)throw Error("Wildcard handlers receive raw params; omit the parser.");if(this.fallbackKinds.has("request"))throw Error("A request fallback is already registered.");return this.fallbackKinds.add("request"),this.request({method:e},t)}if(n)return this.request({method:e,params:t},n);let r=pg[e];if(!r)throw Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);if(e===S.initialize)this.hasInitializeHandler=!0;return this.request(r,t)}onNotification(e,t,n){if(e==="*"){if(n)throw Error("Wildcard handlers receive raw params; omit the parser.");if(this.fallbackKinds.has("notification"))throw Error("A notification fallback is already registered.");return this.fallbackKinds.add("notification"),this.notification({method:e},t)}if(n)return this.notification({method:e,params:t},n);let r=t$[e];if(!r)throw Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(r,t)}request(e,t){return tg(this.builder,e,(n,r,o,i,s)=>r$(n,Zn.create(r,i),o,i,s),t,e.mapResponse),this}notification(e,t){return ng(this.builder,e,(n,r,o,i)=>o$(n,Zn.create(r),o,i),t),this}connectConnection(e,t={}){if(Gv(e)){let a=this.openStreamConnection(e);if(!t.deferConnectHandlers)this[ec](a.connection);return a}let[n,r]=Wv(),o=e[cg]().connect(r),i=Jv(o),s=this.openStreamConnection(n);s.rawConnection.closed.then(()=>i.close()),o.closed.then(()=>s.connection.close());try{e[s$](i),this[ec](s.connection)}catch(a){throw i.close(a),s.connection.close(a),a}return s}openStreamConnection(e){let t=this.builder.connect(e);return{rawConnection:t,connection:Kv(t,this.connectHandlers)}}};sc=class sc{id;sessionId;connection;constructor(e,t,n){this.id=e,this.sessionId=t,this.connection=n}static create(e,t,n){return new sc(e,t,n)}currentOutput(){return this.connection.sendRequest(O.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(O.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(O.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},te)}release(){return this.connection.sendRequest(O.terminal_release,{sessionId:this.sessionId,terminalId:this.id},te)}async[Symbol.asyncDispose](){await this.release()}}});var _g=v(()=>{Qa();ge()});var bg=v(()=>{_g()});var yg=v(()=>{pn();wg();bg()});import{randomUUID as c$}from"node:crypto";function zg(e,t,n){let r=new Map,o=(i)=>{let s=r.get(i);r.delete(i),s?.turn?.abort(),s?.release()};return hg({name:`nimblebrain-subscription-${e.id}`}).onRequest($t.agent.initialize,()=>({protocolVersion:Ai,agentCapabilities:{loadSession:!1,promptCapabilities:{embeddedContext:!0},mcpCapabilities:{acp:!0,http:!1},...e.takesSystemPrompt?{sessionCapabilities:{systemPrompt:{mode:{override:{}}}}}:{}},agentInfo:{name:`nimblebrain-subscription-${e.id}`,version:p$},...n||e.modelLabel?{_meta:{...n?{[l$]:n}:{},...e.modelLabel?{[d$]:e.modelLabel}:{}}}:{}})).onRequest($t.agent.session.new,(i)=>{let s=_$(i.params._meta),a=c$(),u=i.params.systemPrompt?.content.map((b)=>b.type==="text"?b.text:"").join(`
67
67
 
68
- `);return r.set(d,{mcpUrl:a,release:l,...f?{system:f}:{}}),{sessionId:d}}).onRequest(xt.agent.session.prompt,async(i)=>{let s=r.get(i.params.sessionId);if(!s)throw T.invalidParams(void 0,"unknown session");s.turn?.abort();let a=new AbortController;s.turn=a;let l=performance.now();Lt(`turn started on ${e.label}`);try{let d=await e.run({prompt:Mv(i.params.prompt),...s.system?{system:s.system}:{},mcpUrl:s.mcpUrl,signal:a.signal,emit:(g)=>void i.client.notify(xt.client.session.update,{sessionId:i.params.sessionId,update:g}).catch(()=>{})}),f=d.usage;return Lt(`turn ${d.stopReason} in ${Math.round(performance.now()-l)}ms: ${f.inputTokens+(f.cacheReadTokens??0)} in / ${f.outputTokens} out tokens, billed to the subscription`),{stopReason:d.stopReason,usage:{inputTokens:f.inputTokens,outputTokens:f.outputTokens,totalTokens:f.inputTokens+f.outputTokens,cachedReadTokens:f.cacheReadTokens??0,cachedWriteTokens:f.cacheWriteTokens??0},_meta:{[Ov]:{calls:d.calls}}}}catch(d){let f=Dv(d,e.label);throw Lt(`turn failed (${f.code}): ${f.message}`),T.internalError({[yc]:{code:f.code,message:f.message}},`${e.label} turn failed: ${f.code}`)}finally{if(s.turn===a)s.turn=void 0}}).onNotification(xt.agent.session.cancel,(i)=>{r.get(i.params.sessionId)?.turn?.abort()}).onRequest(xt.agent.session.close,(i)=>(o(i.params.sessionId),{})).onConnect((i)=>{i.closed.then(()=>{for(let s of[...r.keys()])o(s)})})}function Dv(e,t){if(e instanceof Ne)return{code:e.code,message:e.message};if(e instanceof Q)return{code:Lv[e.reason],message:e.message};return{code:"cli_failed",message:`${t} could not finish the turn. Check the agent worker's log, then send your message again.`}}function Mv(e){return e.map((t)=>{if(t.type==="text")return t.text;if(t.type==="resource"&&"text"in t.resource)return t.resource.text;return""}).filter(Boolean).join(`
68
+ `),d=u?{system:u}:{};if(s==="internal")return r.set(a,{purpose:s,release:()=>{},...d}),{sessionId:a};let p=i.params.mcpServers.find((b)=>("type"in b)&&b.type==="acp");if(!p||!("serverId"in p))throw T.invalidParams(void 0,"the session names no acp MCP server");let{url:g,release:w}=t.bind(i.client,p.serverId);return r.set(a,{purpose:s,mcpUrl:g,release:w,...d}),{sessionId:a}}).onRequest($t.agent.session.prompt,async(i)=>{let s=r.get(i.params.sessionId);if(!s)throw T.invalidParams(void 0,"unknown session");s.turn?.abort();let a=new AbortController;s.turn=a;let u=performance.now();Bt(`${g$[s.purpose]} started on ${e.label}`);try{let d=await e.run({prompt:b$(i.params.prompt),...w$(s),signal:a.signal,emit:(g)=>void i.client.notify($t.client.session.update,{sessionId:i.params.sessionId,update:g}).catch(()=>{})}),p=d.usage;return Bt(`turn ${d.stopReason} in ${Math.round(performance.now()-u)}ms: ${p.inputTokens+(p.cacheReadTokens??0)} in / ${p.outputTokens} out tokens, billed to the subscription`),{stopReason:d.stopReason,usage:{inputTokens:p.inputTokens,outputTokens:p.outputTokens,totalTokens:p.inputTokens+p.outputTokens,cachedReadTokens:p.cacheReadTokens??0,cachedWriteTokens:p.cacheWriteTokens??0},_meta:{[u$]:{calls:d.calls}}}}catch(d){let p=h$(d,e.label);throw Bt(`turn failed (${p.code}): ${p.message}`),T.internalError({[Vc]:{code:p.code,message:p.message}},`${e.label} turn failed: ${p.code}`)}finally{if(s.turn===a)s.turn=void 0}}).onNotification($t.agent.session.cancel,(i)=>{r.get(i.params.sessionId)?.turn?.abort()}).onRequest($t.agent.session.close,(i)=>(o(i.params.sessionId),{})).onConnect((i)=>{i.closed.then(()=>{for(let s of[...r.keys()])o(s)})})}function h$(e,t){if(e instanceof Pe)return{code:e.code,message:e.message};if(e instanceof X)return{code:m$[e.reason],message:e.message};return{code:"cli_failed",message:`${t} could not finish the turn. Check the agent worker's log, then send your message again.`}}function w$(e){return{purpose:e.purpose,...e.system?{system:e.system}:{},...e.mcpUrl?{mcpUrl:e.mcpUrl}:{}}}function _$(e){return e?.[f$]?.purpose==="internal"?"internal":"turn"}function b$(e){return e.map((t)=>{if(t.type==="text")return t.text;if(t.type==="resource"&&"text"in t.resource)return t.resource.text;return""}).filter(Boolean).join(`
69
69
 
70
- `)}var Ov="nimblebrain-subscription/usage",Nv="nimblebrain-subscription/plan",Pv="0.1.0",Lv;var ng=S(()=>{eg();Yt();It();Lv={api_key:"api_key",not_signed_in:"signed_out",not_installed:"cli_missing",unreadable:"cli_failed"}});import{randomBytes as jv}from"node:crypto";function og(e){let t=new Map;return{bind(n,r){let o=jv(24).toString("hex");return t.set(o,{client:n,serverId:r}),{url:`${e()}${xo}${o}`,release:()=>t.delete(o)}},async handle(n,r){let o=(n.url??"").slice(xo.length).split(/[/?]/)[0]??"",i=t.get(o);if(!i)return Pn(r,404);if(n.method==="DELETE")return Pn(r,200);if(n.method!=="POST")return Pn(r,405);return Uv(i,n,r)}}}async function Uv(e,t,n){let r;try{r=JSON.parse(await Bv(t))}catch{return Pn(n,400)}let o=Array.isArray(r)?r:[r],i=(await Promise.all(o.map((s)=>Zv(e,s)))).filter((s)=>s!==void 0);if(i.length===0)return Pn(n,202);n.writeHead(200,{"content-type":"application/json"}),n.end(JSON.stringify(Array.isArray(r)?i:i[0]))}async function Zv({client:e,serverId:t},n){if(!n.method)return;if(n.id===void 0||n.id===null){await e.notify(rg,{serverId:t,method:n.method,params:n.params});return}let{id:r}=n;try{let o=await e.request(rg,{serverId:t,requestId:String(r),method:n.method,...n.params?{params:n.params}:{}});return{jsonrpc:"2.0",id:r,...o}}catch(o){return{jsonrpc:"2.0",id:r,error:{code:-32603,message:o instanceof Error?o.message:String(o)}}}}function Bv(e){return new Promise((t,n)=>{let r="";e.on("data",(o)=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",n)})}function Pn(e,t){e.writeHead(t),e.end()}var rg="mcp/message",xo="/mcp/";var ig=()=>{};import{createServer as Fv}from"node:http";function qv(e){if(e.headers.origin!==void 0)return!1;let t=e.headers.host;if(!t)return!1;try{return Vv.has(new URL(`http://${t}`).hostname)}catch{return!1}}async function ag(e,t,n){let o="",i=og(()=>o),s=new Ti({createAgent:()=>tg(e,i,n)}),a=Zu(s),l=async(w,b)=>{if(!qv(w))return b.writeHead(403),void b.end();let z=new URL(w.url??"/","http://worker").pathname;if(z==="/healthz")return b.writeHead(200,{"content-type":"text/plain"}),void b.end("ok");if(z===sg)return a(w,b);if(z.startsWith(xo))return i.handle(w,b);b.writeHead(404),b.end()},d=Fv((w,b)=>{l(w,b).catch(()=>{if(!b.headersSent)b.writeHead(500);b.end()})});await new Promise((w,b)=>{d.once("error",b),d.listen(t,"127.0.0.1",()=>w())});let f=d.address();return o=`http://127.0.0.1:${typeof f==="object"&&f?f.port:t}`,{acpUrl:`${o}${sg}`,async stop(){await s.close(),d.closeAllConnections(),await new Promise((w)=>d.close(()=>w()))}}}var sg="/acp",Vv;var cg=S(()=>{Fu();pl();ng();ig();Vv=new Set(["127.0.0.1","localhost","host.docker.internal"])});import{parseArgs as Hv}from"node:util";function ko(){process.stderr.write(`usage: nimblebrain ${it} <claude|codex> [--port <n>] [--model <id>] [--log <path>]
70
+ `)}var u$="nimblebrain-subscription/usage",l$="nimblebrain-subscription/plan",d$="nimblebrain-subscription/model",f$="nimblebrain-subscription/session",p$="0.1.0",m$,g$;var xg=v(()=>{yg();rn();Pt();m$={api_key:"api_key",not_signed_in:"signed_out",not_installed:"cli_missing",unreadable:"cli_failed"};g$={turn:"turn",internal:"internal run"}});import{randomBytes as y$}from"node:crypto";function Sg(e){let t=new Map;return{bind(n,r){let o=y$(24).toString("hex");return t.set(o,{client:n,serverId:r}),{url:`${e()}${Io}${o}`,release:()=>t.delete(o)}},async handle(n,r){let o=(n.url??"").slice(Io.length).split(/[/?]/)[0]??"",i=t.get(o);if(!i)return Bn(r,404);if(n.method==="DELETE")return Bn(r,200);if(n.method!=="POST")return Bn(r,405);return z$(i,n,r)}}}async function z$(e,t,n){let r;try{r=JSON.parse(await k$(t))}catch{return Bn(n,400)}let o=Array.isArray(r)?r:[r],i=(await Promise.all(o.map((s)=>x$(e,s)))).filter((s)=>s!==void 0);if(i.length===0)return Bn(n,202);n.writeHead(200,{"content-type":"application/json"}),n.end(JSON.stringify(Array.isArray(r)?i:i[0]))}async function x$({client:e,serverId:t},n){if(!n.method)return;if(n.id===void 0||n.id===null){await e.notify(kg,{serverId:t,method:n.method,params:n.params});return}let{id:r}=n;try{let o=await e.request(kg,{serverId:t,requestId:String(r),method:n.method,...n.params?{params:n.params}:{}});return{jsonrpc:"2.0",id:r,...o}}catch(o){return{jsonrpc:"2.0",id:r,error:{code:-32603,message:o instanceof Error?o.message:String(o)}}}}function k$(e){return new Promise((t,n)=>{let r="";e.on("data",(o)=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",n)})}function Bn(e,t){e.writeHead(t),e.end()}var kg="mcp/message",Io="/mcp/";var vg=()=>{};import{createServer as S$}from"node:http";function $$(e){if(e.headers.origin!==void 0)return!1;let t=e.headers.host;if(!t)return!1;try{return v$.has(new URL(`http://${t}`).hostname)}catch{return!1}}async function Eg(e,t,n){let o="",i=Sg(()=>o),s=new Bi({createAgent:()=>zg(e,i,n)}),a=al(s),u=async(w,b)=>{if(!$$(w))return b.writeHead(403),void b.end();let z=new URL(w.url??"/","http://worker").pathname;if(z==="/healthz")return b.writeHead(200,{"content-type":"text/plain"}),void b.end("ok");if(z===$g)return a(w,b);if(z.startsWith(Io))return i.handle(w,b);b.writeHead(404),b.end()},d=S$((w,b)=>{u(w,b).catch(()=>{if(!b.headersSent)b.writeHead(500);b.end()})});await new Promise((w,b)=>{d.once("error",b),d.listen(t,"127.0.0.1",()=>w())});let p=d.address();return o=`http://127.0.0.1:${typeof p==="object"&&p?p.port:t}`,{acpUrl:`${o}${$g}`,async stop(){await s.close(),d.closeAllConnections(),await new Promise((w)=>d.close(()=>w()))}}}var $g="/acp",v$;var Ig=v(()=>{ul();Rl();xg();vg();v$=new Set(["127.0.0.1","localhost","host.docker.internal"])});import{parseArgs as E$}from"node:util";function Co(){process.stderr.write(`usage: nimblebrain ${at} <claude|codex> [--port <n>] [--model <id>] [--log <path>]
71
71
  Runs NimbleBrain's agent turns on the Claude Code or Codex you are signed in to,
72
72
  billed to your subscription, never an API key. \`npx nimblebrain use\` starts it for you.
73
- `),process.exit(2)}function Gv(e){let t;try{t=Wv(e)}catch{ko()}let[n,...r]=t.positionals;if(r.length>0)ko();let{model:o,log:i}=t.values,s={...o?{model:o}:{},...i?{log:i}:{}},a=n==="claude"?kc(s):n==="codex"?vc(s):ko(),l=Number(t.values.port??Ct[a.id]);if(!Number.isInteger(l)||l<1||l>65535)ko();return{backend:a,port:l}}function Wv(e){return Hv({args:e,options:{port:{type:"string"},model:{type:"string"},log:{type:"string"}},allowPositionals:!0,strict:!0})}async function ug(e){let{backend:t,port:n}=Gv(e);try{await Kv(t,n)}catch(r){let o=r instanceof Q?r.message:r.code==="EADDRINUSE"?`port ${n} is in use on 127.0.0.1.`:r instanceof Error?r.message:String(r);process.stderr.write(`
73
+ `),process.exit(2)}function I$(e){let t;try{t=C$(e)}catch{Co()}let[n,...r]=t.positionals;if(r.length>0)Co();let{model:o,log:i}=t.values,s={...o?{model:o}:{},...i?{log:i}:{}},a=n==="claude"?Gc(s):n==="codex"?Kc(s):Co(),u=Number(t.values.port??ct[a.id]);if(!Number.isInteger(u)||u<1||u>65535)Co();return{backend:a,port:u}}function C$(e){return E$({args:e,options:{port:{type:"string"},model:{type:"string"},log:{type:"string"}},allowPositionals:!0,strict:!0})}async function Cg(e){let{backend:t,port:n}=I$(e);try{await T$(t,n)}catch(r){let o=r instanceof X?r.message:r.code==="EADDRINUSE"?`port ${n} is in use on 127.0.0.1.`:r instanceof Error?r.message:String(r);process.stderr.write(`
74
74
  Not started: ${o}
75
75
 
76
- `),process.exit(1)}}async function Kv(e,t){let n=await e.preflight(),r=Bo.filter((a)=>process.env[a]),o=await ag(e,t,n.plan),i=["",` NimbleBrain on ${e.label}`,"",` Billed to: ${n.describe}`,r.length>0?` API keys: ${r.join(", ")} set in this shell, and withheld from ${e.label}`:" API keys: none, so nothing can bill API pricing",` Tools: ${Yn[e.id]}`,` Listening: ${o.acpUrl} (this machine only)`,""," An install made by `npx nimblebrain` dials it once `npx nimblebrain use` has run."," A source checkout (`bun run dev`) dials it with, in nimblebrain.json:","",` "execution": { "default": "${e.id}",`,` "runtimes": { "${e.id}": { "driver": "${e.id}", "url": "${o.acpUrl}" } } }`,""," Every chat turn and run then goes to your subscription. Ctrl-C stops it.",""];process.stderr.write(`${i.join(`
76
+ `),process.exit(1)}}async function T$(e,t){let n=await e.preflight(),r=ei.filter((a)=>process.env[a]),o=await Eg(e,t,n.plan),i=["",` NimbleBrain on ${e.label}`,"",` Billed to: ${n.describe}`,r.length>0?` API keys: ${r.join(", ")} set in this shell, and withheld from ${e.label}`:" API keys: none, so nothing can bill API pricing",` Model: ${e.modelLabel??`${e.label}'s default`}`,` Tools: ${Jn[e.id]}`,` Listening: ${o.acpUrl} (this machine only)`,""," An install made by `npx nimblebrain` dials it once `npx nimblebrain use` has run."," A source checkout (`bun run dev`) dials it with, in nimblebrain.json:","",` "execution": { "default": "${e.id}",`,` "runtimes": { "${e.id}": { "driver": "${e.id}", "url": "${o.acpUrl}" } } }`,""," Every chat turn and run then goes to your subscription. Ctrl-C stops it.",""];process.stderr.write(`${i.join(`
77
77
  `)}
78
- `);let s=async()=>{Lt("stopping"),await o.stop(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}var lg=S(()=>{Ho();Ko();It();Tt();cg()});import{writeSync as So}from"node:fs";import{spawn as Xa}from"node:child_process";import{constants as fg}from"node:fs";import{access as mg,chmod as hg,mkdir as gg,readFile as wg,rename as _g,rm as Qa,rmdir as bg,writeFile as yg}from"node:fs/promises";import{createServer as zg}from"node:net";import{homedir as xg}from"node:os";import{delimiter as kg,dirname as Sg,join as Io,resolve as Co}from"node:path";var vg=2000;function tc(){return{exec(e,t,n={}){return new Promise((r)=>{let o="",i="",s=!1,a=Xa(e,t,{stdio:["ignore","pipe","pipe"],timeout:n.timeoutMs??30000,cwd:n.cwd,env:n.env});a.stdout.on("data",(l)=>{o+=l.toString()}),a.stderr.on("data",(l)=>{i+=l.toString()}),a.on("error",(l)=>{if(l.code==="ENOENT")s=!0}),a.on("close",(l)=>r({code:l,stdout:o,stderr:i,missing:s}))})},launch(e,t){return new Promise((n)=>{let r;try{r=Xa(e,t,{stdio:"ignore",detached:!0})}catch{n(!1);return}let o=setTimeout(()=>{r.unref(),n(!0)},vg);r.once("error",()=>{clearTimeout(o),n(!1)}),r.once("exit",(i)=>{clearTimeout(o),n(i===0)})})},self:{node:process.execPath,script:Co(process.argv[1]??"")},uid:process.getuid?.()??0,async which(e){let t=process.platform==="win32"?(process.env.PATHEXT??".EXE").split(";"):[""];for(let n of(process.env.PATH??"").split(kg).filter(Boolean))for(let r of t)try{return await mg(Io(n,e+r),fg.X_OK),!0}catch{}return!1},portFree(e){return new Promise((t)=>{let n=zg();n.once("error",()=>t(!1)),n.once("listening",()=>n.close(()=>t(!0))),n.listen(e,"127.0.0.1")})},getJson:async(e,t=3000)=>ec(await Eo(e,{headers:{"user-agent":"nimblebrain-cli"}},t)),getText:(e,t=1e4)=>Eo(e,{headers:{"user-agent":"nimblebrain-cli"}},t),postJson:async(e,t,n=5000)=>ec(await Eo(e,{method:"POST",headers:{"user-agent":"nimblebrain-cli","content-type":"application/json"},body:JSON.stringify(t)},n)),async readText(e){try{return await wg(e,"utf8")}catch{return}},async writeText(e,t,n=420){await gg(Sg(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;try{await yg(r,t,{mode:n}),await hg(r,n),await _g(r,e)}catch(o){throw await Qa(r,{force:!0}).catch(()=>{return}),o}},async remove(e){try{await bg(e)}catch(t){if(t.code==="ENOTDIR")await Qa(e,{force:!0})}},prompt:(e,t={})=>t.hidden?Eg(e):$g(e),interactive:Boolean(process.stdin.isTTY&&process.stderr.isTTY),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),say:(e)=>{process.stderr.write(`${e}
79
- `)},env:process.env,platform:process.platform,home:xg(),cwd:process.cwd()}}async function Eo(e,t,n){let r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await fetch(e,{...t,signal:r.signal});return{status:i.status,body:await i.text()}}catch{return}finally{clearTimeout(o)}}function ec(e){if(!e)return;try{return{status:e.status,body:JSON.parse(e.body)}}catch{return e}}async function $g(e){let{createInterface:t}=await import("node:readline/promises"),n=t({input:process.stdin,output:process.stderr});try{return(await n.question(e)).trim()}finally{n.close()}}function Eg(e){return new Promise((t,n)=>{let r=process.stdin;process.stderr.write(e);let o="";r.setRawMode(!0),r.resume(),r.setEncoding("utf8");let i=(a)=>{r.setRawMode(!1),r.pause(),r.removeListener("data",s),process.stderr.write(`
80
- `),a()},s=(a)=>{let l=Ig(o,a);if(o=l.value,l.end==="enter")i(()=>t(o.trim()));if(l.end==="cancel")i(()=>n(Error("Cancelled.")))};r.on("data",s)})}function Ig(e,t){let n=e;for(let r of t){if(r==="\r"||r===`
81
- `)return{value:n,end:"enter"};if(r==="\x03")return{value:n,end:"cancel"};n=r===""||r==="\b"?n.slice(0,-1):n+r}return{value:n}}function Ln(e,t){return Co(e.cwd,t??e.env.NIMBLEBRAIN_HOME??Io(e.home,".nimblebrain-local"))}var Ve="npx nimblebrain";function fe(e,t){let n=Co(e.cwd,Io(e.home,".nimblebrain-local"));if(t===n&&Ln(e)===n)return Ve;return`${Ve} --home ${Cg(t)}`}function Cg(e){return/^[A-Za-z0-9_./,:@%+=-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}function To(e,t){return e.replaceAll(Ve,()=>t)}import{parseArgs as Ug}from"node:util";var Dn={USAGE:"Run `npx nimblebrain --help` for the commands and flags.",DOCKER_MISSING:"Install Docker Desktop or Docker Engine (https://docs.docker.com/get-docker/), then run this again.",DOCKER_NOT_RUNNING:"Start Docker Desktop (or the Docker service), then run this again.",DOCKER_PERMISSION:"Let this user use Docker (https://docs.docker.com/engine/install/linux-postinstall/), sign in again, then run this again.",COMPOSE_MISSING:"Install Docker Compose v2 (https://docs.docker.com/compose/install/) or update Docker Desktop, then run this again.",ARCH_UNSUPPORTED:"NimbleBrain publishes no image for this CPU architecture.",LOW_MEMORY:"Give Docker at least 2 GB of memory in its settings, then run this again.",PORT_IN_USE:"Stop whatever holds the port, or pass --port with a free one.",NOT_INSTALLED:"Run `npx nimblebrain` to install it.",NOT_OURS:"This folder holds files the CLI did not write. Remove them yourself, or choose another --home.",INSTALL_INCOMPLETE:"Run `npx nimblebrain` to finish installing it, or `npx nimblebrain uninstall` to remove it.",NETWORK:"Check the network connection, then run the same command again.",HEALTH_TIMEOUT:"Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",AGENT_UNSUPPORTED:"Pass --agent claude-code, cursor, codex or none.",START_FAILED:"Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",HOME_NOT_SHARED:"Docker cannot read the install's folder. Share this folder with Docker, or move it into a folder Docker shares and pass that folder with --home, then run this again. To install somewhere else instead, run `npx nimblebrain uninstall` first; it deletes this install's data.",NEEDS_TERMINAL:"A person runs this in their own terminal; it asks for input no agent should give.",CANCELLED:"Nothing was changed. Run the command again to go ahead.",RUNTIME_UNSUPPORTED:"Pass a newer runtime with --runtime, or leave it out to install the newest release.",NOT_RUNNING:"Run `npx nimblebrain up`, then run this again.",TELEMETRY_LOCKED:"Nothing to change: DO_NOT_TRACK or the install's configuration decides telemetry here.",LOCAL_MODEL_UNREACHABLE:"Install Ollama (https://ollama.com/download) and start it, then run this again.",LOCAL_MODEL_MISSING:"Download the model with `ollama pull <model>`, or check that Ollama has disk space, then run this again.",LOCAL_MODEL_NO_TOOLS:"Choose a model with tool calling, such as gemma4:e4b; https://docs.nimblebrain.ai/config/local-models/ lists the ones run with NimbleBrain.",LOCAL_CONTEXT_SMALL:"Run `npx nimblebrain local-model` to prepare the model again with a 32k context window.",INTERRUPTED:"Run `npx nimblebrain status` to see what is in place, then run the same command again.",UPDATE_REQUIRED:"Run `npx nimblebrain update`; this install's NimbleBrain cannot reach servers on this machine yet.",WORKSPACE_NOT_FOUND:"Run `npx nimblebrain status` for the workspace ids, then pass one with --workspace.",SERVER_NOT_FOUND:"Run `npx nimblebrain mcp list` for the server names in this workspace.",DIRECT_URL_NOT_ALLOWED:"Adding a server by URL needs a local install made by `npx nimblebrain`; run `npx nimblebrain update`, or add the server to the instance's connector catalog.",URL_NOT_LOOPBACK:"Run the server on this machine and pass its localhost, 127.0.0.1 or [::1] URL, such as http://127.0.0.1:8000/mcp.",URL_INVALID:"Pass the server's full MCP URL, such as http://127.0.0.1:8000/mcp.",INVALID_SERVER_NAME:"Pass another name with --name: lowercase letters, digits and hyphens.",NAME_TAKEN:"Pass another name with --name, or remove the existing one with `npx nimblebrain mcp remove <serverName>`.",NAME_IS_CATALOG_ENTRY:"Pass another name with --name; this one belongs to a catalog connector.",REQUEST_FAILED:"Run `npx nimblebrain logs` and look at the last error line, then run this again.",AGENT_CLI_MISSING:"Install the agent's own CLI (Claude Code or Codex) and sign in to your subscription with it, then run this again.",AGENT_NOT_SIGNED_IN:"Sign the agent's CLI in to your Claude or ChatGPT subscription, then run this again.",AGENT_BILLS_API_KEY:"Sign the agent's CLI in to your Claude or ChatGPT subscription instead of an API key, then run this again.",HOST_LOOPBACK_UNREACHABLE:"Run NimbleBrain on your subscription from macOS for now. On Linux, NimbleBrain's container reaches this machine over the Docker bridge, not 127.0.0.1, and the agent worker listens on 127.0.0.1 only. `npx nimblebrain key` gives NimbleBrain a model key instead.",PLATFORM_UNSUPPORTED:"Run NimbleBrain on your subscription from macOS for now. `npx nimblebrain key` gives NimbleBrain a model key instead.",MODEL_KEY_MISSING:"Run `npx nimblebrain key` in your own terminal to enter a model key, then run this again.",AGENT_WORKER_FAILED:"Read agent-worker.log in the install's folder (its path is in log) for why the agent worker stopped, then run this again."},Tg={DOCKER_MISSING:{mac_brew:"Install Docker Desktop with `brew install --cask docker`, open it once from Applications, then run this again.",mac:"Install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/), open it once, then run this again."},DOCKER_NOT_RUNNING:{colima:"Start Colima with `colima start`, then run this again."},COMPOSE_MISSING:{brew:"Install Compose with `brew install docker-compose`, then run this again."},LOW_MEMORY:{colima:"Restart Colima with more memory: `colima stop && colima start --memory 4`, then run this again.",docker_desktop:"In Docker Desktop, open Settings > Resources, set Memory to at least 2 GB, apply, then run this again."},AGENT_CLI_MISSING:{claude:"Install or update Claude Code (https://claude.com/claude-code), run `claude` and sign in with your Claude account, then run this again.",codex:"Install or update Codex with `npm i -g @openai/codex`, run `codex login` and choose Sign in with ChatGPT, then run this again."},AGENT_NOT_SIGNED_IN:{claude:"Run `claude`, sign in with your Claude account, then run this again.",codex:"Run `codex login`, choose Sign in with ChatGPT, then run this again."},AGENT_BILLS_API_KEY:{claude:"Run `claude /login`, choose your Claude subscription, then run this again.",codex:"Run `codex logout`, then `codex login` and choose Sign in with ChatGPT, then run this again."},LOCAL_MODEL_UNREACHABLE:{brew_install:"Install Ollama with `brew install ollama`, then run this again; it offers to start Ollama for you.",app:"Open the Ollama app, then run this again.",brew:"Run `brew services start ollama` (it then also starts at login), then run this again.",systemd:"Run `sudo systemctl start ollama`, then run this again.",serve:"Run `ollama serve` in another terminal, then run this again."}};class x extends Error{code;fix;detail;variant;constructor(e,t,n={},r){super(t??e);this.code=e;let o=Tg[e];this.fix=r&&o?.[r]||Dn[e],this.variant=r,this.detail=n}with(e,t=this.message){return new x(this.code,t,{...this.detail,...e},this.variant)}}function Mn(e){return{...e.detail,ok:!1,error:e.code,message:e.message,fix:e.fix}}function nc(e){return e.ok?0:Ao(e.error)}function Ao(e){return e==="USAGE"?2:1}var qe="http://127.0.0.1:11434",Ag="http://host.docker.internal:11434/v1",tt="gemma4:e4b",jn=32768,Rg=3600000,Og=30000,Ng=120000,oc=["NB_LOCAL_MODEL_URL","NB_LOCAL_MODEL","NB_LOCAL_MODEL_CONTEXT"];function kt(e){return e.includes("NB_LOCAL_MODEL_URL")}function Pg(e){return`nimblebrain-${e.replace(/[^A-Za-z0-9._-]+/g,"-")}`}function ue(e){let n=e.split(`
82
- `).find((r)=>r.startsWith("NB_LOCAL_MODEL="))?.slice(15).trim();return n?n:void 0}async function Ro(e,t){let n=await e.postJson(`${qe}/api/show`,{model:t});return n?.status===200?n.body:void 0}function Lg(e){let t=e?.match(/^num_ctx\s+(\d+)/m);return t?Number(t[1]):void 0}async function Un(e){let t=await e.getJson(`${qe}/api/version`),n=t?.body?.version;return t?.status===200&&typeof n==="string"?n:void 0}var Dg=["/etc/systemd/system/ollama.service","/usr/lib/systemd/system/ollama.service"];async function Mg(e){let t=["/Applications",`${e.home}/Applications`].map((r)=>`${r}/Ollama.app/Contents/Info.plist`);if(e.platform==="darwin"&&await rc(e,t))return{kind:"app",start:["open","-g","-a","Ollama"],fix:"app"};if(e.platform==="linux"&&await rc(e,Dg))return{kind:"systemd",start:["systemctl","start","--no-ask-password","ollama"],fix:"systemd"};let n=await e.exec("brew",["list","--versions","ollama"]);if(n.code===0&&n.stdout.trim())return{kind:"brew",start:["brew","services","start","ollama"],fix:"brew"};if(await e.which("ollama"))return{kind:"binary",fix:"serve"};return{kind:"none",fix:n.missing?void 0:"brew_install"}}async function rc(e,t){for(let n of t)if(await e.readText(n)!==void 0)return!0;return!1}async function nt(e,t){let n=await Un(e);if(n)return{version:n};let r=await Mg(e),o=(d,f={})=>new x("LOCAL_MODEL_UNREACHABLE",d,{check:"ollama",ollama:r.kind,...f},r.fix);if(!r.start)throw o(r.kind==="none"?`Ollama does not answer at ${qe}, and it does not look installed.`:`Ollama does not answer at ${qe}.`);let i=r.start.join(" ");if(!await t(i))throw o(`Ollama is installed but not running at ${qe}; it was not started.`);e.say(`Starting Ollama: ${i}`);let[s="",...a]=r.start,l=await e.exec(s,a,{timeoutMs:60000});if(l.code!==0||l.missing){let d=l.stderr.trim().split(`
83
- `)[0];throw o(`\`${i}\` did not start Ollama${d?`: ${d}`:"."}`)}for(let d=0;d<Og;d+=1000){await e.sleep(1000);let f=await Un(e);if(f){if(e.say(`Ollama ${f} is running.`),e.platform==="linux")e.say("On Linux, NimbleBrain's container reaches Ollama only when it listens beyond 127.0.0.1 (OLLAMA_HOST=0.0.0.0).");return{version:f,started:i}}}throw o(`Ollama was started with \`${i}\` but did not answer at ${qe} within 30 seconds.`,{ollama_started:i})}async function ic(e,t,n){let{started:r}=await nt(e,n.start);try{return{values:await jg(e,t,n.pull),started:r}}catch(o){if(o instanceof x&&r)throw o.with({ollama_started:r});throw o}}async function jg(e,t,n){let r=await Ro(e,t);if(!r){if(!await n(t))throw new x("LOCAL_MODEL_MISSING",`Ollama has no model "${t}".`,{check:"model"});if(e.say(`Downloading ${t} with Ollama. A model is several GB; this can take a while.`),r=(await e.postJson(`${qe}/api/pull`,{model:t,stream:!1},Rg))?.status===200?await Ro(e,t):void 0,!r)throw new x("LOCAL_MODEL_MISSING",`Ollama could not download "${t}".`,{check:"model"})}if(!r.capabilities?.includes("tools"))throw new x("LOCAL_MODEL_NO_TOOLS",`${t} does not support tool calling, which NimbleBrain's agents need.`,{check:"tools"});let o=Pg(t);if((await e.postJson(`${qe}/api/create`,{model:o,from:t,parameters:{num_ctx:jn},stream:!1},Ng))?.status!==200)throw new x("LOCAL_MODEL_MISSING",`Ollama could not prepare ${o} from ${t}.`,{check:"model"});return{NB_LOCAL_MODEL_URL:Ag,NB_LOCAL_MODEL:o,NB_LOCAL_MODEL_CONTEXT:String(jn)}}async function sc(e,t,n){let r=[],{version:o,started:i}=await nt(e,n).catch((d)=>{if(!(d instanceof x))throw d;throw r.push({check:"ollama",ok:!1,detail:d.message}),d.with({check:"ollama",checks:r})});r.push({check:"ollama",ok:!0,detail:i?`${o} (started: ${i})`:o});let s=await Ro(e,t),a=(d,f,g)=>{throw r.push({check:d,ok:!1,detail:g}),new x(f,g,{check:d,checks:r,ollama_started:i})};if(!s)a("model","LOCAL_MODEL_MISSING",`Ollama has no model "${t}".`);if(r.push({check:"model",ok:!0,detail:t}),!s?.capabilities?.includes("tools"))a("tools","LOCAL_MODEL_NO_TOOLS",`${t} does not support tool calling.`);r.push({check:"tools",ok:!0,detail:"tool calling"});let l=Lg(s?.parameters);if(l===void 0||l<jn)a("context","LOCAL_CONTEXT_SMALL",`${t} has a context window of ${l??"Ollama's default"}, below ${jn}.`);return r.push({check:"context",ok:!0,detail:`${l} tokens`}),{checks:r,started:i}}var Zn={init:{args:[],description:"Check this machine, start NimbleBrain, connect your coding agent (default)"},doctor:{args:[],description:"Check Docker, Compose, architecture, memory and the port; installs nothing"},status:{args:[],description:"Version, health, URL and each workspace's MCP URL"},open:{args:[],description:"Open NimbleBrain's web UI in the default browser"},key:{args:[],description:"Enter the model key at a hidden prompt"},"local-model":{args:["[model]"],description:`Prepare a model served by Ollama for NimbleBrain's agents (default ${tt})`},use:{args:["[claude|codex|api|local]","[model]"],description:"Choose what runs NimbleBrain's agents: claude (your Claude subscription), codex (your ChatGPT plan), api (an API key) or local (an Ollama model); asks when none is named"},telemetry:{args:["[on|off|status]"],description:"Whether this install sends anonymous usage data"},up:{args:[],description:"Start NimbleBrain"},down:{args:[],description:"Stop NimbleBrain; data survives down"},logs:{args:[],description:"Recent runtime log lines"},update:{args:[],description:"Move to the newest release, keeping data, and refresh the connected agent's nimblebrain skill"},uninstall:{args:[],description:"Remove NimbleBrain and its data"},mcp:{args:["<add|list|remove>"],description:"MCP servers in development; see mcp add, list and remove"}},Zg=Object.keys(Zn),Bg=["on","off","status"],St=["claude-code","cursor","codex","none"],He=["claude","codex","api","local"],Gt=`${He.slice(0,-1).join(", ")} or ${He.at(-1)}`,vt=27246,Oo={json:{type:"boolean",description:"One JSON object on stdout; progress and notices go to stderr"},yes:{type:"boolean",short:"y",description:"Take every default; implied when no terminal is attached"},agent:{type:"string",takes:"name",description:`The coding agent to connect: ${St.slice(0,-1).join(", ")} or ${St.at(-1)}`,commands:["init"]},port:{type:"string",takes:"n",description:`Local port (default ${vt}; for doctor, the install's own port; for use, the agent worker's, default 27290 for claude and 27291 for codex)`,commands:["init","doctor","use"]},home:{type:"string",takes:"dir",description:"Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); each home is a separate install"},provider:{type:"string",takes:"name",description:"The model provider for key (default anthropic); the installed release decides which it takes, and key lists them",commands:["key"]},use:{type:"string",takes:He.join("|"),description:"What runs NimbleBrain's agents, as use takes it; without it (or --local-model), init asks a person, or leaves it unchosen and returns the question in model_source.ask",commands:["init"]},"local-model":{type:"string",takes:"model",description:"Run on this Ollama model (implies --use local)",commands:["init"]},runtime:{type:"string",takes:"tag",description:"The NimbleBrain release to install or update to (default the newest)",commands:["init","update"]},"no-open":{type:"boolean",description:"Do not open the web UI in the browser when init finishes",commands:["init"]},telemetry:{type:"string",takes:"on|off",description:"The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided",commands:["init"]},name:{type:"string",takes:"name",description:"The server name (default from the server's card, else its URL)",commands:["mcp add"]},workspace:{type:"string",takes:"id",description:"The workspace (default the one init connected, the first in status)",commands:["mcp add","mcp list","mcp remove"]},help:{type:"boolean",short:"h",description:"The commands and flags; with --json, these, each command's answer and every error code as JSON"},version:{type:"boolean",short:"v",description:"This CLI's version"}},Fg=Object.fromEntries(Object.entries(Oo).map(([e,t])=>[e,t.short?{type:t.type,short:t.short}:{type:t.type}]));function No(e){let{values:t,positionals:n}=Wg(e),r=t.json===!0,o=t.port===void 0?void 0:Number(t.port);if(o!==void 0&&(!Number.isInteger(o)||o<1||o>65535))throw new x("USAGE",`--port must be a port number, not "${t.port}".`);let i;if(t.agent!==void 0){if(!St.includes(t.agent))throw new x("AGENT_UNSUPPORTED",`Unknown agent "${t.agent}".`);i=t.agent}let s=qg(t.telemetry),a=Vg(t.use,t["local-model"]),l={json:r,yes:t.yes===!0,agent:i,port:o,home:t.home,provider:t.provider,localModel:t["local-model"],use:a,runtime:t.runtime,telemetry:s,noOpen:t["no-open"]===!0,name:t.name,workspace:t.workspace};if(t.help)return{kind:"help",flags:l};if(t.version)return{kind:"version",flags:l};let d=n[0]??"init";if(d==="help")return{kind:"help",flags:l};return{kind:"run",command:Hg(d,n),flags:l,arg:n[1],operand:n[2]}}function Vg(e,t){if(e===void 0)return t===void 0?void 0:"local";if(!He.includes(e))throw new x("USAGE",`--use must be ${Gt}, not "${e}".`);if(t!==void 0&&e!=="local")throw new x("USAGE",`--local-model runs on a local model, so it takes --use local, not "${e}".`);return e}function qg(e){if(e===void 0||e==="on"||e==="off")return e;throw new x("USAGE",`--telemetry must be on or off, not "${e}".`)}var Ht={add:{operand:"url",description:"Add an MCP server you run on this machine to a workspace"},list:{operand:null,description:"The servers in a workspace"},remove:{operand:"serverName",description:"Remove a server from a workspace"}};function Hg(e,t){if(!Zg.includes(e))throw new x("USAGE",`Unknown command "${e}".`);if(e==="mcp")return Gg(t);let n=e==="use"?3:e==="telemetry"||e==="local-model"?2:1;if(t.length>n)throw new x("USAGE",`Unexpected argument "${t[n]}".`);let r=t[1];if(e==="telemetry"&&r!==void 0&&!Bg.includes(r))throw new x("USAGE",`telemetry takes on, off or status, not "${r}".`);return e}function Gg(e){let t=e[1];if(t===void 0||!Object.hasOwn(Ht,t))throw new x("USAGE",`mcp takes add <url>, list or remove <serverName>${t===void 0?"":`, not "${t}"`}.`);let{operand:n}=Ht[t],r=n===null?2:3;if(e.length>r)throw new x("USAGE",`Unexpected argument "${e[r]}".`);if(n!==null&&e[2]===void 0)throw new x("USAGE",`mcp ${t} needs a ${n}.`);return"mcp"}function Wg(e){try{return Ug({args:e,options:Fg,allowPositionals:!0,strict:!0})}catch(t){throw new x("USAGE",t instanceof Error?t.message:String(t))}}function Po(e){return e.includes("--json")}import{randomBytes as Kg}from"node:crypto";import{basename as Jg,join as Bn}from"node:path";function cc(e){let t=Jg(e).toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"");return`${!t?"nimblebrain":t.startsWith("nimblebrain")?t:`nimblebrain-${t}`}-${Kg(3).toString("hex")}`}var Yg="https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";async function Lo(e,t){let n=await e.getText(`${Yg}/${t}/docker-compose.yml`,15000);if(!n)throw new x("NETWORK",`Could not download the Compose file for ${t}.`);if(n.status===404)throw new x("RUNTIME_UNSUPPORTED",`NimbleBrain ${t} has no Compose file to install.`);if(n.status!==200)throw new x("NETWORK",`Downloading the Compose file for ${t} answered ${n.status}.`);if(!n.body.includes("${NIMBLEBRAIN_TAG")||!n.body.includes("NIMBLEBRAIN_WEB_PORT"))throw new x("RUNTIME_UNSUPPORTED",`NimbleBrain ${t}'s Compose file does not take its image tag and port from .env.`);return n.body}function xe(e){return[...new Set([...e.matchAll(/\b([A-Z][A-Z0-9_]*_API_KEY)=\$\{\1\b/g)].map((t)=>t[1]??""))]}function uc(e){return e.includes("NB_TELEMETRY_CONSENT")}function Fn(e){return e.includes("NB_HOST_LOOPBACK")}function Do(e){return e.includes("NB_AGENT_RUNTIME_URL")}function Mo(e){return Object.fromEntries(xe(e).map((t)=>[t.replace(/_API_KEY$/,"").replace(/_GENERATIVE_AI$/,"").toLowerCase(),t]))}function Xg(e,t){let n={...e.env};for(let r of[...t,"NIMBLEBRAIN_TAG","NIMBLEBRAIN_WEB_PORT","COMPOSE_PROJECT_NAME","NB_TELEMETRY_KEY","NB_TELEMETRY_ID","NB_TELEMETRY_CONSENT","NB_LOCAL_MODEL_URL","NB_LOCAL_MODEL","NB_LOCAL_MODEL_CONTEXT","NB_AGENT_RUNTIME","NB_AGENT_RUNTIME_URL"])delete n[r];return n}var lc={cmd:"docker",args:["compose"]},ac=new WeakMap;function jo(e){let t=ac.get(e);if(!t)t=Qg(e),ac.set(e,t);return t}async function Qg(e){for(let t of[lc,{cmd:"docker-compose",args:[]}]){let n=await e.exec(t.cmd,[...t.args,"version","--short"]);if(n.code===0&&ew(n.stdout)>=2)return{...t,version:n.stdout.trim()}}return}function ew(e){return Number.parseInt(e.trim().replace(/^v/,""),10)}async function tw(e,t,n){let r=await jo(e)??lc;return e.exec(r.cmd,[...r.args,...t],n)}async function rt(e,t,n,r=120000){let o=xe(await e.readText(R(t).compose)??"");return tw(e,n,{cwd:t,env:Xg(e,o),timeoutMs:r})}async function Wt(e,t){return await e.readText(R(t).env)!==void 0}async function Vn(e,t){if(!await Wt(e,t))return!1;let n=await rt(e,t,["ps","-q"],30000);return n.code===0&&n.stdout.trim()!==""}function Uo(e){return/\/\.colima\/default\//.test(e)?"colima":void 0}function $t(e){let t=`${e.stderr}
78
+ `);let s=async()=>{Bt("stopping"),await o.stop(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s)}var Tg=v(()=>{oi();ai();Pt();Re();Ig()});import{writeSync as To}from"node:fs";import{spawn as lc}from"node:child_process";import{constants as Og,realpathSync as Ng}from"node:fs";import{access as Pg,chmod as Lg,mkdir as Mg,readFile as Dg,rename as jg,rm as dc,rmdir as Ug,writeFile as Zg}from"node:fs/promises";import{createServer as Bg}from"node:net";import{homedir as Fg}from"node:os";import{delimiter as Vg,dirname as qg,join as pc,resolve as No}from"node:path";var Hg=2000;function mc(){return{exec(e,t,n={}){return new Promise((r)=>{let o="",i="",s=!1,a=lc(e,t,{stdio:["ignore","pipe","pipe"],timeout:n.timeoutMs??30000,cwd:n.cwd,env:n.env});a.stdout.on("data",(u)=>{o+=u.toString()}),a.stderr.on("data",(u)=>{i+=u.toString()}),a.on("error",(u)=>{if(u.code==="ENOENT")s=!0}),a.on("close",(u)=>r({code:u,stdout:o,stderr:i,missing:s}))})},launch(e,t){return new Promise((n)=>{let r;try{r=lc(e,t,{stdio:"ignore",detached:!0})}catch{n(!1);return}let o=setTimeout(()=>{r.unref(),n(!0)},Hg);r.once("error",()=>{clearTimeout(o),n(!1)}),r.once("exit",(i)=>{clearTimeout(o),n(i===0)})})},self:{node:process.execPath,script:Gg(process.argv[1]??"")},uid:process.getuid?.()??0,async which(e){let t=process.platform==="win32"?(process.env.PATHEXT??".EXE").split(";"):[""];for(let n of(process.env.PATH??"").split(Vg).filter(Boolean))for(let r of t){let o=pc(n,e+r);try{return await Pg(o,Og.X_OK),o}catch{}}return},portFree(e){return new Promise((t)=>{let n=Bg();n.once("error",()=>t(!1)),n.once("listening",()=>n.close(()=>t(!0))),n.listen(e,"127.0.0.1")})},getJson:async(e,t=3000)=>fc(await Oo(e,{headers:{"user-agent":"nimblebrain-cli"}},t)),getText:(e,t=1e4)=>Oo(e,{headers:{"user-agent":"nimblebrain-cli"}},t),postJson:async(e,t,n=5000)=>fc(await Oo(e,{method:"POST",headers:{"user-agent":"nimblebrain-cli","content-type":"application/json"},body:JSON.stringify(t)},n)),async readText(e){try{return await Dg(e,"utf8")}catch{return}},async writeText(e,t,n=420){await Mg(qg(e),{recursive:!0,mode:448});let r=`${e}.${process.pid}.tmp`;try{await Zg(r,t,{mode:n}),await Lg(r,n),await jg(r,e)}catch(o){throw await dc(r,{force:!0}).catch(()=>{return}),o}},async remove(e){try{await Ug(e)}catch(t){if(t.code==="ENOTDIR")await dc(e,{force:!0})}},prompt:(e,t={})=>t.hidden?Kg(e):Wg(e),interactive:Boolean(process.stdin.isTTY&&process.stderr.isTTY),sleep:(e)=>new Promise((t)=>setTimeout(t,e)),say:(e)=>{process.stderr.write(`${e}
79
+ `)},env:process.env,platform:process.platform,home:Fg(),cwd:process.cwd()}}function Gg(e){let t=No(e);try{return Ng(t)}catch{return t}}async function Oo(e,t,n){let r=new AbortController,o=setTimeout(()=>r.abort(),n);try{let i=await fetch(e,{...t,signal:r.signal});return{status:i.status,body:await i.text()}}catch{return}finally{clearTimeout(o)}}function fc(e){if(!e)return;try{return{status:e.status,body:JSON.parse(e.body)}}catch{return e}}async function Wg(e){let{createInterface:t}=await import("node:readline/promises"),n=t({input:process.stdin,output:process.stderr});try{return(await n.question(e)).trim()}finally{n.close()}}function Kg(e){return new Promise((t,n)=>{let r=process.stdin;process.stderr.write(e);let o="";r.setRawMode(!0),r.resume(),r.setEncoding("utf8");let i=(a)=>{r.setRawMode(!1),r.pause(),r.removeListener("data",s),process.stderr.write(`
80
+ `),a()},s=(a)=>{let u=Jg(o,a);if(o=u.value,u.end==="enter")i(()=>t(o.trim()));if(u.end==="cancel")i(()=>n(Error("Cancelled.")))};r.on("data",s)})}function Jg(e,t){let n=e;for(let r of t){if(r==="\r"||r===`
81
+ `)return{value:n,end:"enter"};if(r==="\x03")return{value:n,end:"cancel"};n=r===""||r==="\b"?n.slice(0,-1):n+r}return{value:n}}function Et(e,t){let n=t??e.env.NIMBLEBRAIN_HOME;return n===void 0?It(e):No(e.cwd,n)}function It(e){return No(e.cwd,pc(e.home,".nimblebrain-local"))}var Ve="npx nimblebrain";function me(e,t){let n=It(e);if(t===n&&Et(e)===n)return Ve;return`${Ve} --home ${Yg(t)}`}function Yg(e){return/^[A-Za-z0-9_./,:@%+=-]+$/.test(e)?e:`'${e.replaceAll("'","'\\''")}'`}function Po(e,t){return e.replaceAll(Ve,()=>t)}import{basename as tw,join as rt}from"node:path";import{join as Mo}from"node:path";var Fn={USAGE:"Run `npx nimblebrain --help` for the commands and flags.",DOCKER_MISSING:"Install Docker Desktop or Docker Engine (https://docs.docker.com/get-docker/), then run this again.",DOCKER_NOT_RUNNING:"Start Docker Desktop (or the Docker service), then run this again.",DOCKER_PERMISSION:"Let this user use Docker (https://docs.docker.com/engine/install/linux-postinstall/), sign in again, then run this again.",COMPOSE_MISSING:"Install Docker Compose v2 (https://docs.docker.com/compose/install/) or update Docker Desktop, then run this again.",ARCH_UNSUPPORTED:"NimbleBrain publishes no image for this CPU architecture.",LOW_MEMORY:"Give Docker at least 2 GB of memory in its settings, then run this again.",PORT_IN_USE:"Stop whatever holds the port, or pass --port with a free one.",NOT_INSTALLED:"Run `npx nimblebrain` to install it.",NOT_OURS:"This folder holds files the CLI did not write. Remove them yourself, or choose another --home.",INSTALL_INCOMPLETE:"Run `npx nimblebrain` to finish installing it, or `npx nimblebrain uninstall` to remove it.",NETWORK:"Check the network connection, then run the same command again.",HEALTH_TIMEOUT:"Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",AGENT_UNSUPPORTED:"Pass --agent claude-code, cursor, codex or none.",START_FAILED:"Run `npx nimblebrain logs` and look at the last error line, then run the command again; `npx nimblebrain` finishes an install whose first start did not.",HOME_NOT_SHARED:"Docker cannot read the install's folder. Share this folder with Docker, or move it into a folder Docker shares and pass that folder with --home, then run this again. To install somewhere else instead, run `npx nimblebrain uninstall` first; it deletes this install's data.",NEEDS_TERMINAL:"A person runs this in their own terminal; it asks for input no agent should give.",CANCELLED:"Nothing was changed. Run the command again to go ahead.",RUNTIME_UNSUPPORTED:"Pass a newer runtime with --runtime, or leave it out to install the newest release.",NOT_RUNNING:"Run `npx nimblebrain up`, then run this again.",TELEMETRY_LOCKED:"Nothing to change: DO_NOT_TRACK or the install's configuration decides telemetry here.",LOCAL_MODEL_UNREACHABLE:"Install Ollama (https://ollama.com/download) and start it, then run this again.",LOCAL_MODEL_MISSING:"Download the model with `ollama pull <model>`, or check that Ollama has disk space, then run this again.",LOCAL_MODEL_NO_TOOLS:"Choose a model with tool calling, such as gemma4:e4b; https://docs.nimblebrain.ai/config/local-models/ lists the ones run with NimbleBrain.",LOCAL_CONTEXT_SMALL:"Run `npx nimblebrain local-model` to prepare the model again with a 32k context window.",INTERRUPTED:"Run `npx nimblebrain status` to see what is in place, then run the same command again.",UPDATE_REQUIRED:"Run `npx nimblebrain update`; this install's NimbleBrain cannot reach servers on this machine yet.",WORKSPACE_NOT_FOUND:"Run `npx nimblebrain status` for the workspace ids, then pass one with --workspace.",SERVER_NOT_FOUND:"Run `npx nimblebrain mcp list` for the server names in this workspace.",DIRECT_URL_NOT_ALLOWED:"Adding a server by URL needs a local install made by `npx nimblebrain`; run `npx nimblebrain update`, or add the server to the instance's connector catalog.",URL_NOT_LOOPBACK:"Run the server on this machine and pass its localhost, 127.0.0.1 or [::1] URL, such as http://127.0.0.1:8000/mcp.",URL_INVALID:"Pass the server's full MCP URL, such as http://127.0.0.1:8000/mcp.",INVALID_SERVER_NAME:"Pass another name with --name: lowercase letters, digits and hyphens.",NAME_TAKEN:"Pass another name with --name, or remove the existing one with `npx nimblebrain mcp remove <serverName>`.",NAME_IS_CATALOG_ENTRY:"Pass another name with --name; this one belongs to a catalog connector.",REQUEST_FAILED:"Run `npx nimblebrain logs` and look at the last error line, then run this again.",AGENT_CLI_MISSING:"Install the agent's own CLI (Claude Code or Codex) and sign in to your subscription with it, then run this again.",AGENT_NOT_SIGNED_IN:"Sign the agent's CLI in to your Claude or ChatGPT subscription, then run this again.",AGENT_BILLS_API_KEY:"Sign the agent's CLI in to your Claude or ChatGPT subscription instead of an API key, then run this again.",HOST_LOOPBACK_UNREACHABLE:"Run NimbleBrain on your subscription from macOS for now. On Linux, NimbleBrain's container reaches this machine over the Docker bridge, not 127.0.0.1, and the agent worker listens on 127.0.0.1 only. `npx nimblebrain key` gives NimbleBrain a model key instead.",PLATFORM_UNSUPPORTED:"Run NimbleBrain on your subscription from macOS for now. `npx nimblebrain key` gives NimbleBrain a model key instead.",MODEL_KEY_MISSING:"Run `npx nimblebrain key` in your own terminal to enter a model key, then run this again.",AGENT_WORKER_FAILED:"Read agent-worker.log in the install's folder (its path is in log) for why the agent worker stopped, then run this again."},Xg={DOCKER_MISSING:{mac_brew:"Install Docker Desktop with `brew install --cask docker`, open it once from Applications, then run this again.",mac:"Install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/), open it once, then run this again."},DOCKER_NOT_RUNNING:{colima:"Start Colima with `colima start`, then run this again."},COMPOSE_MISSING:{brew:"Install Compose with `brew install docker-compose`, then run this again."},LOW_MEMORY:{colima:"Restart Colima with more memory: `colima stop && colima start --memory 4`, then run this again.",docker_desktop:"In Docker Desktop, open Settings > Resources, set Memory to at least 2 GB, apply, then run this again."},AGENT_CLI_MISSING:{claude:"Install or update Claude Code (https://claude.com/claude-code), run `claude` and sign in with your Claude account, then run this again.",codex:"Install or update Codex with `npm i -g @openai/codex`, run `codex login` and choose Sign in with ChatGPT, then run this again."},AGENT_NOT_SIGNED_IN:{claude:"Run `claude`, sign in with your Claude account, then run this again.",codex:"Run `codex login`, choose Sign in with ChatGPT, then run this again."},AGENT_BILLS_API_KEY:{claude:"Run `claude /login`, choose your Claude subscription, then run this again.",codex:"Run `codex logout`, then `codex login` and choose Sign in with ChatGPT, then run this again."},LOCAL_MODEL_UNREACHABLE:{brew_install:"Install Ollama with `brew install ollama`, then run this again; it offers to start Ollama for you.",app:"Open the Ollama app, then run this again.",brew:"Run `brew services start ollama` (it then also starts at login), then run this again.",systemd:"Run `sudo systemctl start ollama`, then run this again.",serve:"Run `ollama serve` in another terminal, then run this again."}};class x extends Error{code;fix;detail;variant;constructor(e,t,n={},r){super(t??e);this.code=e;let o=Xg[e];this.fix=r&&o?.[r]||Fn[e],this.variant=r,this.detail=n}with(e,t=this.message){return new x(this.code,t,{...this.detail,...e},this.variant)}}function Vn(e){return{...e.detail,ok:!1,error:e.code,message:e.message,fix:e.fix}}function hc(e){return e.ok?0:Lo(e.error)}function Lo(e){return e==="USAGE"?2:1}var Do=100,gc=10;function jo(e,t){return[...new Set([It(e),Et(e)])].filter((n)=>n!==t)}async function Qg(e,t){let n=[];for(let r of jo(e,t)){let o=wc(await e.readText(Mo(r,"install.json")),"port");if(o===void 0)continue;let i=await e.readText(Mo(r,".env"))??"",s=Number(i.match(/^NB_AGENT_RUNTIME_URL=https?:\/\/[^/]+:(\d+)\//m)?.[1]),a=wc(await e.readText(Mo(r,"agent-worker.json")),"port")??(Number.isInteger(s)&&s>0?s:void 0);n.push({home:r,web:o,worker:a})}return n}function wc(e,t){if(e===void 0)return;try{let n=JSON.parse(e)?.[t];return typeof n==="number"&&Number.isInteger(n)&&n>0?n:void 0}catch{return}}async function ew(e,t,n,r){let o=n.find((s)=>s.web===t);if(o)return{held_by:"nimblebrain",home:o.home};let i=n.find((s)=>s.worker===t);if(i)return{held_by:"agent_worker",home:i.home};if(r==="web"){let s=await e.getText(`http://127.0.0.1:${t}/`,1500);if(s?.status===200&&/<title>\s*NimbleBrain/i.test(s.body))return{held_by:"nimblebrain",home:null}}return{held_by:"other",home:null}}async function qn(e,t,n,r){let o=await Qg(e,t),i=new Set(o.flatMap((a)=>[a.web,a.worker]));if(!i.has(n)&&await e.portFree(n))return;for(let a=1;a<gc;a++){let u=n+a*Do;if(u>65535)break;if(i.has(u)||!await e.portFree(u))continue;return{from:n,to:u,...await ew(e,n,o,r)}}let s=Math.min(n+(gc-1)*Do,65535);throw new x("PORT_IN_USE",`Port ${n} is in use, and so is every port tried after it (every ${Do} up to ${s}).`)}function _c(e,t){return t.startsWith(`${e.home}/`)?`~${t.slice(e.home.length)}`:t}function Uo(e,t){if(t.held_by==="nimblebrain")return t.home?`your NimbleBrain at ${_c(e,t.home)}`:"another NimbleBrain";if(t.held_by==="agent_worker"&&t.home)return`the agent worker of your NimbleBrain at ${_c(e,t.home)}`;return"another program"}function Hn(e,t,n){return`Port ${t.from} is in use (by ${Uo(e,t)}), so ${n} uses ${t.to}.`}var ot="nimblebrain";function Yt(e){return e.serverName??ot}async function yc(e,t,n){if(t===It(e))return ot;let r=tw(t).toLowerCase().replace(/^\.+/,"").replace(/^nimblebrain-?/,"").replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"");if(!r)return n;let o=`${ot}-${r}`,i=new Set;for(let s of jo(e,t)){let a=await e.readText(rt(s,"install.json"));if(a===void 0)continue;try{let u=JSON.parse(a);i.add(typeof u?.serverName==="string"?u.serverName:ot)}catch{}}return i.has(o)?n:o}async function zc(e,t,n,r){let o=r.name;if(t==="none")return{connected:null,name:o};try{if(o!==ot&&await nw(e,t,o))o=r.fallback;let i=bc(t,o,n);if(t==="claude-code")return await e.exec("claude",["mcp","remove","-s","user",o]),(await e.exec("claude",["mcp","add","--transport","http","-s","user",o,n])).code===0?{connected:t,name:o}:{connected:null,name:o,manual:i};if(t==="codex")return await e.exec("codex",["mcp","remove",o]),(await e.exec("codex",["mcp","add",o,"--url",n])).code===0?{connected:t,name:o}:{connected:null,name:o,manual:i};return await rw(e,o,n),{connected:t,name:o}}catch{return{connected:null,name:o,manual:bc(t,o,n)}}}async function nw(e,t,n){if(t==="claude-code")return(await e.exec("claude",["mcp","get",n])).code===0;if(t==="codex")return(await e.exec("codex",["mcp","get",n])).code===0;if(t==="cursor")return n in((await Bo(e)).mcpServers??{});return!1}async function xc(e,t,n){if(t==="claude-code")await e.exec("claude",["mcp","remove","-s","user",n]);if(t==="codex")await e.exec("codex",["mcp","remove",n]);if(t!=="cursor")return;try{let r=await Bo(e);if(!r.mcpServers||!(n in r.mcpServers))return;delete r.mcpServers[n],await e.writeText(Zo(e),`${JSON.stringify(r,null,2)}
82
+ `,384)}catch{}}var Zo=(e)=>rt(e.home,".cursor","mcp.json");async function Bo(e){let t=await e.readText(Zo(e));return t?JSON.parse(t):{}}async function rw(e,t,n){let r=await Bo(e);r.mcpServers={...r.mcpServers??{},[t]:{url:n}},await e.writeText(Zo(e),`${JSON.stringify(r,null,2)}
83
+ `,384)}function bc(e,t,n){if(e==="claude-code")return`claude mcp add --transport http -s user ${t} ${n}`;if(e==="codex")return`codex mcp add ${t} --url ${n}`;return`Add to ~/.cursor/mcp.json: {"mcpServers":{"${t}":{"url":"${n}"}}}`}async function kc(e,t){if(t==="none")return;await e.exec("npx",["-y","skills","add","nimblebraininc/skills","--skill",Gn,"--agent",t,"-g","-y"],{timeoutMs:120000})}async function Sc(e,t){if(!await Fo(e,t))return"not_installed";try{let n=await e.exec("npx",["-y","skills","update",Gn,"-g","-y"],{timeoutMs:120000});if(n.code!==0)return"failed";return/Updated \d+ skill/.test(n.stdout)?"updated":"unchanged"}catch{return"failed"}}var Gn="nimblebrain";function ow(e,t){if(t==="claude-code")return rt(e.env.CLAUDE_CONFIG_DIR?.trim()||rt(e.home,".claude"),"skills");if(t==="codex")return rt(e.home,".agents","skills");if(t==="cursor")return rt(e.home,".cursor","skills");return}async function Fo(e,t){let n=ow(e,t);if(!n)return null;return await e.readText(rt(n,Gn,"SKILL.md"))===void 0?null:Gn}import{parseArgs as hw}from"node:util";var qe="http://127.0.0.1:11434",iw="http://host.docker.internal:11434/v1",it="gemma4:e4b",Wn=32768,sw=3600000,aw=30000,cw=120000,$c=["NB_LOCAL_MODEL_URL","NB_LOCAL_MODEL","NB_LOCAL_MODEL_CONTEXT"];function Ct(e){return e.includes("NB_LOCAL_MODEL_URL")}function uw(e){return`nimblebrain-${e.replace(/[^A-Za-z0-9._-]+/g,"-")}`}function le(e){let n=e.split(`
84
+ `).find((r)=>r.startsWith("NB_LOCAL_MODEL="))?.slice(15).trim();return n?n:void 0}async function Vo(e,t){let n=await e.postJson(`${qe}/api/show`,{model:t});return n?.status===200?n.body:void 0}function lw(e){let t=e?.match(/^num_ctx\s+(\d+)/m);return t?Number(t[1]):void 0}async function Kn(e){let t=await e.getJson(`${qe}/api/version`),n=t?.body?.version;return t?.status===200&&typeof n==="string"?n:void 0}var dw=["/etc/systemd/system/ollama.service","/usr/lib/systemd/system/ollama.service"];async function fw(e){let t=["/Applications",`${e.home}/Applications`].map((r)=>`${r}/Ollama.app/Contents/Info.plist`);if(e.platform==="darwin"&&await vc(e,t))return{kind:"app",start:["open","-g","-a","Ollama"],fix:"app"};if(e.platform==="linux"&&await vc(e,dw))return{kind:"systemd",start:["systemctl","start","--no-ask-password","ollama"],fix:"systemd"};let n=await e.exec("brew",["list","--versions","ollama"]);if(n.code===0&&n.stdout.trim())return{kind:"brew",start:["brew","services","start","ollama"],fix:"brew"};if(await e.which("ollama"))return{kind:"binary",fix:"serve"};return{kind:"none",fix:n.missing?void 0:"brew_install"}}async function vc(e,t){for(let n of t)if(await e.readText(n)!==void 0)return!0;return!1}async function st(e,t){let n=await Kn(e);if(n)return{version:n};let r=await fw(e),o=(d,p={})=>new x("LOCAL_MODEL_UNREACHABLE",d,{check:"ollama",ollama:r.kind,...p},r.fix);if(!r.start)throw o(r.kind==="none"?`Ollama does not answer at ${qe}, and it does not look installed.`:`Ollama does not answer at ${qe}.`);let i=r.start.join(" ");if(!await t(i))throw o(`Ollama is installed but not running at ${qe}; it was not started.`);e.say(`Starting Ollama: ${i}`);let[s="",...a]=r.start,u=await e.exec(s,a,{timeoutMs:60000});if(u.code!==0||u.missing){let d=u.stderr.trim().split(`
85
+ `)[0];throw o(`\`${i}\` did not start Ollama${d?`: ${d}`:"."}`)}for(let d=0;d<aw;d+=1000){await e.sleep(1000);let p=await Kn(e);if(p){if(e.say(`Ollama ${p} is running.`),e.platform==="linux")e.say("On Linux, NimbleBrain's container reaches Ollama only when it listens beyond 127.0.0.1 (OLLAMA_HOST=0.0.0.0).");return{version:p,started:i}}}throw o(`Ollama was started with \`${i}\` but did not answer at ${qe} within 30 seconds.`,{ollama_started:i})}async function Ec(e,t,n){let{started:r}=await st(e,n.start);try{return{values:await pw(e,t,n.pull),started:r}}catch(o){if(o instanceof x&&r)throw o.with({ollama_started:r});throw o}}async function pw(e,t,n){let r=await Vo(e,t);if(!r){if(!await n(t))throw new x("LOCAL_MODEL_MISSING",`Ollama has no model "${t}".`,{check:"model"});if(e.say(`Downloading ${t} with Ollama. A model is several GB; this can take a while.`),r=(await e.postJson(`${qe}/api/pull`,{model:t,stream:!1},sw))?.status===200?await Vo(e,t):void 0,!r)throw new x("LOCAL_MODEL_MISSING",`Ollama could not download "${t}".`,{check:"model"})}if(!r.capabilities?.includes("tools"))throw new x("LOCAL_MODEL_NO_TOOLS",`${t} does not support tool calling, which NimbleBrain's agents need.`,{check:"tools"});let o=uw(t);if((await e.postJson(`${qe}/api/create`,{model:o,from:t,parameters:{num_ctx:Wn},stream:!1},cw))?.status!==200)throw new x("LOCAL_MODEL_MISSING",`Ollama could not prepare ${o} from ${t}.`,{check:"model"});return{NB_LOCAL_MODEL_URL:iw,NB_LOCAL_MODEL:o,NB_LOCAL_MODEL_CONTEXT:String(Wn)}}async function Ic(e,t,n){let r=[],{version:o,started:i}=await st(e,n).catch((d)=>{if(!(d instanceof x))throw d;throw r.push({check:"ollama",ok:!1,detail:d.message}),d.with({check:"ollama",checks:r})});r.push({check:"ollama",ok:!0,detail:i?`${o} (started: ${i})`:o});let s=await Vo(e,t),a=(d,p,g)=>{throw r.push({check:d,ok:!1,detail:g}),new x(p,g,{check:d,checks:r,ollama_started:i})};if(!s)a("model","LOCAL_MODEL_MISSING",`Ollama has no model "${t}".`);if(r.push({check:"model",ok:!0,detail:t}),!s?.capabilities?.includes("tools"))a("tools","LOCAL_MODEL_NO_TOOLS",`${t} does not support tool calling.`);r.push({check:"tools",ok:!0,detail:"tool calling"});let u=lw(s?.parameters);if(u===void 0||u<Wn)a("context","LOCAL_CONTEXT_SMALL",`${t} has a context window of ${u??"Ollama's default"}, below ${Wn}.`);return r.push({check:"context",ok:!0,detail:`${u} tokens`}),{checks:r,started:i}}Re();var Yn={init:{args:[],description:"Check this machine, start NimbleBrain, connect your coding agent (default)"},doctor:{args:[],description:"Check Docker, Compose, architecture, memory and the port; installs nothing"},status:{args:[],description:"Version, health, URL and each workspace's MCP URL"},open:{args:[],description:"Open NimbleBrain's web UI in the default browser"},key:{args:[],description:"Enter the model key at a hidden prompt"},"local-model":{args:["[model]"],description:`Prepare a model served by Ollama for NimbleBrain's agents (default ${it})`},use:{args:["[claude|codex|api|local]","[model]"],description:"Choose what runs NimbleBrain's agents: claude (your Claude subscription), codex (your ChatGPT plan), api (an API key) or local (an Ollama model); asks when none is named"},telemetry:{args:["[on|off|status]"],description:"Whether this install sends anonymous usage data"},up:{args:[],description:"Start NimbleBrain"},down:{args:[],description:"Stop NimbleBrain; data survives down"},logs:{args:[],description:"Recent runtime log lines"},update:{args:[],description:"Move to the newest release, keeping data, and refresh the connected agent's nimblebrain skill"},uninstall:{args:[],description:"Remove NimbleBrain and its data"},mcp:{args:["<add|list|remove>"],description:"MCP servers in development; see mcp add, list and remove"}},gw=Object.keys(Yn),ww=["on","off","status"],At=["claude-code","cursor","codex","none"],He=["claude","codex","api","local"],Qt=`${He.slice(0,-1).join(", ")} or ${He.at(-1)}`,Rt=27246,qo={json:{type:"boolean",description:"One JSON object on stdout; progress and notices go to stderr"},yes:{type:"boolean",short:"y",description:"Take every default; implied when no terminal is attached"},agent:{type:"string",takes:"name",description:`The coding agent to connect: ${At.slice(0,-1).join(", ")} or ${At.at(-1)}`,commands:["init"]},port:{type:"string",takes:"n",description:`Local port (default ${Rt}, or on a new install the next free port 100 on when that one is in use; for doctor, the install's own port; for use, the agent worker's, default 27290 for claude and 27291 for codex, moved the same way). A port given here is never moved: in use, it is PORT_IN_USE`,commands:["init","doctor","use"]},home:{type:"string",takes:"dir",description:"Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); each home is a separate install"},provider:{type:"string",takes:"name",description:"The model provider for key (default anthropic); the installed release decides which it takes, and key lists them",commands:["key"]},use:{type:"string",takes:He.join("|"),description:"What runs NimbleBrain's agents, as use takes it; without it (or --local-model), init asks a person, or leaves it unchosen and returns the question in model_source.ask",commands:["init"]},model:{type:"string",takes:"id",description:"The model your subscription's turns run on, for use claude|codex and init --use claude|codex: for claude sonnet (default), opus, haiku or a full model id; for codex a model your plan offers (default Codex's own)",commands:["init","use"]},"local-model":{type:"string",takes:"model",description:"Run on this Ollama model (implies --use local)",commands:["init"]},runtime:{type:"string",takes:"tag",description:"The NimbleBrain release to install or update to (default the newest)",commands:["init","update"]},"no-open":{type:"boolean",description:"Do not open the web UI in the browser when init finishes",commands:["init"]},telemetry:{type:"string",takes:"on|off",description:"The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided",commands:["init"]},name:{type:"string",takes:"name",description:"The server name (default from the server's card, else its URL)",commands:["mcp add"]},workspace:{type:"string",takes:"id",description:"The workspace (default the one init connected, the first in status)",commands:["mcp add","mcp list","mcp remove"]},help:{type:"boolean",short:"h",description:"The commands and flags; with --json, these, each command's answer and every error code as JSON"},version:{type:"boolean",short:"v",description:"This CLI's version"}},_w=Object.fromEntries(Object.entries(qo).map(([e,t])=>[e,t.short?{type:t.type,short:t.short}:{type:t.type}]));function Ho(e){let{values:t,positionals:n}=Sw(e),r=t.json===!0,o=t.port===void 0?void 0:Number(t.port);if(o!==void 0&&(!Number.isInteger(o)||o<1||o>65535))throw new x("USAGE",`--port must be a port number, not "${t.port}".`);let i;if(t.agent!==void 0){if(!At.includes(t.agent))throw new x("AGENT_UNSUPPORTED",`Unknown agent "${t.agent}".`);i=t.agent}let s=zw(t.telemetry),a=bw(t.use,t["local-model"]),u={json:r,yes:t.yes===!0,agent:i,port:o,home:t.home,provider:t.provider,localModel:t["local-model"],use:a,model:yw(t.model),runtime:t.runtime,telemetry:s,noOpen:t["no-open"]===!0,name:t.name,workspace:t.workspace};if(t.help)return{kind:"help",flags:u};if(t.version)return{kind:"version",flags:u};let d=n[0]??"init";if(d==="help")return{kind:"help",flags:u};return{kind:"run",command:xw(d,n),flags:u,arg:n[1],operand:n[2]}}function bw(e,t){if(e===void 0)return t===void 0?void 0:"local";if(!He.includes(e))throw new x("USAGE",`--use must be ${Qt}, not "${e}".`);if(t!==void 0&&e!=="local")throw new x("USAGE",`--local-model runs on a local model, so it takes --use local, not "${e}".`);return e}function yw(e){if(e===void 0||Tc.test(e))return e;throw new x("USAGE",`--model takes a model name such as sonnet, opus or haiku, or a full model id, not "${e}".`)}function zw(e){if(e===void 0||e==="on"||e==="off")return e;throw new x("USAGE",`--telemetry must be on or off, not "${e}".`)}var Xt={add:{operand:"url",description:"Add an MCP server you run on this machine to a workspace"},list:{operand:null,description:"The servers in a workspace"},remove:{operand:"serverName",description:"Remove a server from a workspace"}};function xw(e,t){if(!gw.includes(e))throw new x("USAGE",`Unknown command "${e}".`);if(e==="mcp")return kw(t);let n=e==="use"?3:e==="telemetry"||e==="local-model"?2:1;if(t.length>n)throw new x("USAGE",`Unexpected argument "${t[n]}".`);let r=t[1];if(e==="telemetry"&&r!==void 0&&!ww.includes(r))throw new x("USAGE",`telemetry takes on, off or status, not "${r}".`);return e}function kw(e){let t=e[1];if(t===void 0||!Object.hasOwn(Xt,t))throw new x("USAGE",`mcp takes add <url>, list or remove <serverName>${t===void 0?"":`, not "${t}"`}.`);let{operand:n}=Xt[t],r=n===null?2:3;if(e.length>r)throw new x("USAGE",`Unexpected argument "${e[r]}".`);if(n!==null&&e[2]===void 0)throw new x("USAGE",`mcp ${t} needs a ${n}.`);return"mcp"}function Sw(e){try{return hw({args:e,options:_w,allowPositionals:!0,strict:!0})}catch(t){throw new x("USAGE",t instanceof Error?t.message:String(t))}}function Go(e){return e.includes("--json")}import{randomBytes as vw}from"node:crypto";import{basename as $w,join as Xn}from"node:path";function Rc(e){let t=$w(e).toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/^[^a-z0-9]+/,"").replace(/[^a-z0-9]+$/,"");return`${!t?"nimblebrain":t.startsWith("nimblebrain")?t:`nimblebrain-${t}`}-${vw(3).toString("hex")}`}var Ew="https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";async function Wo(e,t){let n=await e.getText(`${Ew}/${t}/docker-compose.yml`,15000);if(!n)throw new x("NETWORK",`Could not download the Compose file for ${t}.`);if(n.status===404)throw new x("RUNTIME_UNSUPPORTED",`NimbleBrain ${t} has no Compose file to install.`);if(n.status!==200)throw new x("NETWORK",`Downloading the Compose file for ${t} answered ${n.status}.`);if(!n.body.includes("${NIMBLEBRAIN_TAG")||!n.body.includes("NIMBLEBRAIN_WEB_PORT"))throw new x("RUNTIME_UNSUPPORTED",`NimbleBrain ${t}'s Compose file does not take its image tag and port from .env.`);return n.body}function ze(e){return[...new Set([...e.matchAll(/\b([A-Z][A-Z0-9_]*_API_KEY)=\$\{\1\b/g)].map((t)=>t[1]??""))]}function Oc(e){return e.includes("NB_TELEMETRY_CONSENT")}function Qn(e){return e.includes("NB_HOST_LOOPBACK")}function Ko(e){return e.includes("NB_AGENT_RUNTIME_URL")}function Jo(e){return Object.fromEntries(ze(e).map((t)=>[t.replace(/_API_KEY$/,"").replace(/_GENERATIVE_AI$/,"").toLowerCase(),t]))}function Iw(e,t){let n={...e.env};for(let r of[...t,"NIMBLEBRAIN_TAG","NIMBLEBRAIN_WEB_PORT","COMPOSE_PROJECT_NAME","NB_TELEMETRY_KEY","NB_TELEMETRY_ID","NB_TELEMETRY_CONSENT","NB_LOCAL_MODEL_URL","NB_LOCAL_MODEL","NB_LOCAL_MODEL_CONTEXT","NB_AGENT_RUNTIME","NB_AGENT_RUNTIME_URL"])delete n[r];return n}var Nc={cmd:"docker",args:["compose"]},Ac=new WeakMap;function Yo(e){let t=Ac.get(e);if(!t)t=Cw(e),Ac.set(e,t);return t}async function Cw(e){for(let t of[Nc,{cmd:"docker-compose",args:[]}]){let n=await e.exec(t.cmd,[...t.args,"version","--short"]);if(n.code===0&&Tw(n.stdout)>=2)return{...t,version:n.stdout.trim()}}return}function Tw(e){return Number.parseInt(e.trim().replace(/^v/,""),10)}async function Aw(e,t,n){let r=await Yo(e)??Nc;return e.exec(r.cmd,[...r.args,...t],n)}async function ut(e,t,n,r=120000){let o=ze(await e.readText(R(t).compose)??"");return Aw(e,n,{cwd:t,env:Iw(e,o),timeoutMs:r})}async function en(e,t){return await e.readText(R(t).env)!==void 0}async function er(e,t){if(!await en(e,t))return!1;let n=await ut(e,t,["ps","-q"],30000);return n.code===0&&n.stdout.trim()!==""}function Xo(e){return/\/\.colima\/default\//.test(e)?"colima":void 0}function Ot(e){let t=`${e.stderr}
84
86
  ${e.stdout}`,n=t.trim().split(`
85
- `).filter((r)=>r.trim()).pop()??"Compose failed.";if(/cannot connect to the docker daemon|failed to connect to the docker api/i.test(t))return new x("DOCKER_NOT_RUNNING",n,{},Uo(t));if(/no such host|timeout|TLS handshake|connection refused|network is unreachable/i.test(t))return new x("NETWORK",n);if(/port is already allocated|address already in use/i.test(t))return new x("PORT_IN_USE",n);if(/is not shared from the host/i.test(t))return new x("HOME_NOT_SHARED",n);return new x("START_FAILED",n)}function Re(e,t){let n=e===""?[]:e.replace(/\n$/,"").split(`
87
+ `).filter((r)=>r.trim()).pop()??"Compose failed.";if(/cannot connect to the docker daemon|failed to connect to the docker api/i.test(t))return new x("DOCKER_NOT_RUNNING",n,{},Xo(t));if(/no such host|timeout|TLS handshake|connection refused|network is unreachable/i.test(t))return new x("NETWORK",n);if(/port is already allocated|address already in use/i.test(t))return new x("PORT_IN_USE",n);if(/is not shared from the host/i.test(t))return new x("HOME_NOT_SHARED",n);return new x("START_FAILED",n)}function Oe(e,t){let n=e===""?[]:e.replace(/\n$/,"").split(`
86
88
  `),r=new Set,o=n.map((i)=>{let s=i.match(/^([A-Z][A-Z0-9_]*)=/)?.[1];if(s&&s in t)return r.add(s),`${s}=${t[s]}`;return i});for(let[i,s]of Object.entries(t))if(!r.has(i))o.push(`${i}=${s}`);return`${o.join(`
87
89
  `)}
88
- `}function ot(e,t){let n=Object.entries(Mo(t)).find(([,r])=>Oe(e,[r]));return n?n[0]:null}function Oe(e,t){return t.some((n)=>new RegExp(`^${n}=\\S`,"m").test(e))}var R=(e)=>({compose:Bn(e,"docker-compose.yml"),env:Bn(e,".env"),instance:Bn(e,"instance.json"),install:Bn(e,"install.json")}),dc=`${JSON.stringify({auth:{adapter:"dev"}},null,2)}
89
- `;var nw=["x86_64","amd64","aarch64","arm64"],rw=1879048192;async function qn(e,t,n=!1){let r=ow();await iw(e,r);let o=await sw(e,r);return await aw(e,r),cw(o.arch,r),uw(o,r),await lw(e,t,n,r),{ok:!0,checks:r.checks,arch:o.arch}}function ow(){let e=[];return{checks:e,pass:(t,n)=>{e.push({check:t,ok:!0,detail:n})},fail:(t,n,r,o)=>{throw e.push({check:t,ok:!1,detail:r}),new x(n,r,{check:t,checks:e},o)}}}async function iw(e,t){let n=await e.exec("docker",["--version"]);if(n.missing){let r=e.platform!=="darwin"?void 0:await e.which("brew")?"mac_brew":"mac";t.fail("docker","DOCKER_MISSING","Docker is not installed.",r)}t.pass("docker",n.stdout.trim())}async function sw(e,t){let n=await e.exec("docker",["info","--format","{{json .}}"]);if(n.code!==0){if(/permission denied/i.test(`${n.stderr}
90
- ${n.stdout}`))t.fail("docker-daemon","DOCKER_PERMISSION","This user may not use Docker.");t.fail("docker-daemon","DOCKER_NOT_RUNNING","Docker is installed but not running.",Uo(n.stderr))}return t.pass("docker-daemon","running"),dw(n.stdout)}async function aw(e,t){let n=await jo(e);if(!n){let r=e.platform==="darwin"&&await e.which("brew")?"brew":void 0;t.fail("compose","COMPOSE_MISSING","Docker Compose v2 is not available.",r)}t.pass("compose",n.cmd==="docker"?n.version:`${n.version} (${n.cmd})`)}function cw(e,t){if(!nw.includes(e))t.fail("arch","ARCH_UNSUPPORTED",`No NimbleBrain image is published for ${e||"this architecture"}.`);t.pass("arch",e)}function uw({memory:e,kind:t},n){if(e>0&&e<rw)n.fail("memory","LOW_MEMORY",`Docker has ${pc(e)} of memory; NimbleBrain needs 2 GB.`,t);n.pass("memory",e>0?pc(e):"unknown")}async function lw(e,t,n,r){if(n)return r.pass("port",`${t} (this install)`);if(!await e.portFree(t))r.fail("port","PORT_IN_USE",`Port ${t} is in use.`);r.pass("port",String(t))}function dw(e){try{let t=JSON.parse(e);return{arch:typeof t.Architecture==="string"?t.Architecture:"",memory:typeof t.MemTotal==="number"?t.MemTotal:0,kind:t.OperatingSystem==="Docker Desktop"?"docker_desktop":t.Name==="colima"?"colima":void 0}}catch{return{arch:"",memory:0}}}function pc(e){return`${(e/1073741824).toFixed(1)} GB`}var Kt={version:"The NimbleBrain runtime release installed, without the leading v",phase:"starting until the install's first start answers health, else ready; npx nimblebrain finishes a starting install, and only down, logs, uninstall, status and doctor act on one",cli_version:"This CLI's version; it moves independently of the runtime",health:"ok when NimbleBrain answers, else down",url:"Where the web UI and API answer, on 127.0.0.1",workspaces:"Each workspace as {id, name, mcp}, mcp being its MCP URL; empty while down",agent:"{connected, skill}: the coding agent init connected (or null), and the nimblebrain skill's name when that agent has it (else null)",model_key:"set or missing: whether the install's .env holds a model key (never the key)",host_loopback:"Whether this release can reach a server on this machine; mcp add needs it, update brings it",local_model:"The Ollama model saved for NimbleBrain's agents (nimblebrain-<model>), or null",model_source:"{source, label}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet), and that as a person reads it, such as your Claude Max subscription through Claude Code. A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget",agent_runtime:"{name, worker}: the runtime NimbleBrain's agents run on (native, claude-code or codex), and the agent worker that serves it as {running, pid, url, log, login_item} (null for native): whether it answers /healthz, its process id while it runs, its ACP URL on 127.0.0.1, its log file, and the macOS LaunchAgent that starts it at login and again after a crash (null when none is installed, as after down)",telemetry:"{state, locked?, ask?, set?}: on, off or undecided; locked says why no one can change it here; ask and set, only while undecided, are the question to pass to the person and the command that answers it",updates:"{cli?, runtime?}, each {current, latest}: what the last cached lookup found; absent when nothing is known or the check is off"};var Hn={init:{...Kt,model_source:"{source, label}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet), and that as a person reads it, such as your Claude Max subscription through Claude Code. A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget. When nothing runs them and no person was asked (--yes, --json or no terminal, without --use), it also carries {ask, options, default, set}: the question to pass to the person, each source as {source, label, available, detected, note} (available: it can be chosen here; detected: signed in, a key saved, or Ollama answering), the one to suggest, and the command that answers it",already:"true when an install was already here; it was reported, not changed",manual:"The settings to add to the coding agent by hand, when connecting it failed",opened:"Whether the browser opened, when init tried (a new install, a person at a terminal)",ollama_started:"The command that started Ollama, when this run started it"},doctor:{checks:"Each check run, in order, as {check, ok, detail}",arch:"The CPU architecture Docker reports",ollama_started:"The command that started Ollama, when this run started it; on a local model only"},status:Kt,open:{url:"The web UI's URL, to open by hand when opened is false",opened:"Whether a browser was started"},key:{provider:"The provider the key was entered for",model_key:"set"},"local-model":{local_model:"The model NimbleBrain's agents now run on (nimblebrain-<model>)",ollama_started:"The command that started Ollama, when this run started it"},telemetry:{telemetry:Kt.telemetry},use:{model_source:"{source, label}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet), and that as a person reads it, such as your Claude Max subscription through Claude Code. A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget",agent_runtime:"{name, worker}: the runtime NimbleBrain's agents run on (native, claude-code or codex), and the agent worker that serves it as {running, pid, url, log, login_item} (null for native): whether it answers /healthz, its process id while it runs, its ACP URL on 127.0.0.1, its log file, and the macOS LaunchAgent that starts it at login and again after a crash (null when none is installed, as after down)",billed_to:"Who pays for each turn, from the agent CLI's own sign-in, such as your Claude Max subscription; for claude and codex only",tools:"What the agent CLI may call during a turn: your workspace's tools, and for Codex its read-only shell; for claude and codex only",provider:"The provider whose key is saved; for api only",local_model:"The model NimbleBrain's agents now run on (nimblebrain-<model>); for local only",ollama_started:"The command that started Ollama, when this run started it; for local only"},up:{...Kt,ollama_started:"The command that started Ollama, when this run started it"},down:{health:"down"},logs:{lines:"The runtime's last log lines, up to 100"},update:{...Kt,already:"true when the install was already on that release",from:"The release moved from, as vX.Y.Z, when it moved",skill_update:"What happened to the connected agent's nimblebrain skill: updated, unchanged, not_installed or failed; absent with no agent"},uninstall:{removed:"true"},"mcp add":{serverName:"The name the server was added under",url:"The URL as given",dialed:"Where NimbleBrain, inside Docker, connects to it",placements:"Where the server's UI appears, from its Server Card",wsId:"The workspace it was added to",warning:"Why the server is not connected yet (it was added anyway), when it is not",notice:"Anything else NimbleBrain says about the server, when it says something"},"mcp list":{wsId:"The workspace listed",servers:"Each server as {serverName, displayName?, url?, state?, status?, statusReason?, toolCount?}"},"mcp remove":{serverName:"The server removed",wsId:"The workspace it was removed from"},help:{cli_version:"This CLI's version",commands:"Each command as {name, args, description, answer}",flags:"Each flag as {name, short?, takes, description, commands?}",errors:"Each error code as {code, fix, exit}"}};var pw={name:"help",args:[],description:"These commands and flags; with --json, these, each command's answer and every error code as JSON",answer:{...Hn.help}};function fc(){return[...Object.keys(Zn).flatMap((t)=>{if(t==="mcp")return Object.keys(Ht).map((r)=>{let o=Ht[r];return{name:`mcp ${r}`,args:o.operand?[`<${o.operand}>`]:[],description:o.description,answer:{...Hn[`mcp ${r}`]}}});let n=Zn[t];return[{name:t,args:[...n.args],description:n.description,answer:{...Hn[t]}}]}),pw]}function mc(){return Object.entries(Oo).map(([e,t])=>{let n={name:`--${e}`,takes:"takes"in t?t.takes:null,description:t.description};if("short"in t)n.short=`-${t.short}`;if("commands"in t)n.commands=[...t.commands];return n})}function fw(){return Object.keys(Dn).map((e)=>({code:e,fix:Dn[e],exit:Ao(e)}))}function hc(e){return{ok:!0,cli_version:e,commands:fc(),flags:mc(),errors:fw()}}function gc(e){let t=fc().map((i)=>[[i.name,...i.args].join(" "),i.description]),n=mc().map((i)=>[[i.takes?`${i.name} <${i.takes}>`:i.name,i.short].filter(Boolean).join(", "),i.commands?`${i.description}; for ${i.commands.join(", ")}`:i.description]),r=Math.max(...[...t,...n].map(([i])=>i.length))+2,o=([i,s])=>` ${i.padEnd(r)}${s}`;return[`nimblebrain ${e}: install and run NimbleBrain on this machine`,"","Usage: npx nimblebrain [command] [flags]","","Commands:",...t.map(o),"","Flags:",...n.map(o),"","What each command answers, and every error code and its fix: npx nimblebrain help --json",""].join(`
91
- `)}import{join as Xn}from"node:path";import{join as mw}from"node:path";var hw="ai.nimblebrain.agent-worker";function Gn(e,t){let n=`${hw}.${t}`;return{label:n,path:mw(e.home,"Library","LaunchAgents",`${n}.plist`)}}var gw=["PATH","HOME","LANG","CLAUDE_CONFIG_DIR","CODEX_HOME"];function wc(e,t,n,r){let o=gw.filter((i)=>r[i]).map((i)=>` <key>${i}</key>
92
- <string>${Jt(r[i]??"")}</string>`);return`<?xml version="1.0" encoding="UTF-8"?>
90
+ `}function lt(e,t){let n=Object.entries(Jo(t)).find(([,r])=>Ne(e,[r]));return n?n[0]:null}function Ne(e,t){return t.some((n)=>new RegExp(`^${n}=\\S`,"m").test(e))}var R=(e)=>({compose:Xn(e,"docker-compose.yml"),env:Xn(e,".env"),instance:Xn(e,"instance.json"),install:Xn(e,"install.json")}),Pc=`${JSON.stringify({auth:{adapter:"dev"}},null,2)}
91
+ `;var Rw=["x86_64","amd64","aarch64","arm64"],Ow=1879048192;async function tr(e,t,n=!1,r){let o=Nw();await Pw(e,o);let i=await Lw(e,o);await Mw(e,o),Dw(i.arch,o),jw(i,o);let s=await Uw(e,t,n,r,o);return{ok:!0,checks:o.checks,arch:i.arch,...s?{port_moved:s}:{}}}function Nw(){let e=[];return{checks:e,pass:(t,n)=>{e.push({check:t,ok:!0,detail:n})},fail:(t,n,r,o)=>{throw e.push({check:t,ok:!1,detail:r}),new x(n,r,{check:t,checks:e},o)}}}async function Pw(e,t){let n=await e.exec("docker",["--version"]);if(n.missing){let r=e.platform!=="darwin"?void 0:await e.which("brew")?"mac_brew":"mac";t.fail("docker","DOCKER_MISSING","Docker is not installed.",r)}t.pass("docker",n.stdout.trim())}async function Lw(e,t){let n=await e.exec("docker",["info","--format","{{json .}}"]);if(n.code!==0){if(/permission denied/i.test(`${n.stderr}
92
+ ${n.stdout}`))t.fail("docker-daemon","DOCKER_PERMISSION","This user may not use Docker.");t.fail("docker-daemon","DOCKER_NOT_RUNNING","Docker is installed but not running.",Xo(n.stderr))}return t.pass("docker-daemon","running"),Zw(n.stdout)}async function Mw(e,t){let n=await Yo(e);if(!n){let r=e.platform==="darwin"&&await e.which("brew")?"brew":void 0;t.fail("compose","COMPOSE_MISSING","Docker Compose v2 is not available.",r)}t.pass("compose",n.cmd==="docker"?n.version:`${n.version} (${n.cmd})`)}function Dw(e,t){if(!Rw.includes(e))t.fail("arch","ARCH_UNSUPPORTED",`No NimbleBrain image is published for ${e||"this architecture"}.`);t.pass("arch",e)}function jw({memory:e,kind:t},n){if(e>0&&e<Ow)n.fail("memory","LOW_MEMORY",`Docker has ${Lc(e)} of memory; NimbleBrain needs 2 GB.`,t);n.pass("memory",e>0?Lc(e):"unknown")}async function Uw(e,t,n,r,o){if(n){o.pass("port",`${t} (this install)`);return}if(r===void 0){if(!await e.portFree(t))o.fail("port","PORT_IN_USE",`Port ${t} is in use.`);o.pass("port",String(t));return}let i;try{i=await qn(e,r,t,"web")}catch(s){if(s instanceof x)o.fail("port",s.code,s.message);throw s}return o.pass("port",i?`${i.to} (${t} is in use by ${Uo(e,i)})`:String(t)),i}function Zw(e){try{let t=JSON.parse(e);return{arch:typeof t.Architecture==="string"?t.Architecture:"",memory:typeof t.MemTotal==="number"?t.MemTotal:0,kind:t.OperatingSystem==="Docker Desktop"?"docker_desktop":t.Name==="colima"?"colima":void 0}}catch{return{arch:"",memory:0}}}function Lc(e){return`${(e/1073741824).toFixed(1)} GB`}var tn={version:"The NimbleBrain runtime release installed, without the leading v",phase:"starting until the install's first start answers health, else ready; npx nimblebrain finishes a starting install, and only down, logs, uninstall, status and doctor act on one",cli_version:"This CLI's version; it moves independently of the runtime",health:"ok when NimbleBrain answers, else down",url:"Where the web UI and API answer, on 127.0.0.1",workspaces:"Each workspace as {id, name, mcp}, mcp being its MCP URL; empty while down",agent:"{connected, server, skill}: the coding agent init connected (or null), the name this install's server is registered under in it (nimblebrain for the default home, nimblebrain-<folder> for another; null with no agent), and the nimblebrain skill's name when that agent has it (else null)",model_key:"set or missing: whether the install's .env holds a model key (never the key)",host_loopback:"Whether this release can reach a server on this machine; mcp add needs it, update brings it",local_model:"The Ollama model saved for NimbleBrain's agents (nimblebrain-<model>), or null",model_source:"{source, label, model}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet); that as a person reads it, such as your Claude Max subscription through Claude Code (Sonnet); and the model a subscription's turns run on as --model named it (sonnet by default for claude; null for Codex's own default, and for api and local). A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget",agent_runtime:"{name, worker}: the runtime NimbleBrain's agents run on (native, claude-code or codex), and the agent worker that serves it as {running, pid, url, log, login_item} (null for native): whether it answers /healthz, its process id while it runs, its ACP URL on 127.0.0.1, its log file, and the macOS LaunchAgent that starts it at login and again after a crash (null when none is installed, as after down)",telemetry:"{state, locked?, ask?, set?}: on, off or undecided; locked says why no one can change it here; ask and set, only while undecided, are the question to pass to the person and the command that answers it",updates:"{cli?, runtime?}, each {current, latest}: what the last cached lookup found; absent when nothing is known or the check is off"};var nr={init:{...tn,model_source:"{source, label, model}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet); that as a person reads it, such as your Claude Max subscription through Claude Code (Sonnet); and the model a subscription's turns run on as --model named it (sonnet by default for claude; null for Codex's own default, and for api and local). A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget. When nothing runs them and no person was asked (--yes, --json or no terminal, without --use), it also carries {ask, options, default, set}: the question to pass to the person, each source as {source, label, available, detected, note} (available: it can be chosen here; detected: signed in, a key saved, or Ollama answering), the one to suggest, and the command that answers it",already:"true when an install was already here; it was reported, not changed",manual:"The settings to add to the coding agent by hand, when connecting it failed",opened:"Whether the browser opened, when init tried (a new install, a person at a terminal)",ollama_started:"The command that started Ollama, when this run started it",port_moved:"{from, to, held_by, home}: present when the default port was in use and no --port was given, so the next free port 100 on was taken instead: the default, the port used, what holds the default (nimblebrain: another install's web UI; agent_worker: another install's agent worker; other: anything else), and that install's home when the CLI can see it (else null); on a new install only, and recorded, so every later command uses it"},doctor:{checks:"Each check run, in order, as {check, ok, detail}",arch:"The CPU architecture Docker reports",ollama_started:"The command that started Ollama, when this run started it; on a local model only",port_moved:"{from, to, held_by, home}: present when the default port was in use and no --port was given, so the next free port 100 on was taken instead: the default, the port used, what holds the default (nimblebrain: another install's web UI; agent_worker: another install's agent worker; other: anything else), and that install's home when the CLI can see it (else null); with no install in the home, as init would take it"},status:tn,open:{url:"The web UI's URL, to open by hand when opened is false",opened:"Whether a browser was started"},key:{provider:"The provider the key was entered for",model_key:"set"},"local-model":{local_model:"The model NimbleBrain's agents now run on (nimblebrain-<model>)",ollama_started:"The command that started Ollama, when this run started it"},telemetry:{telemetry:tn.telemetry},use:{model_source:"{source, label, model}: what runs NimbleBrain's agents, as use names it (claude, codex, api or local; null when nothing does yet); that as a person reads it, such as your Claude Max subscription through Claude Code (Sonnet); and the model a subscription's turns run on as --model named it (sonnet by default for claude; null for Codex's own default, and for api and local). A subscription is in use whenever .env names its worker; a saved key or local model then serves only runs with a spend budget",agent_runtime:"{name, worker}: the runtime NimbleBrain's agents run on (native, claude-code or codex), and the agent worker that serves it as {running, pid, url, log, login_item} (null for native): whether it answers /healthz, its process id while it runs, its ACP URL on 127.0.0.1, its log file, and the macOS LaunchAgent that starts it at login and again after a crash (null when none is installed, as after down)",billed_to:"Who pays for each turn, from the agent CLI's own sign-in, such as your Claude Max subscription; for claude and codex only",tools:"What the agent CLI may call during a turn: your workspace's tools, and for Codex its read-only shell; for claude and codex only",provider:"The provider whose key is saved; for api only",local_model:"The model NimbleBrain's agents now run on (nimblebrain-<model>); for local only",ollama_started:"The command that started Ollama, when this run started it; for local only",port_moved:"{from, to, held_by, home}: present when the default port was in use and no --port was given, so the next free port 100 on was taken instead: the default, the port used, what holds the default (nimblebrain: another install's web UI; agent_worker: another install's agent worker; other: anything else), and that install's home when the CLI can see it (else null); the agent worker's port, for claude and codex only (27290 and 27291 by default), recorded in .env and the login item"},up:{...tn,ollama_started:"The command that started Ollama, when this run started it"},down:{health:"down"},logs:{lines:"The runtime's last log lines, up to 100"},update:{...tn,already:"true when the install was already on that release",from:"The release moved from, as vX.Y.Z, when it moved",skill_update:"What happened to the connected agent's nimblebrain skill: updated, unchanged, not_installed or failed; absent with no agent"},uninstall:{removed:"true"},"mcp add":{serverName:"The name the server was added under",url:"The URL as given",dialed:"Where NimbleBrain, inside Docker, connects to it",placements:"Where the server's UI appears, from its Server Card",wsId:"The workspace it was added to",warning:"Why the server is not connected yet (it was added anyway), when it is not",notice:"Anything else NimbleBrain says about the server, when it says something"},"mcp list":{wsId:"The workspace listed",servers:"Each server as {serverName, displayName?, url?, state?, status?, statusReason?, toolCount?}"},"mcp remove":{serverName:"The server removed",wsId:"The workspace it was removed from"},help:{cli_version:"This CLI's version",commands:"Each command as {name, args, description, answer}",flags:"Each flag as {name, short?, takes, description, commands?}",errors:"Each error code as {code, fix, exit}"}};var Bw={name:"help",args:[],description:"These commands and flags; with --json, these, each command's answer and every error code as JSON",answer:{...nr.help}};function Mc(){return[...Object.keys(Yn).flatMap((t)=>{if(t==="mcp")return Object.keys(Xt).map((r)=>{let o=Xt[r];return{name:`mcp ${r}`,args:o.operand?[`<${o.operand}>`]:[],description:o.description,answer:{...nr[`mcp ${r}`]}}});let n=Yn[t];return[{name:t,args:[...n.args],description:n.description,answer:{...nr[t]}}]}),Bw]}function Dc(){return Object.entries(qo).map(([e,t])=>{let n={name:`--${e}`,takes:"takes"in t?t.takes:null,description:t.description};if("short"in t)n.short=`-${t.short}`;if("commands"in t)n.commands=[...t.commands];return n})}function Fw(){return Object.keys(Fn).map((e)=>({code:e,fix:Fn[e],exit:Lo(e)}))}function jc(e){return{ok:!0,cli_version:e,commands:Mc(),flags:Dc(),errors:Fw()}}function Uc(e){let t=Mc().map((i)=>[[i.name,...i.args].join(" "),i.description]),n=Dc().map((i)=>[[i.takes?`${i.name} <${i.takes}>`:i.name,i.short].filter(Boolean).join(", "),i.commands?`${i.description}; for ${i.commands.join(", ")}`:i.description]),r=Math.max(...[...t,...n].map(([i])=>i.length))+2,o=([i,s])=>` ${i.padEnd(r)}${s}`;return[`nimblebrain ${e}: install and run NimbleBrain on this machine`,"","Usage: npx nimblebrain [command] [flags]","","Commands:",...t.map(o),"","Flags:",...n.map(o),"","What each command answers, and every error code and its fix: npx nimblebrain help --json",""].join(`
93
+ `)}import{dirname as L_,join as ar}from"node:path";import{join as Vw}from"node:path";var qw="ai.nimblebrain.agent-worker";function rr(e,t){let n=`${qw}.${t}`;return{label:n,path:Vw(e.home,"Library","LaunchAgents",`${n}.plist`)}}var Hw=["PATH","HOME","LANG","CLAUDE_CONFIG_DIR","CODEX_HOME"];function Zc(e,t,n,r){let o=Hw.filter((i)=>r[i]).map((i)=>` <key>${i}</key>
94
+ <string>${nn(r[i]??"")}</string>`);return`<?xml version="1.0" encoding="UTF-8"?>
93
95
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
94
96
  <plist version="1.0">
95
97
  <dict>
96
98
  <key>Label</key>
97
- <string>${Jt(e.label)}</string>
99
+ <string>${nn(e.label)}</string>
98
100
  <key>ProgramArguments</key>
99
101
  <array>
100
- ${t.map((i)=>` <string>${Jt(i)}</string>`).join(`
102
+ ${t.map((i)=>` <string>${nn(i)}</string>`).join(`
101
103
  `)}
102
104
  </array>
103
105
  <key>EnvironmentVariables</key>
@@ -117,29 +119,28 @@ ${o.join(`
117
119
  <key>ProcessType</key>
118
120
  <string>Background</string>
119
121
  <key>StandardOutPath</key>
120
- <string>${Jt(n)}</string>
122
+ <string>${nn(n)}</string>
121
123
  <key>StandardErrorPath</key>
122
- <string>${Jt(n)}</string>
124
+ <string>${nn(n)}</string>
123
125
  </dict>
124
126
  </plist>
125
- `}function Jt(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}var Zo=(e)=>`gui/${e.uid}`;async function _c(e,t){for(let n=0;n<5;n++){if((await e.exec("launchctl",["bootstrap",Zo(e),t.path])).code===0)return!0;await e.sleep(500)}return!1}async function bc(e,t){return(await e.exec("launchctl",["bootout",`${Zo(e)}/${t.label}`])).code===0}async function Wn(e,t){let n=await e.exec("launchctl",["print",`${Zo(e)}/${t.label}`]);if(n.code!==0)return{loaded:!1};let r=Number(n.stdout.match(/^\s*pid = (\d+)/m)?.[1]),o=Number(n.stdout.match(/^\s*last exit code = (-?\d+)/m)?.[1]);return{loaded:!0,...Number.isInteger(r)&&r>0?{pid:r}:{},...Number.isInteger(o)?{lastExit:o}:{}}}Ho();Ko();It();Tt();var st={runtime:"NB_AGENT_RUNTIME",url:"NB_AGENT_RUNTIME_URL"},at=(e)=>({record:Xn(e,"agent-worker.json"),log:Xn(e,"agent-worker.log"),bin:Xn(e,"bin","nimblebrain.mjs"),binDir:Xn(e,"bin")}),Xt={"claude-code":{label:"Claude Code",arg:"claude",bin:"claude",status:Vo,readsStderr:!1,account:qo,variant:"claude"},codex:{label:"Codex",arg:"codex",bin:"codex",status:Go,readsStderr:!0,account:Wo,variant:"codex"}},i_=20000,s_=5000,Qn=250;function er(e){let t=e.match(/^NB_AGENT_RUNTIME=(\S*)\r?$/m)?.[1];if(t!=="claude-code"&&t!=="codex")return{name:"native"};let n=e.match(/^NB_AGENT_RUNTIME_URL=(\S*)\r?$/m)?.[1]??"",r=Number(n.match(/^https?:\/\/[^/]+:(\d+)\//)?.[1]);return Number.isInteger(r)&&r>0?{name:t,port:r}:{name:t}}function a_(e){return`http://host.docker.internal:${e}/acp`}var Tc=(e)=>`http://127.0.0.1:${e}/acp`;async function tr(e,t){return(await e.getText(`http://127.0.0.1:${t}/healthz`,1000))?.status===200}async function Ac(e,t){let{name:n,port:r}=er(await e.readText(R(t).env)??"");if(n==="native")return{name:n,worker:null};let o=await Jo(e,t),i=r??o?.port,s=i!==void 0&&await tr(e,i),a=await u_(e,t),l=s&&a?(await Wn(e,a)).pid??null:null;return{name:n,worker:{running:s,pid:l,url:i===void 0?"":Tc(i),log:at(t).log,login_item:a?.path??null}}}async function nr(e,t){let n=Xt[t],r=await e.exec(n.bin,n.status,{env:Ge(e.env)}),o=r.missing?void 0:n.readsStderr?`${r.stdout}
126
- ${r.stderr}`:r.stdout;try{return n.account(o)}catch(i){if(!(i instanceof Q))throw i;throw new x(c_[i.reason],i.message,{},n.variant)}}var c_={not_installed:"AGENT_CLI_MISSING",unreadable:"AGENT_CLI_MISSING",not_signed_in:"AGENT_NOT_SIGNED_IN",api_key:"AGENT_BILLS_API_KEY"};async function Jo(e,t){let n=await e.readText(at(t).record);if(n===void 0)return;try{let r=JSON.parse(n);if(typeof r?.port!=="number"||r.agent!=="claude-code"&&r.agent!=="codex")return;return{port:r.port,agent:r.agent,plan:Ic(r.plan),label:Ic(r.label),pid:typeof r.pid==="number"?r.pid:void 0}}catch{return}}var Ic=(e)=>typeof e==="string"&&e?e:void 0;async function Rc(e,t){let n=await Jo(e,t);return n&&await tr(e,n.port)?n.plan:void 0}async function Yo(e,t){try{let n=JSON.parse(await e.readText(R(t).install)??"");return typeof n.project==="string"&&n.project?n.project:void 0}catch{return}}async function u_(e,t){let n=await Yo(e,t);if(!n)return;let r=Gn(e,n);return await e.readText(r.path)===void 0?void 0:r}async function Cc(e,t){let n=await e.exec("ps",["-p",String(t),"-o","command="]);return n.code===0&&n.stdout.includes(it)}async function l_(e,t){if(!await Cc(e,t))return!1;await e.exec("kill",["-TERM",String(t)]);for(let n=0;n<s_;n+=Qn)if(await e.sleep(Qn),!await Cc(e,t))return!0;return await e.exec("kill",["-KILL",String(t)]),!0}async function Pe(e,t){let n=await Jo(e,t),r=await Yo(e,t),o=!1;if(r){let i=Gn(e,r);if(o=await bc(e,i),await e.readText(i.path)!==void 0)await e.remove(i.path),o=!0}if(n?.pid!==void 0)o=await l_(e,n.pid)||o;return await e.remove(at(t).record),o}async function d_(e,t,n,r){let o=at(t),i=e.self.script.endsWith(".js")?await e.readText(e.self.script):void 0,s=i===void 0?e.self.script:o.bin,a=[it,Xt[n].arg,"--port",String(r)];return{program:[e.self.node,s,...a,"--log",o.log],...i===void 0?{}:{copy:i}}}async function Xo(e,t,n,r,o){if(e.platform!=="darwin")throw new x("PLATFORM_UNSUPPORTED","The agent worker runs on macOS only, as a login item launchd keeps running.");let i=at(t),s=Gn(e,await Yo(e,t)??"nimblebrain"),{program:a,copy:l}=await d_(e,t,n,r),d=wc(s,a,i.log,e.env),f={port:r,agent:n,plan:o,label:s.label},g=()=>e.writeText(i.record,`${JSON.stringify(f,null,2)}
127
- `,384),w=async()=>({running:!0,pid:(await Wn(e,s)).pid??null,url:Tc(r),log:i.log,login_item:s.path});if(await e.readText(s.path)===d&&(l===void 0||await e.readText(i.bin)===l)&&await tr(e,r))return await g(),w();if(await Pe(e,t),!await e.portFree(r))throw new x("PORT_IN_USE",`Port ${r} on 127.0.0.1 is in use, so the agent worker cannot listen there.`);if(l!==void 0)await e.writeText(i.bin,l,384);if(await e.readText(i.log)===void 0)await e.writeText(i.log,"",384);if(await e.writeText(s.path,d,420),await g(),!await _c(e,s))throw await Pe(e,t),new x("AGENT_WORKER_FAILED","launchd did not load the agent worker.",{log:i.log,login_item:s.path});if(await p_(e,s,r))return w();throw await Pe(e,t),new x("AGENT_WORKER_FAILED",`The agent worker stopped before it answered${await f_(e,i.log)}`,{log:i.log})}async function p_(e,t,n){for(let r=0;r<=i_;r+=Qn){if(await tr(e,n))return!0;let o=await Wn(e,t);if(!o.loaded||o.pid===void 0&&o.lastExit!==void 0&&o.lastExit!==0)return!1;await e.sleep(Qn)}return!1}async function f_(e,t){let n=(await e.readText(t)??"").split(`
128
- `).map((r)=>r.trim()).filter(Boolean).pop();return n?`: ${n}`:"."}async function Qt(e,t){let{name:n,port:r}=er(await e.readText(R(t).env)??"");if(n==="native")return;let o=await nr(e,n);await Xo(e,t,n,r??Ct[n],o.plan)}async function Oc(e,t,n,r){let o=R(t),i=n==="native"||r===void 0?{[st.runtime]:"",[st.url]:""}:{[st.runtime]:n,[st.url]:a_(r)};await e.writeText(o.env,Re(await e.readText(o.env)??"",i),384)}import{join as At}from"node:path";var me="nimblebrain";async function Nc(e,t,n){if(t==="none")return{connected:null};let r=h_(t,n);try{if(t==="claude-code")return await e.exec("claude",["mcp","remove","-s","user",me]),(await e.exec("claude",["mcp","add","--transport","http","-s","user",me,n])).code===0?{connected:t}:{connected:null,manual:r};if(t==="codex")return await e.exec("codex",["mcp","remove",me]),(await e.exec("codex",["mcp","add",me,"--url",n])).code===0?{connected:t}:{connected:null,manual:r};return await m_(e,n),{connected:t}}catch{return{connected:null,manual:r}}}async function m_(e,t){let n=At(e.home,".cursor","mcp.json"),r=await e.readText(n),o=r?JSON.parse(r):{};o.mcpServers={...o.mcpServers??{},[me]:{url:t}},await e.writeText(n,`${JSON.stringify(o,null,2)}
129
- `,384)}function h_(e,t){if(e==="claude-code")return`claude mcp add --transport http -s user ${me} ${t}`;if(e==="codex")return`codex mcp add ${me} --url ${t}`;return`Add to ~/.cursor/mcp.json: {"mcpServers":{"${me}":{"url":"${t}"}}}`}async function Pc(e,t){if(t==="none")return;await e.exec("npx",["-y","skills","add","nimblebraininc/skills","--skill",rr,"--agent",t,"-g","-y"],{timeoutMs:120000})}async function Lc(e,t){if(!await Qo(e,t))return"not_installed";try{let n=await e.exec("npx",["-y","skills","update",rr,"-g","-y"],{timeoutMs:120000});if(n.code!==0)return"failed";return/Updated \d+ skill/.test(n.stdout)?"updated":"unchanged"}catch{return"failed"}}var rr="nimblebrain";function g_(e,t){if(t==="claude-code")return At(e.env.CLAUDE_CONFIG_DIR?.trim()||At(e.home,".claude"),"skills");if(t==="codex")return At(e.home,".agents","skills");if(t==="cursor")return At(e.home,".cursor","skills");return}async function Qo(e,t){let n=g_(e,t);if(!n)return null;return await e.readText(At(n,rr,"SKILL.md"))===void 0?null:rr}import{join as si}from"node:path";Tt();var Mc={claude:"claude-code",codex:"codex"},or=(e)=>e==="claude"||e==="codex",jc="How should NimbleBrain's agents run?";function ei(e,t){let n=er(e).name;if(n==="claude-code")return"claude";if(n==="codex")return"codex";if(ue(e))return"local";return Oe(e,xe(t))?"api":null}async function Rt(e,t){let n=R(t),r=await e.readText(n.env)??"",o=await e.readText(n.compose)??"",i=ei(r,o);if(i===null)return{source:i,label:null};let s=i==="api"?ot(r,o):i==="local"?ue(r):await Rc(e,t);return{source:i,label:w_(i,s??void 0)}}function w_(e,t){switch(e){case"claude":return`your ${t??"Claude"} subscription through Claude Code`;case"codex":return`your ${t===void 0||t==="ChatGPT"?"ChatGPT plan":t} through Codex`;case"api":return t?`an API key (${t})`:"an API key";case"local":return t?`a local model (${t}) through Ollama`:"a local model through Ollama"}}async function en(e,t,n){let[r,o]=await Promise.all([Dc(e,"claude",n),Dc(e,"codex",n)]),i=ot(t,n),s=kt(n)&&await Un(e)!==void 0;return[r,o,{source:"api",label:"An API key for a hosted model (Anthropic, OpenAI, Google, …)",available:!0,detected:i!==null,note:i?`your ${i} key is saved`:null},{source:"local",label:"A local model through Ollama",available:kt(n),detected:s,note:!kt(n)?"this release takes no local model":s?"Ollama is running":null}]}var __={claude:(e)=>`Your ${e??"Claude"} subscription, through Claude Code`,codex:()=>"Your ChatGPT plan, through Codex"},b_={AGENT_CLI_MISSING:(e)=>`${e} is not installed`,AGENT_NOT_SIGNED_IN:()=>"not signed in",AGENT_BILLS_API_KEY:()=>"signed in with an API key, not a subscription"};async function Dc(e,t,n){let r=__[t],o=(s)=>({source:t,label:r(),available:!1,detected:!1,note:s});if(e.platform!=="darwin")return o("macOS only for now");if(!Do(n))return o("needs a newer NimbleBrain release");let i=Mc[t];try{let s=await nr(e,i);return{source:t,label:r(s.plan),available:!0,detected:!0,note:"signed in"}}catch(s){if(!(s instanceof x))throw s;let a=b_[s.code]?.(Xt[i].label)??null;return{source:t,label:r(),available:!0,detected:!1,note:a}}}function Uc(e){let t=(n)=>e.some((r)=>r.source===n&&r.available&&r.detected);if(t("claude"))return"claude";if(t("codex"))return"codex";return"api"}function Zc(e,t){return{ask:jc,options:e,default:Uc(e),set:`${t} use ${He.join("|")}`}}function y_(e){let t=e.filter((i)=>i.available),n=Math.max(...t.map((i)=>i.label.length))+3,r=[jc,...t.map((i,s)=>{let a=i.note?`(${i.note})`:"";return` ${s+1}) ${a?i.label.padEnd(n):i.label}${a}`.trimEnd()})],o=e.filter((i)=>!i.available);for(let i of o)r.push(` Not here: ${z_(i.label)} (${i.note})`);return r}var z_=(e)=>e.charAt(0).toLowerCase()+e.slice(1);async function ir(e,t){let n=t.filter((s)=>s.available),r=Uc(t),o=Math.max(1,n.findIndex((s)=>s.source===r)+1);for(let s of y_(t))e.say(s);let i=n.map((s)=>s.source).join(", ");for(let s=0;s<3;s++){let a=(await e.prompt(`Choose 1-${n.length}, or ${i} [${o}]: `)).trim().toLowerCase();if(a==="")return n[o-1]?.source??r;let l=n[Number(a)-1];if(/^\d+$/.test(a)&&l)return l.source;let d=n.find((f)=>f.source===a);if(d)return d.source;e.say(`"${a}" is not one of them.`)}throw new x("USAGE",`Choose one of ${i}.`)}function Bc(){return new x("USAGE",`use takes ${Gt}, or asks which at a terminal.`)}async function sr(e,t,n,r){let o=Mc[n],i=Xt[o].label;if(e.platform==="linux")throw new x("HOST_LOOPBACK_UNREACHABLE",`On Linux, NimbleBrain's container cannot reach an agent worker on this machine's 127.0.0.1, so it cannot run on ${i} yet.`);if(e.platform!=="darwin")throw new x("PLATFORM_UNSUPPORTED",`The agent worker runs on macOS only, so NimbleBrain cannot run on ${i} here yet.`);let s=await e.readText(R(t).compose)??"";if(!Do(s))throw new x("RUNTIME_UNSUPPORTED","This release's runtime takes no agent runtime from .env; a newer release does.");let a=await nr(e,o);await Pe(e,t);let l=r??Ct[o],d=await Xo(e,t,o,l,a.plan);return await Oc(e,t,o,l),{worker:d,account:a,runtime:o}}async function Ot(e,t,n){await Pe(e,t);let r=R(t),o={[st.runtime]:"",[st.url]:""};if(n)for(let i of oc)o[i]="";await e.writeText(r.env,Re(await e.readText(r.env)??"",o),384)}import{randomUUID as Fc}from"node:crypto";import{join as cr}from"node:path";var x_="phc_qKmpYhdDtcFYZchu3KAKFFmYHG88nfUDPCFqxoAmbS7E",k_="https://us.i.posthog.com/batch/",ti="Help improve NimbleBrain by sending anonymous usage data? No prompts, content, names or keys are sent.",ct=(e)=>cr(e,"telemetry-report.jsonl"),ar=(e)=>cr(e,"telemetry-id"),S_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,v_=!0;function ni(e){return e.env.NIMBLEBRAIN_TELEMETRY_KEY??(v_?x_:"")}function ri(e){return e.env.DO_NOT_TRACK==="1"}function Le(e){if(ri(e))return"do_not_track";if(!ni(e))return"no_destination";return}function ur(e,t,n){if(n)return{state:e==="undecided"?"off":e,locked:n};if(e!=="undecided")return{state:e};return{state:e,ask:ti,set:`${t} telemetry on|off`}}function lr(e,t,n){let r=[],o={id:n??Fc(),record(i,s={}){if(Le(e))return;r.push({event:i,distinct_id:o.id,timestamp:new Date().toISOString(),properties:{cli_version:t,os:process.platform,arch:process.arch,node_version:process.version,...s}})},async settle(i,s){try{if(s==="off"||Le(e)){await e.remove(ct(i));return}let l=[...await qc(e,i),...r].map((d)=>({...d,distinct_id:o.id}));if(s==="on")await $_(e,i,l);else if(r.length>0)await e.writeText(ct(i),Hc(l),384)}catch{}finally{r.length=0}}};return o}async function $_(e,t,n){if(n.length===0)return;let r=await e.postJson(k_,{api_key:ni(e),batch:n});if(r&&r.status<300)await e.remove(ct(t));else await e.writeText(ct(t),Hc(n),384)}async function Vc(e,t){if(Le(e))return;try{let n=(await e.readText(ar(t)))?.trim();if(n&&S_.test(n))return n.toLowerCase();let r=await tn(e,t)??Fc();return await e.writeText(ar(t),`${r}
130
- `,384),r}catch{return}}async function tn(e,t){return(await qc(e,t))[0]?.distinct_id}async function qc(e,t){let n=await e.readText(ct(t));if(!n)return[];return n.split(`
131
- `).filter((r)=>r.trim()).flatMap((r)=>{try{return[JSON.parse(r)]}catch{return[]}})}var Hc=(e)=>`${e.map((t)=>JSON.stringify(t)).join(`
127
+ `}function nn(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}var Qo=(e)=>`gui/${e.uid}`;async function Bc(e,t){for(let n=0;n<5;n++){if((await e.exec("launchctl",["bootstrap",Qo(e),t.path])).code===0)return!0;await e.sleep(500)}return!1}async function Fc(e,t){return(await e.exec("launchctl",["bootout",`${Qo(e)}/${t.label}`])).code===0}async function or(e,t){let n=await e.exec("launchctl",["print",`${Qo(e)}/${t.label}`]);if(n.code!==0)return{loaded:!1};let r=Number(n.stdout.match(/^\s*pid = (\d+)/m)?.[1]),o=Number(n.stdout.match(/^\s*last exit code = (-?\d+)/m)?.[1]);return{loaded:!0,...Number.isInteger(r)&&r>0?{pid:r}:{},...Number.isInteger(o)?{lastExit:o}:{}}}oi();ai();Pt();Re();var xe={runtime:"NB_AGENT_RUNTIME",url:"NB_AGENT_RUNTIME_URL",model:"NB_AGENT_WORKER_MODEL"},dt=(e)=>({record:ar(e,"agent-worker.json"),log:ar(e,"agent-worker.log"),bin:ar(e,"bin","nimblebrain.mjs"),binDir:ar(e,"bin")}),Lt={"claude-code":{label:"Claude Code",arg:"claude",bin:"claude",status:ni,readsStderr:!1,account:ri,variant:"claude"},codex:{label:"Codex",arg:"codex",bin:"codex",status:ii,readsStderr:!0,account:si,variant:"codex"}},M_=20000,D_=5000,cr=250;function on(e){let t=e.match(/^NB_AGENT_RUNTIME=(\S*)\r?$/m)?.[1];if(t!=="claude-code"&&t!=="codex")return{name:"native"};let n=e.match(/^NB_AGENT_RUNTIME_URL=(\S*)\r?$/m)?.[1]??"",r=Number(n.match(/^https?:\/\/[^/]+:(\d+)\//)?.[1]),o=e.match(/^NB_AGENT_WORKER_MODEL=(\S+)\r?$/m)?.[1];return{name:t,...Number.isInteger(r)&&r>0?{port:r}:{},...o?{model:o}:{}}}function j_(e){return`http://host.docker.internal:${e}/acp`}var Qc=(e)=>`http://127.0.0.1:${e}/acp`;async function ur(e,t){return(await e.getText(`http://127.0.0.1:${t}/healthz`,1000))?.status===200}async function eu(e,t){let{name:n,port:r}=on(await e.readText(R(t).env)??"");if(n==="native")return{name:n,worker:null};let o=await ui(e,t),i=r??o?.port,s=i!==void 0&&await ur(e,i),a=await Z_(e,t),u=s&&a?(await or(e,a)).pid??null:null;return{name:n,worker:{running:s,pid:u,url:i===void 0?"":Qc(i),log:dt(t).log,login_item:a?.path??null}}}async function lr(e,t){let n=Lt[t],r=await e.exec(n.bin,n.status,{env:Ge(e.env)}),o=r.missing?void 0:n.readsStderr?`${r.stdout}
128
+ ${r.stderr}`:r.stdout;try{return n.account(o)}catch(i){if(!(i instanceof X))throw i;throw new x(U_[i.reason],i.message,{},n.variant)}}var U_={not_installed:"AGENT_CLI_MISSING",unreadable:"AGENT_CLI_MISSING",not_signed_in:"AGENT_NOT_SIGNED_IN",api_key:"AGENT_BILLS_API_KEY"};async function ui(e,t){let n=await e.readText(dt(t).record);if(n===void 0)return;try{let r=JSON.parse(n);if(typeof r?.port!=="number"||r.agent!=="claude-code"&&r.agent!=="codex")return;return{port:r.port,agent:r.agent,plan:ci(r.plan),model:ci(r.model),label:ci(r.label),pid:typeof r.pid==="number"?r.pid:void 0}}catch{return}}var ci=(e)=>typeof e==="string"&&e?e:void 0;async function tu(e,t){let n=await ui(e,t);return n&&await ur(e,n.port)?n.plan:void 0}async function li(e,t){try{let n=JSON.parse(await e.readText(R(t).install)??"");return typeof n.project==="string"&&n.project?n.project:void 0}catch{return}}async function Z_(e,t){let n=await li(e,t);if(!n)return;let r=rr(e,n);return await e.readText(r.path)===void 0?void 0:r}async function Xc(e,t){let n=await e.exec("ps",["-p",String(t),"-o","command="]);return n.code===0&&n.stdout.includes(at)}async function B_(e,t){if(!await Xc(e,t))return!1;await e.exec("kill",["-TERM",String(t)]);for(let n=0;n<D_;n+=cr)if(await e.sleep(cr),!await Xc(e,t))return!0;return await e.exec("kill",["-KILL",String(t)]),!0}async function Le(e,t){let n=await ui(e,t),r=await li(e,t),o=!1;if(r){let i=rr(e,r);if(o=await Fc(e,i),await e.readText(i.path)!==void 0)await e.remove(i.path),o=!0}if(n?.pid!==void 0)o=await B_(e,n.pid)||o;return await e.remove(dt(t).record),o}async function F_(e,t,n,r,o){let i=dt(t),s=e.self.script.endsWith(".ts")?void 0:await e.readText(e.self.script),a=s===void 0?e.self.script:i.bin,u=[at,Lt[n].arg,"--port",String(r),...o?["--model",o]:[]];return{program:[e.self.node,a,...u,"--log",i.log],...s===void 0?{}:{copy:s}}}async function di(e,t,n,r,o,i){if(e.platform!=="darwin")throw new x("PLATFORM_UNSUPPORTED","The agent worker runs on macOS only, as a login item launchd keeps running.");let s=dt(t),a=rr(e,await li(e,t)??"nimblebrain"),{program:u,copy:d}=await F_(e,t,n,r,i),p={...e.env,PATH:await H_(e,n)},g=Zc(a,u,s.log,p),w={port:r,agent:n,plan:o,label:a.label,model:i},b=()=>e.writeText(s.record,`${JSON.stringify(w,null,2)}
129
+ `,384),z=async()=>({running:!0,pid:(await or(e,a)).pid??null,url:Qc(r),log:s.log,login_item:a.path});if(await e.readText(a.path)===g&&(d===void 0||await e.readText(s.bin)===d)&&await ur(e,r))return await b(),z();if(await Le(e,t),!await e.portFree(r))throw new x("PORT_IN_USE",`Port ${r} on 127.0.0.1 is in use, so the agent worker cannot listen there.`);if(d!==void 0)await e.writeText(s.bin,d,384);if(await e.readText(s.log)===void 0)await e.writeText(s.log,"",384);if(await e.writeText(a.path,g,420),await b(),!await Bc(e,a))throw await Le(e,t),new x("AGENT_WORKER_FAILED","launchd did not load the agent worker.",{log:s.log,login_item:a.path});if(await V_(e,a,r))return z();throw await Le(e,t),new x("AGENT_WORKER_FAILED",`The agent worker stopped before it answered${await q_(e,s.log)}`,{log:s.log})}async function V_(e,t,n){for(let r=0;r<=M_;r+=cr){if(await ur(e,n))return!0;let o=await or(e,t);if(!o.loaded||o.pid===void 0&&o.lastExit!==void 0&&o.lastExit!==0)return!1;await e.sleep(cr)}return!1}async function q_(e,t){let n=(await e.readText(t)??"").split(`
130
+ `).map((r)=>r.trim()).filter(Boolean).pop();return n?`: ${n}`:"."}async function sn(e,t){let{name:n,port:r,model:o}=on(await e.readText(R(t).env)??"");if(n==="native")return;let i=await lr(e,n);await di(e,t,n,r??ct[n],i.plan,o)}async function H_(e,t){let n=await e.which(Lt[t].bin),r=[...n?[L_(n)]:[],...(e.env.PATH??"").split(":").filter((o)=>o&&!/[\\/]_npx[\\/]/.test(o))];return[...new Set(r)].join(":")}async function nu(e,t,n,r,o){let i=R(t),s=n==="native"||r===void 0?{[xe.runtime]:"",[xe.url]:"",[xe.model]:""}:{[xe.runtime]:n,[xe.url]:j_(r),[xe.model]:o??""};await e.writeText(i.env,Oe(await e.readText(i.env)??"",s),384)}import{join as _i}from"node:path";Re();var ou={claude:"claude-code",codex:"codex"},Mt=(e)=>e==="claude"||e==="codex",iu="How should NimbleBrain's agents run?";function fi(e,t){let n=on(e).name;if(n==="claude-code")return"claude";if(n==="codex")return"codex";if(le(e))return"local";return Ne(e,ze(t))?"api":null}async function Dt(e,t){let n=R(t),r=await e.readText(n.env)??"",o=await e.readText(n.compose)??"",i=fi(r,o);if(i===null)return{source:i,label:null,model:null};let s=i==="api"?lt(r,o):i==="local"?le(r):await tu(e,t),a=Mt(i)?on(r).model??null:null,u=G_(i,s??void 0);return{source:i,label:a?`${u} (${Tt(a)})`:u,model:a}}function G_(e,t){switch(e){case"claude":return`your ${t??"Claude"} subscription through Claude Code`;case"codex":return`your ${t===void 0||t==="ChatGPT"?"ChatGPT plan":t} through Codex`;case"api":return t?`an API key (${t})`:"an API key";case"local":return t?`a local model (${t}) through Ollama`:"a local model through Ollama"}}async function an(e,t,n){let[r,o]=await Promise.all([ru(e,"claude",n),ru(e,"codex",n)]),i=lt(t,n),s=Ct(n)&&await Kn(e)!==void 0;return[r,o,{source:"api",label:"An API key for a hosted model (Anthropic, OpenAI, Google, …)",available:!0,detected:i!==null,note:i?`your ${i} key is saved`:null},{source:"local",label:"A local model through Ollama",available:Ct(n),detected:s,note:!Ct(n)?"this release takes no local model":s?"Ollama is running":null}]}var W_={claude:(e)=>`Your ${e??"Claude"} subscription, through Claude Code`,codex:()=>"Your ChatGPT plan, through Codex"},K_={AGENT_CLI_MISSING:(e)=>`${e} is not installed`,AGENT_NOT_SIGNED_IN:()=>"not signed in",AGENT_BILLS_API_KEY:()=>"signed in with an API key, not a subscription"};async function ru(e,t,n){let r=W_[t],o=(s)=>({source:t,label:r(),available:!1,detected:!1,note:s});if(e.platform!=="darwin")return o("macOS only for now");if(!Ko(n))return o("needs a newer NimbleBrain release");let i=ou[t];try{let s=await lr(e,i);return{source:t,label:r(s.plan),available:!0,detected:!0,note:"signed in"}}catch(s){if(!(s instanceof x))throw s;let a=K_[s.code]?.(Lt[i].label)??null;return{source:t,label:r(),available:!0,detected:!1,note:a}}}function su(e){let t=(n)=>e.some((r)=>r.source===n&&r.available&&r.detected);if(t("claude"))return"claude";if(t("codex"))return"codex";return"api"}function au(e,t){return{ask:iu,options:e,default:su(e),set:`${t} use ${He.join("|")}`}}function J_(e){let t=e.filter((i)=>i.available),n=Math.max(...t.map((i)=>i.label.length))+3,r=[iu,...t.map((i,s)=>{let a=i.note?`(${i.note})`:"";return` ${s+1}) ${a?i.label.padEnd(n):i.label}${a}`.trimEnd()})],o=e.filter((i)=>!i.available);for(let i of o)r.push(` Not here: ${Y_(i.label)} (${i.note})`);return r}var Y_=(e)=>e.charAt(0).toLowerCase()+e.slice(1);async function dr(e,t){let n=t.filter((s)=>s.available),r=su(t),o=Math.max(1,n.findIndex((s)=>s.source===r)+1);for(let s of J_(t))e.say(s);let i=n.map((s)=>s.source).join(", ");for(let s=0;s<3;s++){let a=(await e.prompt(`Choose 1-${n.length}, or ${i} [${o}]: `)).trim().toLowerCase();if(a==="")return n[o-1]?.source??r;let u=n[Number(a)-1];if(/^\d+$/.test(a)&&u)return u.source;let d=n.find((p)=>p.source===a);if(d)return d.source;e.say(`"${a}" is not one of them.`)}throw new x("USAGE",`Choose one of ${i}.`)}function cn(e,t){if(e===void 0||t!==void 0&&Mt(t))return;throw new x("USAGE",t==="local"?"--model is for claude and codex; a local model is named after use local, or with --local-model.":`--model is for claude and codex${t?`, not ${t}`:"; pass --use claude or --use codex with it"}.`)}function cu(){return new x("USAGE",`use takes ${Qt}, or asks which at a terminal.`)}async function fr(e,t,n,r,o){let i=ou[n],s=Lt[i].label;if(e.platform==="linux")throw new x("HOST_LOOPBACK_UNREACHABLE",`On Linux, NimbleBrain's container cannot reach an agent worker on this machine's 127.0.0.1, so it cannot run on ${s} yet.`);if(e.platform!=="darwin")throw new x("PLATFORM_UNSUPPORTED",`The agent worker runs on macOS only, so NimbleBrain cannot run on ${s} here yet.`);let a=await e.readText(R(t).compose)??"";if(!Ko(a))throw new x("RUNTIME_UNSUPPORTED","This release's runtime takes no agent runtime from .env; a newer release does.");let u=await lr(e,i);await Le(e,t);let d=r===void 0?await qn(e,t,ct[i],"worker"):void 0;if(d)e.say(Hn(e,d,"the agent worker"));let p=r??d?.to??ct[i],g=o??Cc[i],w=await di(e,t,i,p,u.plan,g);return await nu(e,t,i,p,g),{worker:w,account:u,runtime:i,moved:d}}async function jt(e,t,n){await Le(e,t);let r=R(t),o={[xe.runtime]:"",[xe.url]:"",[xe.model]:""};if(n)for(let i of $c)o[i]="";await e.writeText(r.env,Oe(await e.readText(r.env)??"",o),384)}import{randomUUID as uu}from"node:crypto";import{join as mr}from"node:path";var X_="phc_qKmpYhdDtcFYZchu3KAKFFmYHG88nfUDPCFqxoAmbS7E",Q_="https://us.i.posthog.com/batch/",pi="Help improve NimbleBrain by sending anonymous usage data? No prompts, content, names or keys are sent.",ft=(e)=>mr(e,"telemetry-report.jsonl"),pr=(e)=>mr(e,"telemetry-id"),eb=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,tb=!0;function mi(e){return e.env.NIMBLEBRAIN_TELEMETRY_KEY??(tb?X_:"")}function hi(e){return e.env.DO_NOT_TRACK==="1"}function Me(e){if(hi(e))return"do_not_track";if(!mi(e))return"no_destination";return}function hr(e,t,n){if(n)return{state:e==="undecided"?"off":e,locked:n};if(e!=="undecided")return{state:e};return{state:e,ask:pi,set:`${t} telemetry on|off`}}function gr(e,t,n){let r=[],o={id:n??uu(),record(i,s={}){if(Me(e))return;r.push({event:i,distinct_id:o.id,timestamp:new Date().toISOString(),properties:{cli_version:t,os:process.platform,arch:process.arch,node_version:process.version,...s}})},async settle(i,s){try{if(s==="off"||Me(e)){await e.remove(ft(i));return}let u=[...await du(e,i),...r].map((d)=>({...d,distinct_id:o.id}));if(s==="on")await nb(e,i,u);else if(r.length>0)await e.writeText(ft(i),fu(u),384)}catch{}finally{r.length=0}}};return o}async function nb(e,t,n){if(n.length===0)return;let r=await e.postJson(Q_,{api_key:mi(e),batch:n});if(r&&r.status<300)await e.remove(ft(t));else await e.writeText(ft(t),fu(n),384)}async function lu(e,t){if(Me(e))return;try{let n=(await e.readText(pr(t)))?.trim();if(n&&eb.test(n))return n.toLowerCase();let r=await un(e,t)??uu();return await e.writeText(pr(t),`${r}
131
+ `,384),r}catch{return}}async function un(e,t){return(await du(e,t))[0]?.distinct_id}async function du(e,t){let n=await e.readText(ft(t));if(!n)return[];return n.split(`
132
+ `).filter((r)=>r.trim()).flatMap((r)=>{try{return[JSON.parse(r)]}catch{return[]}})}var fu=(e)=>`${e.map((t)=>JSON.stringify(t)).join(`
132
133
  `)}
133
- `;function Gc(e){return/^n/i.test(e.trim())?"off":"on"}function E_(e){let t=e.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];return t==="on"||t==="off"?t:"undecided"}async function oi(e,t,n){let r=Le(e),o=await ii(e,n),i=o?.consent??E_(await e.readText(cr(t,".env"))??""),s=r??(o?.locked==="operator"||o?.locked==="no_destination"?o.locked:void 0);return ur(i,fe(e,t),s)}async function Wc(e,t,n){try{let r=await tn(e,t);if(!r)return;let o=JSON.parse(await e.readText(cr(t,"install.json"))??"{}");if(typeof o.port!=="number")return;let i=await oi(e,t,`http://127.0.0.1:${o.port}`);await lr(e,n,r).settle(t,i.locked?"off":i.state)}catch{}}function Kc(e,t,n,r){let o={NB_TELEMETRY_KEY:r?ni(e):""};if(t)o.NB_TELEMETRY_ID=t;if(n!=="undecided")o.NB_TELEMETRY_CONSENT=n;return o}async function ii(e,t){let r=(await e.postJson(`${t}/v1/tools/call`,{server:"nb",tool:"workspace_info",arguments:{}}))?.body?.structuredContent?.telemetry;if(r?.consent!=="on"&&r?.consent!=="off"&&r?.consent!=="undecided")return;return{consent:r.consent,locked:typeof r.locked==="string"?r.locked:void 0}}async function Jc(e,t,n){let r=await e.postJson(`${t}/v1/tools/call`,{server:"nb",tool:"set_telemetry",arguments:{consent:n}}),o=r?.body;if(!r||r.status>=300||o?.isError)throw new x("TELEMETRY_LOCKED",o?.content?.[0]?.text??"NimbleBrain did not accept the answer.")}var Yc={name:"nimblebrain",version:"0.9.0-beta.1",description:"Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",license:"Apache-2.0",type:"module",repository:{type:"git",url:"git+https://github.com/NimbleBrainInc/nimblebrain.git",directory:"packages/cli"},homepage:"https://nimblebrain.ai/developers",bin:{nimblebrain:"dist/nimblebrain.js"},files:["dist"],engines:{node:">=20"},scripts:{build:"bun build src/bin.ts --target=node --minify --outfile=dist/nimblebrain.js --banner='#!/usr/bin/env node'","build:release":"bun run build --define NIMBLEBRAIN_CLI_RELEASE=true",test:"bun test --no-env-file test/"},devDependencies:{"@agentclientprotocol/sdk":"2.4.0",zod:"^4.6.6"}};var he=Yc.version;async function ut(e,t){let n=await e.readText(si(t,"install.json"));if(n===void 0)return;try{let r=JSON.parse(n);if(typeof r?.version!=="string"||typeof r.port!=="number"||typeof r.project!=="string"||r.phase!=="starting"&&r.phase!=="ready")return;return r}catch{return}}async function Nt(e,t){let n=await ut(e,t);if(!n)throw new x("NOT_INSTALLED",`No NimbleBrain install in ${t}.`);return n}async function le(e,t){let n=await Nt(e,t);if(n.phase!=="ready")throw new x("INSTALL_INCOMPLETE",`The NimbleBrain install in ${t} has not finished installing.`);return n}async function ke(e,t){let n=await Nt(e,t),r=ai(n),o=await nn(e,r),i=o&&n.phase==="ready"?await ci(e,r):[],s=await e.readText(si(t,"docker-compose.yml"))??"",a=xe(s),l=await e.readText(si(t,".env"))??"",d=Oe(l,a)?"set":"missing";return{ok:!0,version:n.version,phase:n.phase,cli_version:he,health:o?"ok":"down",url:r,workspaces:i,agent:{connected:n.agent??null,skill:n.agent?await Qo(e,n.agent):null},model_key:d,host_loopback:Fn(s),local_model:ue(l)??null,model_source:await Rt(e,t),agent_runtime:await Ac(e,t),telemetry:await oi(e,t,r)}}function ai(e){return`http://127.0.0.1:${e.port}`}async function nn(e,t){let n=await e.getJson(`${t}/v1/health`);return n?.status===200&&n.body?.status==="ok"}async function ci(e,t){let n=await e.getJson(`${t}/v1/bootstrap`);if(n?.status!==200)return[];return(n.body.workspaces??[]).filter((o)=>typeof o.id==="string"&&typeof o.name==="string").map((o)=>({id:o.id,name:o.name,mcp:`${t}/mcp/${o.id}`}))}function dr(e){return e.model_source.source!==null}function C_(e,t){let{env:n}=e;if(n.SSH_CONNECTION||n.SSH_TTY)return;if(e.platform==="darwin")return{cmd:"open",args:[t]};if(e.platform==="linux"&&(n.DISPLAY||n.WAYLAND_DISPLAY))return{cmd:"xdg-open",args:[t]};return}async function ui(e,t){let n=C_(e,t);if(!n)return!1;return e.launch(n.cmd,n.args)}async function Xc(e){let{deps:t,home:n}=e,r=await le(t,n),o=ai(r);if(!await nn(t,o))throw new x("NOT_RUNNING","NimbleBrain is not running.",{url:o});return{ok:!0,url:o,opened:await ui(t,o)}}var T_="https://github.com/NimbleBrainInc/nimblebrain.git/info/refs?service=git-upload-pack",A_=/^v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/,Qc="v0.73.0";async function li(e,t){let n=t??e.env.NIMBLEBRAIN_TAG,r;if(n){if(!A_.test(n))throw new x("USAGE",`"${n}" is not a runtime release tag like v1.2.3.`);r=n}else r=await di(e);if(lt(r,Qc)<0)throw new x("RUNTIME_UNSUPPORTED",`This CLI installs NimbleBrain ${Qc} or newer, not ${r}.`);return r}async function di(e,t=1e4){let n=await e.getText(T_,t);if(n&&n.status!==200)throw new x("NETWORK",`GitHub answered ${n.status} when asked for the newest NimbleBrain release. Pass --runtime vX.Y.Z to skip the lookup.`);let r=[...(n?.body??"").matchAll(/refs\/tags\/([^\s\0^]+)/g)].map((i)=>i[1]??""),o=R_(r);if(!o)throw new x("NETWORK","Could not find the newest NimbleBrain release.");return o}function R_(e){return e.filter((n)=>/^v\d+\.\d+\.\d+$/.test(n)).sort(lt).pop()}function lt(e,t){let[n="",r]=e.replace(/^v/,"").split(/-(.*)/s),[o="",i]=t.replace(/^v/,"").split(/-(.*)/s),s=eu(n.split("."),o.split("."));if(s!==0||!r&&!i)return s;if(!r||!i)return r?-1:1;return eu(r.split("."),i.split("."))}function eu(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=O_(e[n]??"",t[n]??"");if(r!==0)return r}return e.length-t.length}function O_(e,t){if(e===t)return 0;let n=/^\d+$/.test(e),r=/^\d+$/.test(t);if(n&&r)return Number(e)-Number(t);if(n!==r)return n?-1:1;return e<t?-1:1}var mi=900000,N_=180000,We=({deps:e,flags:t})=>e.interactive&&!t.yes&&!t.json,nu=(e)=>/^(y|yes)?$/i.test(e.trim());function dt(e,t){return async(n)=>{if(!We(e))return t;let r=n.startsWith("brew services")?" It then also starts at login.":"";return nu(await e.deps.prompt(`Ollama isn't running. Start it with \`${n}\`?${r} [Y/n] `))}}async function ru(e){let{deps:t,flags:n,home:r}=e,o=await ut(t,r);if(o?.phase==="ready")return{...await ke(t,r),already:!0};let i=await D_(e,o),s=await fu(t,r)?void 0:await Vc(t,r),a=lr(t,e.version,s??await tn(t,r)),l=Date.now();a.record("cli.init_started",{agent:n.agent??null,interactive:t.interactive});try{return await P_(e,await M_(e,o,i,a,l))}catch(d){if(!(d instanceof x))throw d;if(d.code!=="CANCELLED"||i!=="undecided")await L_(a,r,i,d);throw d.with({telemetry:ur(i,fe(t,r),Le(t))})}}async function P_(e,t){let{deps:n,flags:r}=e;if(!n.interactive||r.json||r.noOpen)return t;if(t.health!=="ok"||!dr(t))return t;return{...t,opened:await ui(n,t.url)}}async function L_(e,t,n,r){let o=typeof r.detail.check==="string"?r.detail.check:void 0;e.record(o?"cli.doctor_failed":"cli.init_failed",{error:r.code,check:o}),await e.settle(t,n)}async function D_(e,t){if(Le(e.deps))return"off";if(e.flags.telemetry)return e.flags.telemetry;if(t){let i=(await e.deps.readText(R(e.home).env)??"").match(/^NB_TELEMETRY_CONSENT=(on|off)\r?$/m)?.[1];if(i==="on"||i==="off")return i}if(!We(e))return"undecided";let n=Gc(await e.deps.prompt(`${ti} [Y/n] `)),r=fe(e.deps,e.home);return e.deps.say(n==="on"?`Sending anonymous usage data. Turn it off any time: ${r} telemetry off`:`No usage data will be sent. Turn it on any time: ${r} telemetry on`),n}async function M_(e,t,n,r,o){let{deps:i,flags:s,home:a}=e,l=s.port??t?.port??vt,d=t?.port===l&&await Vn(i,a);if(await qn(i,l,d),!t)await X_(i,a);let f=t&&!s.runtime?`v${t.version}`:await li(i,s.runtime),g=await Lo(i,f);await U_(e,f,l);let w={project:t?.project??cc(a),port:l,version:f.replace(/^v/,""),phase:"starting"};await pr(i,a,w),await pu(i,a,w.project,f,l,g,Kc(i,Le(i)?void 0:r.id,n,uc(g)));let{started:b,asked:z}=await W_(e,g);return rn(b,async()=>{let I=await q_(i,V_(g,f));i.say(I?`Starting NimbleBrain ${f}.`:`Starting NimbleBrain ${f}. The first start downloads about 2 GB of images.`),await De(i,a,l),w.phase="ready",await pr(i,a,w);let E=await Z_(e,w);if(w.agent)r.record("cli.agent_connected",{agent:w.agent});let A=await ke(i,a),X={...A,model_source:await j_(e,A.model_source,z,g),manual:E,ollama_started:b},Fe=await i.readText(R(a).env)??"";return r.record("cli.init_completed",{duration_ms:Date.now()-o,model_key:X.model_key,provider:ue(Fe)?"ollama":ot(Fe,g),model_source:X.model_source.source,agent:w.agent??null}),await r.settle(a,n),{...X}})}async function j_(e,t,n,r){if(t.source!==null||n)return t;let o=await e.deps.readText(R(e.home).env)??"",i=await en(e.deps,o,r);return{...t,...Zc(i,fe(e.deps,e.home))}}async function U_(e,t,n){if(!We(e))return;let r=await e.deps.prompt(`Start NimbleBrain ${t} at http://127.0.0.1:${n}? [Y/n] `);if(/^n/i.test(r))throw new x("CANCELLED","Nothing was installed.")}async function Z_(e,t){let{deps:n,flags:r,home:o}=e,i=r.agent??(We(e)?await F_(n):void 0);if(!i||i==="none")return;let s=(await ke(n,o)).workspaces[0];if(!s)return;let a=await Nc(n,i,s.mcp);if(a.connected)t.agent=a.connected,await Pc(n,a.connected),await pr(n,o,t);return a.manual}async function ou(e){let{deps:t,home:n}=e,r=await le(e.deps,n),i=ue(await t.readText(R(n).env)??"")?await nt(t,dt(e,!0)).catch((f)=>{if(f instanceof x)return f;throw f}):void 0,s=i instanceof x?i.detail.ollama_started:i?.started,a=await fi(Qt(t,n)),l=await rn(s,async()=>(await De(t,n,r.port),ke(t,n))),d=(f)=>f.with({...l},`NimbleBrain is running, but ${pi(f.message)}`);if(i instanceof x)throw d(i);if(a)throw d(a);return{...l,ollama_started:i?.started}}var pi=(e)=>e.charAt(0).toLowerCase()+e.slice(1);function fi(e){return e.then(()=>{return},(t)=>{if(t instanceof x)return t;throw t})}async function iu(e){if(await Nt(e.deps,e.home),await Pe(e.deps,e.home),!await Wt(e.deps,e.home))return{ok:!0,health:"down"};let t=await rt(e.deps,e.home,["down"]);if(t.code!==0)throw $t(t);return{ok:!0,health:"down"}}async function su(e){if(await Nt(e.deps,e.home),!await Wt(e.deps,e.home))return{ok:!0,lines:[]};let t=await rt(e.deps,e.home,["logs","--no-color","--tail","100","platform"]);if(t.code!==0)throw $t(t);return{ok:!0,lines:t.stdout.split(`
134
- `).filter((n)=>n.trim())}}async function au(e){let{deps:t,home:n}=e,r=await le(t,n),o=await li(t,e.flags.runtime),i=`v${r.version}`,s=lt(o,i);if(s===0){let w=await tu(t,r),b=await fi(Qt(t,n)),z={...await ke(t,n),already:!0,...w};if(b)throw b.with({...z},`NimbleBrain is current, but ${pi(b.message)}`);return z}if(s<0)throw new x("USAGE",`${o} is older than the installed ${i}; NimbleBrain does not move backwards.`);let a=await Lo(t,o);await pu(t,n,r.project,o,r.port,a),t.say(`Updating NimbleBrain ${i} → ${o}.`);let l=await rt(t,n,["pull"],mi);if(l.code!==0)throw $t(l);await De(t,n,r.port),await pr(t,n,{...r,version:o.replace(/^v/,"")});let d=await tu(t,r),f=await fi(Qt(t,n)),g={...await ke(t,n),from:i,...d};if(f)throw f.with({...g},`NimbleBrain was updated, but ${pi(f.message)}`);return g}async function tu(e,t){if(!t.agent||t.agent==="none")return{};return{skill_update:await Lc(e,t.agent)}}async function cu(e){let{deps:t,flags:n,home:r}=e,o=await Nt(t,r);if(!n.yes){if(!t.interactive||n.json)throw new x("CANCELLED","Removing deletes every conversation; pass --yes to confirm.");let s=await t.prompt("Remove NimbleBrain and every conversation in it? [y/N] ");if(!/^y/i.test(s))throw new x("CANCELLED","Nothing was removed.")}if(await Pe(t,r),await Wt(t,r)){let s=await rt(t,r,["down","-v","--rmi","all"],mi);if(s.code!==0)throw $t(s)}if(o.agent==="claude-code")await t.exec("claude",["mcp","remove","-s","user",me]);if(o.agent==="codex")await t.exec("codex",["mcp","remove",me]);let i=at(r);for(let s of[...Object.values(R(r)),ct(r),ar(r),i.record,i.log,i.bin,i.binDir])await t.remove(s);return await t.remove(r),{ok:!0,removed:!0}}async function uu(e){let{deps:t,home:n}=e,o=`http://127.0.0.1:${(await le(t,n)).port}`;if(e.arg!=="on"&&e.arg!=="off")return{ok:!0,telemetry:(await ke(t,n)).telemetry};let i=Le(t);if(i)throw new x("TELEMETRY_LOCKED",i==="do_not_track"?"DO_NOT_TRACK is set, so telemetry stays off.":"This CLI has nowhere to send telemetry.");if(!await ii(t,o))throw new x("NOT_RUNNING","NimbleBrain is not running, so it cannot record the answer.");await Jc(t,o,e.arg);let a=R(n);return await t.writeText(a.env,Re(await t.readText(a.env)??"",{NB_TELEMETRY_CONSENT:e.arg}),384),await lr(t,e.version,await tn(t,n)).settle(n,e.arg),{ok:!0,telemetry:ur(e.arg,fe(t,n))}}async function lu(e){if(await le(e.deps,e.home),!e.deps.interactive)throw new x("NEEDS_TERMINAL","`key` asks for a model key at a hidden prompt.");return fr(e,!0)}async function fr(e,t){let{deps:n,flags:r,home:o}=e,i=Mo(await n.readText(R(o).compose)??""),s=Object.keys(i),a=r.provider;if(n.say("NimbleBrain's own agents run on a model key you give it, billed by that provider."),!a)a=await n.prompt(`Model provider (${s.join(", ")}) [anthropic]: `)||"anthropic";let l=i[a];if(!l)throw new x("USAGE",`Unknown provider "${a}"; one of ${s.join(", ")}.`);let d=await n.prompt(`${l} (nothing is shown as you type): `,{hidden:!0});if(!d)throw new x("CANCELLED","No key was entered.");let f=R(o);if(await n.writeText(f.env,Re(await n.readText(f.env)??"",{[l]:d}),384),t){let g=await ut(n,o);await De(n,o,g?.port??vt)}return{ok:!0,provider:a,model_key:"set"}}async function du(e){let t=await le(e.deps,e.home),n=await e.deps.readText(R(e.home).compose)??"",r=e.arg??e.flags.localModel??tt,{name:o,started:i}=await mr(e,n,r);return await rn(i,()=>De(e.deps,e.home,t.port)),{ok:!0,local_model:o,ollama_started:i}}async function rn(e,t){try{return await t()}catch(n){if(n instanceof x&&e)throw n.with({ollama_started:e});throw n}}async function mr(e,t,n){let{deps:r,home:o}=e;if(!kt(t))throw new x("RUNTIME_UNSUPPORTED","This release's runtime takes no local model; a newer release does.");let{values:i,started:s}=await ic(r,n,{start:dt(e,!0),pull:(l)=>B_(e,l)}),a=R(o);return await r.writeText(a.env,Re(await r.readText(a.env)??"",i),384),{name:i.NB_LOCAL_MODEL??n,started:s}}async function B_(e,t){if(!We(e))return!0;return nu(await e.deps.prompt(`Download ${t} with Ollama? It is several GB. [Y/n] `))}async function F_(e){e.say("A coding agent you connect can use NimbleBrain's tools. NimbleBrain's own agents still run on what you chose above.");let t=await e.prompt(`Connect a coding agent? (${St.join(", ")}) [none]: `);return St.includes(t)?t:"none"}function V_(e,t){return[...e.matchAll(/^\s*image:\s*(\S+)/gm)].map((n)=>(n[1]??"").replace(/\$\{NIMBLEBRAIN_TAG(:-[^}]*)?\}/g,t))}async function q_(e,t){if(t.length===0)return!1;return(await e.exec("docker",["image","inspect",...t])).code===0}async function De(e,t,n){let r=await rt(e,t,["up","-d","--no-build"],mi);if(r.code!==0)throw await H_(e,t,$t(r));await G_(e,n)}async function H_(e,t,n){if(n.code!=="START_FAILED"||!/bind source path does not exist/i.test(n.message))return n;return await e.readText(R(t).instance)!==void 0?new x("HOME_NOT_SHARED",n.message):n}async function G_(e,t){let n=`http://127.0.0.1:${t}/v1/health`;for(let r=0;r<=N_;r+=2000){if((await e.getJson(n))?.status===200)return;await e.sleep(2000)}throw new x("HEALTH_TIMEOUT","NimbleBrain did not report healthy within 3 minutes.")}async function pu(e,t,n,r,o,i,s={}){let a=R(t);if(await e.writeText(a.compose,i),await e.readText(a.instance)===void 0)await e.writeText(a.instance,dc);let l=Re(await e.readText(a.env)??"",{COMPOSE_PROJECT_NAME:n,NIMBLEBRAIN_TAG:r,NIMBLEBRAIN_WEB_PORT:String(o),...s});await e.writeText(a.env,l,384)}async function W_(e,t){let n=await e.deps.readText(R(e.home).env)??"",r=ei(n,t),o=!e.flags.use&&r===null&&We(e),i=o?await K_(e,n,t):e.flags.use;if(!i)return{started:await Y_(e,r),asked:o};return{started:await J_(e,i,r,n,t),asked:o}}async function K_(e,t,n){let r=await en(e.deps,t,n);return r.some((o)=>o.available&&o.source!=="api")?ir(e.deps,r):"api"}async function J_(e,t,n,r,o){let{deps:i,flags:s,home:a}=e,l=n!==null&&n!==t;if(or(t)){await sr(i,a,t);return}if(t==="api"){if(!Oe(r,xe(o))&&i.interactive)await fr(e,!1);if(l)await Ot(i,a,!0);return}let d=s.localModel??tt;if(!s.localModel)i.say(`Using ${d}. Another model: ${fe(i,a)} use local <model>`);let{started:f}=await mr(e,o,d);if(l)await Ot(i,a,!1);return f}async function Y_(e,t){if(t==="local")return(await nt(e.deps,dt(e,!0))).started;if(t==="claude"||t==="codex")await Qt(e.deps,e.home);return}async function pr(e,t,n){await e.writeText(R(t).install,`${JSON.stringify(n,null,2)}
135
- `)}async function X_(e,t){let n=await fu(e,t);if(n)throw new x("NOT_OURS",`${n} already exists and this CLI did not write it.`)}async function fu(e,t){if(await ut(e,t))return;for(let n of Object.values(R(t)))if(await e.readText(n)!==void 0)return n;return}async function mu(e){let t=e.arg,n=await tb(e,t==="add");if(t==="add")return nb(n,e.operand??"",e.flags.name);if(t==="list")return rb(n);return ob(n,e.operand??"")}var Q_=["DIRECT_URL_NOT_ALLOWED","URL_NOT_LOOPBACK","URL_INVALID","INVALID_SERVER_NAME","NAME_TAKEN","NAME_IS_CATALOG_ENTRY"],eb=60000,hi=15000;async function tb(e,t){let{deps:n,home:r,flags:o}=e,i=await le(n,r);if(t&&!Fn(await n.readText(R(r).compose)??""))throw new x("UPDATE_REQUIRED",`NimbleBrain ${i.version} cannot reach a server on this machine.`,{version:i.version});let s=`http://127.0.0.1:${i.port}`;if(!await nn(n,s))throw new x("NOT_RUNNING","NimbleBrain is not running.");let a=await ci(n,s),l=o.workspace?a.find((d)=>d.id===o.workspace):a[0];if(!l)throw new x("WORKSPACE_NOT_FOUND",o.workspace?`No workspace "${o.workspace}" on this install.`:"This install has no workspace.",{workspaces:a.map((d)=>d.id)});return{ctx:e,url:s,wsId:l.id}}async function nb(e,t,n){let r=URL.canParse(t)?new URL(t).protocol:"";if(r!=="http:"&&r!=="https:")throw new x("URL_INVALID",`"${t}" is not an http or https URL.`);let o={kind:"direct-url",url:t,...n?{serverName:n}:{}},i=await hr(e,{action:"install",entry:{id:"direct-url",name:n??t,install:o}},eb);return{ok:!0,serverName:i.serverName,url:i.url,dialed:i.dialed,placements:i.placements,wsId:i.wsId??e.wsId,...i.warning?{warning:i.warning}:{},...i.notice?{notice:i.notice}:{}}}async function rb(e){let t=await hr(e,{action:"list_installed",scope:"workspace"},hi),r=(Array.isArray(t.installed)?t.installed:[]).map((o)=>({serverName:o.serverName,displayName:o.displayName,url:o.url,state:o.state,status:o.status,statusReason:o.statusReason,toolCount:o.toolCount}));return{ok:!0,wsId:e.wsId,servers:r}}async function ob(e,t){let n=await hr(e,{action:"list_installed",scope:"workspace"},hi);if(!(Array.isArray(n.installed)?n.installed:[]).some((o)=>o.serverName===t))throw new x("SERVER_NOT_FOUND",`This workspace has no server named "${t}".`,{wsId:e.wsId});return await hr(e,{action:"uninstall",serverName:t},hi),{ok:!0,serverName:t,wsId:e.wsId}}async function hr(e,t,n){let r=await e.ctx.deps.postJson(`${e.url}/v1/workspaces/${encodeURIComponent(e.wsId)}/tools/call`,{server:"nb",tool:"manage_connectors",arguments:t},n);if(!r)throw new x("NOT_RUNNING","NimbleBrain did not answer.");let o=r.body??{};if(r.status===404&&o.error==="workspace_error")throw new x("WORKSPACE_NOT_FOUND",`No workspace "${e.wsId}" on this install.`);if(r.status<200||r.status>=300){let s=typeof o.message==="string"?o.message:`HTTP ${r.status}`;throw new x("REQUEST_FAILED",`NimbleBrain refused the request: ${s}`,{status:r.status})}let i=o.content?.find((s)=>s.type==="text")?.text;if(o.isError){let s=o.structuredContent?.error,a=Q_.find((l)=>l===s);throw new x(a??"REQUEST_FAILED",i??"NimbleBrain refused the request.")}return o.structuredContent??{}}import{join as hu}from"node:path";var ib="https://registry.npmjs.org/nimblebrain/latest",sb=86400000,gu=5000,wu=1000,ab=/^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function _u(e){let t=e.env.XDG_CACHE_HOME?.trim(),n=t?.startsWith("/")?t:hu(e.home,".cache");return hu(n,"nimblebrain","update-check.json")}function cb(e){let t=e.env.CI?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="false"&&t!=="0"||e.env.NIMBLEBRAIN_NO_UPDATE_CHECK==="1"||ri(e)}function bu(e){if(cb(e))return;let t=ub(e),n=!1,r=t.then(async(o)=>{if(o&&Date.now()-o.checked_at<sb)return o;return await lb(e,o)??o});return r.then(()=>{n=!0}),{async known(o){let i=await t;if(n)return r;let s=o>0?e.sleep(o).then(()=>i):Promise.resolve(i);return Promise.race([r,s])}}}async function ub(e){try{let t=JSON.parse(await e.readText(_u(e))??"null");if(typeof t?.checked_at!=="number")return;return{checked_at:t.checked_at,cli:gi(t.cli),runtime:gi(t.runtime)}}catch{return}}async function lb(e,t){try{let[n,r]=await Promise.all([e.getJson(ib,gu),di(e,gu).catch(()=>{return})]),o=n?.status===200?gi(n.body?.version):void 0;if(!o&&!r)return;let i={checked_at:Date.now(),cli:o??t?.cli,runtime:r??t?.runtime};return await e.writeText(_u(e),`${JSON.stringify(i)}
136
- `),i}catch{return}}function gi(e){return typeof e==="string"&&ab.test(e)?e:void 0}function wi(e,t,n){let r={};if(e?.cli)r.cli={current:t,latest:e.cli};if(e?.runtime&&n)r.runtime={current:n,latest:e.runtime.replace(/^v/,"")};return r.cli||r.runtime?r:void 0}function yu(e,t,n="npx nimblebrain"){let r=[],o=e?.cli;if(o&&lt(o.latest,o.current)>0)r.push(`nimblebrain ${o.latest} is available (you have ${o.current}): npx nimblebrain@latest`);let i=e?.runtime;if(t&&i&&lt(i.latest,i.current)>0)r.push(`NimbleBrain v${i.latest} is available (you have v${i.current}): ${n} update`);return r}Tt();async function zu(e){let{deps:t,home:n}=e,r=e.arg===void 0?void 0:db(e.arg);if(e.operand!==void 0&&r!=="local")throw new x("USAGE",`Only use local takes a model, not "${e.operand}".`);if(r===void 0&&!We(e))throw Bc();let o=await le(t,n),i=r??await pb(e);if(or(i))return fb(e,i,o.port);if(i==="api")return mb(e,o.port);return hb(e,o.port)}function db(e){if(He.includes(e))return e;throw new x("USAGE",`use takes ${Gt}, not "${e}".`)}async function pb(e){let t=R(e.home),n=await e.deps.readText(t.env)??"",r=await e.deps.readText(t.compose)??"";return ir(e.deps,await en(e.deps,n,r))}async function fb(e,t,n){let{worker:r,account:o,runtime:i}=await sr(e.deps,e.home,t,e.flags.port);return await De(e.deps,e.home,n),{ok:!0,model_source:await Rt(e.deps,e.home),agent_runtime:{name:i,worker:r},billed_to:o.describe,tools:Yn[i]}}async function mb(e,t){let{deps:n,home:r}=e,o=R(r),i=await n.readText(o.compose)??"";if(!Oe(await n.readText(o.env)??"",xe(i))){if(!n.interactive)throw new x("MODEL_KEY_MISSING","This install has no model key, and `key` asks for one at a hidden prompt.");await fr(e,!1)}return await Ot(n,r,!0),await De(n,r,t),{ok:!0,model_source:await Rt(n,r),agent_runtime:{name:"native",worker:null},provider:ot(await n.readText(o.env)??"",i)}}async function hb(e,t){let{deps:n,home:r}=e,o=R(r),i=ue(await n.readText(o.env)??""),s=await n.readText(o.compose)??"",{name:a,started:l}=e.operand===void 0&&i?{name:i,started:(await nt(n,dt(e,!0))).started}:await mr(e,s,e.operand??tt);return await rn(l,async()=>{await Ot(n,r,!1),await De(n,r,t)}),{ok:!0,model_source:await Rt(n,r),agent_runtime:{name:"native",worker:null},local_model:a,ollama_started:l}}var gb=["status","up","init"];async function ku(e,t){let n=Po(e),r;try{r=No(e)}catch(w){return Pt(xu(w),n,Ve)}if(r.kind==="help")return r.flags.json?Pt(hc(he),!0,Ve):{stdout:gc(he),code:0};if(r.kind==="version")return r.flags.json?Pt({ok:!0,version:he},!0,Ve):{stdout:`${he}
137
- `,code:0};let{command:o,flags:i,arg:s,operand:a}=r,l=bu(t),d=Ln(t,i.home),f=fe(t,d),g;try{switch(o){case"doctor":{let w=await ut(t,d),b=i.port??w?.port??vt,z=w?.port===b&&await Vn(t,d),I=dt({deps:t,flags:i},!1);g={...await bb(t,d,b,z,I)};break}case"status":g={...await ke(t,d)};break;default:{let w={deps:t,flags:i,home:d,version:he,arg:s,operand:a};g=await{init:ru,up:ou,down:iu,logs:su,update:au,uninstall:cu,key:lu,telemetry:uu,"local-model":du,use:zu,mcp:mu,open:Xc}[o](w)}}}catch(w){g=xu(w)}if(!g.ok)g={...g,fix:To(g.fix,f)};if(!["init","telemetry","uninstall","doctor"].includes(o))await Wc(t,d,he);return wb(g,o,i.json,l,f)}async function wb(e,t,n,r,o){if(!r)return Pt(e,n,o,t);let i=_b(e)?e.version:void 0,s=wi(await r.known(0),he,i);return{...Pt(s&&i!==void 0?{...e,updates:s}:e,n,o,t),notices:async()=>{let d=await r.known(wu);if(n)return;let f=yu(wi(d,he,i),gb.includes(t),o);return f.length>0?`${f.join(`
134
+ `;function pu(e){return/^n/i.test(e.trim())?"off":"on"}function rb(e){let t=e.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];return t==="on"||t==="off"?t:"undecided"}async function gi(e,t,n){let r=Me(e),o=await wi(e,n),i=o?.consent??rb(await e.readText(mr(t,".env"))??""),s=r??(o?.locked==="operator"||o?.locked==="no_destination"?o.locked:void 0);return hr(i,me(e,t),s)}async function mu(e,t,n){try{let r=await un(e,t);if(!r)return;let o=JSON.parse(await e.readText(mr(t,"install.json"))??"{}");if(typeof o.port!=="number")return;let i=await gi(e,t,`http://127.0.0.1:${o.port}`);await gr(e,n,r).settle(t,i.locked?"off":i.state)}catch{}}function hu(e,t,n,r){let o={NB_TELEMETRY_KEY:r?mi(e):""};if(t)o.NB_TELEMETRY_ID=t;if(n!=="undecided")o.NB_TELEMETRY_CONSENT=n;return o}async function wi(e,t){let r=(await e.postJson(`${t}/v1/tools/call`,{server:"nb",tool:"workspace_info",arguments:{}}))?.body?.structuredContent?.telemetry;if(r?.consent!=="on"&&r?.consent!=="off"&&r?.consent!=="undecided")return;return{consent:r.consent,locked:typeof r.locked==="string"?r.locked:void 0}}async function gu(e,t,n){let r=await e.postJson(`${t}/v1/tools/call`,{server:"nb",tool:"set_telemetry",arguments:{consent:n}}),o=r?.body;if(!r||r.status>=300||o?.isError)throw new x("TELEMETRY_LOCKED",o?.content?.[0]?.text??"NimbleBrain did not accept the answer.")}var wu={name:"nimblebrain",version:"0.9.0-beta.2",description:"Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",license:"Apache-2.0",type:"module",repository:{type:"git",url:"git+https://github.com/NimbleBrainInc/nimblebrain.git",directory:"packages/cli"},homepage:"https://nimblebrain.ai/developers",bin:{nimblebrain:"dist/nimblebrain.js"},files:["dist"],engines:{node:">=20"},scripts:{build:"bun build src/bin.ts --target=node --minify --outfile=dist/nimblebrain.js --banner='#!/usr/bin/env node'","build:release":"bun run build --define NIMBLEBRAIN_CLI_RELEASE=true",test:"bun test --no-env-file test/"},devDependencies:{"@agentclientprotocol/sdk":"2.4.0",zod:"^4.6.6"}};var he=wu.version;async function pt(e,t){let n=await e.readText(_i(t,"install.json"));if(n===void 0)return;try{let r=JSON.parse(n);if(typeof r?.version!=="string"||typeof r.port!=="number"||typeof r.project!=="string"||r.phase!=="starting"&&r.phase!=="ready")return;if(r.serverName!==void 0&&typeof r.serverName!=="string")delete r.serverName;return r}catch{return}}async function Ut(e,t){let n=await pt(e,t);if(!n)throw new x("NOT_INSTALLED",`No NimbleBrain install in ${t}.`);return n}async function de(e,t){let n=await Ut(e,t);if(n.phase!=="ready")throw new x("INSTALL_INCOMPLETE",`The NimbleBrain install in ${t} has not finished installing.`);return n}async function ke(e,t){let n=await Ut(e,t),r=bi(n),o=await ln(e,r),i=o&&n.phase==="ready"?await yi(e,r):[],s=await e.readText(_i(t,"docker-compose.yml"))??"",a=ze(s),u=await e.readText(_i(t,".env"))??"",d=Ne(u,a)?"set":"missing";return{ok:!0,version:n.version,phase:n.phase,cli_version:he,health:o?"ok":"down",url:r,workspaces:i,agent:{connected:n.agent??null,server:n.agent?Yt(n):null,skill:n.agent?await Fo(e,n.agent):null},model_key:d,host_loopback:Qn(s),local_model:le(u)??null,model_source:await Dt(e,t),agent_runtime:await eu(e,t),telemetry:await gi(e,t,r)}}function bi(e){return`http://127.0.0.1:${e.port}`}async function ln(e,t){let n=await e.getJson(`${t}/v1/health`);return n?.status===200&&n.body?.status==="ok"}async function yi(e,t){let n=await e.getJson(`${t}/v1/bootstrap`);if(n?.status!==200)return[];return(n.body.workspaces??[]).filter((o)=>typeof o.id==="string"&&typeof o.name==="string").map((o)=>({id:o.id,name:o.name,mcp:`${t}/mcp/${o.id}`}))}function wr(e){return e.model_source.source!==null}function ib(e,t){let{env:n}=e;if(n.SSH_CONNECTION||n.SSH_TTY)return;if(e.platform==="darwin")return{cmd:"open",args:[t]};if(e.platform==="linux"&&(n.DISPLAY||n.WAYLAND_DISPLAY))return{cmd:"xdg-open",args:[t]};return}async function zi(e,t){let n=ib(e,t);if(!n)return!1;return e.launch(n.cmd,n.args)}async function _u(e){let{deps:t,home:n}=e,r=await de(t,n),o=bi(r);if(!await ln(t,o))throw new x("NOT_RUNNING","NimbleBrain is not running.",{url:o});return{ok:!0,url:o,opened:await zi(t,o)}}var sb="https://github.com/NimbleBrainInc/nimblebrain.git/info/refs?service=git-upload-pack",ab=/^v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/,bu="v0.73.0";async function xi(e,t){let n=t??e.env.NIMBLEBRAIN_TAG,r;if(n){if(!ab.test(n))throw new x("USAGE",`"${n}" is not a runtime release tag like v1.2.3.`);r=n}else r=await ki(e);if(mt(r,bu)<0)throw new x("RUNTIME_UNSUPPORTED",`This CLI installs NimbleBrain ${bu} or newer, not ${r}.`);return r}async function ki(e,t=1e4){let n=await e.getText(sb,t);if(n&&n.status!==200)throw new x("NETWORK",`GitHub answered ${n.status} when asked for the newest NimbleBrain release. Pass --runtime vX.Y.Z to skip the lookup.`);let r=[...(n?.body??"").matchAll(/refs\/tags\/([^\s\0^]+)/g)].map((i)=>i[1]??""),o=cb(r);if(!o)throw new x("NETWORK","Could not find the newest NimbleBrain release.");return o}function cb(e){return e.filter((n)=>/^v\d+\.\d+\.\d+$/.test(n)).sort(mt).pop()}function mt(e,t){let[n="",r]=e.replace(/^v/,"").split(/-(.*)/s),[o="",i]=t.replace(/^v/,"").split(/-(.*)/s),s=yu(n.split("."),o.split("."));if(s!==0||!r&&!i)return s;if(!r||!i)return r?-1:1;return yu(r.split("."),i.split("."))}function yu(e,t){for(let n=0;n<Math.min(e.length,t.length);n++){let r=ub(e[n]??"",t[n]??"");if(r!==0)return r}return e.length-t.length}function ub(e,t){if(e===t)return 0;let n=/^\d+$/.test(e),r=/^\d+$/.test(t);if(n&&r)return Number(e)-Number(t);if(n!==r)return n?-1:1;return e<t?-1:1}var $i=900000,lb=180000,We=({deps:e,flags:t})=>e.interactive&&!t.yes&&!t.json,xu=(e)=>/^(y|yes)?$/i.test(e.trim());function ht(e,t){return async(n)=>{if(!We(e))return t;let r=n.startsWith("brew services")?" It then also starts at login.":"";return xu(await e.deps.prompt(`Ollama isn't running. Start it with \`${n}\`?${r} [Y/n] `))}}async function ku(e){let{deps:t,flags:n,home:r}=e;cn(n.model,n.use);let o=await pt(t,r);if(o?.phase==="ready")return{...await ke(t,r),already:!0};let i=await pb(e,o),s=await Ou(t,r)?void 0:await lu(t,r),a=gr(t,e.version,s??await un(t,r)),u=Date.now();a.record("cli.init_started",{agent:n.agent??null,interactive:t.interactive});try{return await db(e,await mb(e,o,i,a,u))}catch(d){if(!(d instanceof x))throw d;if(d.code!=="CANCELLED"||i!=="undecided")await fb(a,r,i,d);throw d.with({telemetry:hr(i,me(t,r),Me(t))})}}async function db(e,t){let{deps:n,flags:r}=e;if(!n.interactive||r.json||r.noOpen)return t;if(t.health!=="ok"||!wr(t))return t;return{...t,opened:await zi(n,t.url)}}async function fb(e,t,n,r){let o=typeof r.detail.check==="string"?r.detail.check:void 0;e.record(o?"cli.doctor_failed":"cli.init_failed",{error:r.code,check:o}),await e.settle(t,n)}async function pb(e,t){if(Me(e.deps))return"off";if(e.flags.telemetry)return e.flags.telemetry;if(t){let i=(await e.deps.readText(R(e.home).env)??"").match(/^NB_TELEMETRY_CONSENT=(on|off)\r?$/m)?.[1];if(i==="on"||i==="off")return i}if(!We(e))return"undecided";let n=pu(await e.deps.prompt(`${pi} [Y/n] `)),r=me(e.deps,e.home);return e.deps.say(n==="on"?`Sending anonymous usage data. Turn it off any time: ${r} telemetry off`:`No usage data will be sent. Turn it on any time: ${r} telemetry on`),n}async function mb(e,t,n,r,o){let{deps:i,flags:s,home:a}=e,u=s.port??t?.port??Rt,d=t?.port===u&&await er(i,a),p=!t&&s.port===void 0,{port_moved:g}=await tr(i,u,d,p?a:void 0),w=g?.to??u;if(!t)await Ib(i,a);let b=t&&!s.runtime?`v${t.version}`:await xi(i,s.runtime),z=await Wo(i,b);if(g)i.say(Hn(i,g,"this install"));await gb(e,b,w);let I=t?.project??Rc(a),k={project:I,port:w,version:b.replace(/^v/,""),phase:"starting",serverName:t?.serverName??await yc(i,a,I)};await _r(i,a,k),await Ru(i,a,k.project,b,w,z,hu(i,Me(i)?void 0:r.id,n,Oc(z)));let{started:A,asked:ne}=await Sb(e,z);return dn(A,async()=>{let tt=await zb(i,yb(z,b));i.say(tt?`Starting NimbleBrain ${b}.`:`Starting NimbleBrain ${b}. The first start downloads about 2 GB of images.`),await De(i,a,w),k.phase="ready",await _r(i,a,k);let nt=await wb(e,k);if(k.agent)r.record("cli.agent_connected",{agent:k.agent});let V=await ke(i,a),M={...V,model_source:await hb(e,V.model_source,ne,z),manual:nt,ollama_started:A,port_moved:g},se=await i.readText(R(a).env)??"";return r.record("cli.init_completed",{duration_ms:Date.now()-o,model_key:M.model_key,provider:le(se)?"ollama":lt(se,z),model_source:M.model_source.source,agent:k.agent??null}),await r.settle(a,n),{...M}})}async function hb(e,t,n,r){if(t.source!==null||n)return t;let o=await e.deps.readText(R(e.home).env)??"",i=await an(e.deps,o,r);return{...t,...au(i,me(e.deps,e.home))}}async function gb(e,t,n){if(!We(e))return;let r=await e.deps.prompt(`Start NimbleBrain ${t} at http://127.0.0.1:${n}? [Y/n] `);if(/^n/i.test(r))throw new x("CANCELLED","Nothing was installed.")}async function wb(e,t){let{deps:n,flags:r,home:o}=e,i=r.agent??(We(e)?await bb(n):void 0);if(!i||i==="none")return;let s=(await ke(n,o)).workspaces[0];if(!s)return;let a=await zc(n,i,s.mcp,{name:Yt(t),fallback:t.project});if(a.connected)t.agent=a.connected,t.serverName=a.name,await kc(n,a.connected),await _r(n,o,t);return a.manual}async function Su(e){let{deps:t,home:n}=e,r=await de(e.deps,n),i=le(await t.readText(R(n).env)??"")?await st(t,ht(e,!0)).catch((p)=>{if(p instanceof x)return p;throw p}):void 0,s=i instanceof x?i.detail.ollama_started:i?.started,a=await vi(sn(t,n)),u=await dn(s,async()=>(await De(t,n,r.port),ke(t,n))),d=(p)=>p.with({...u},`NimbleBrain is running, but ${Si(p.message)}`);if(i instanceof x)throw d(i);if(a)throw d(a);return{...u,ollama_started:i?.started}}var Si=(e)=>e.charAt(0).toLowerCase()+e.slice(1);function vi(e){return e.then(()=>{return},(t)=>{if(t instanceof x)return t;throw t})}async function vu(e){if(await Ut(e.deps,e.home),await Le(e.deps,e.home),!await en(e.deps,e.home))return{ok:!0,health:"down"};let t=await ut(e.deps,e.home,["down"]);if(t.code!==0)throw Ot(t);return{ok:!0,health:"down"}}async function $u(e){if(await Ut(e.deps,e.home),!await en(e.deps,e.home))return{ok:!0,lines:[]};let t=await ut(e.deps,e.home,["logs","--no-color","--tail","100","platform"]);if(t.code!==0)throw Ot(t);return{ok:!0,lines:t.stdout.split(`
135
+ `).filter((n)=>n.trim())}}async function Eu(e){let{deps:t,home:n}=e,r=await de(t,n),o=await xi(t,e.flags.runtime),i=`v${r.version}`,s=mt(o,i);if(s===0){let w=await zu(t,r),b=await vi(sn(t,n)),z={...await ke(t,n),already:!0,...w};if(b)throw b.with({...z},`NimbleBrain is current, but ${Si(b.message)}`);return z}if(s<0)throw new x("USAGE",`${o} is older than the installed ${i}; NimbleBrain does not move backwards.`);let a=await Wo(t,o);await Ru(t,n,r.project,o,r.port,a),t.say(`Updating NimbleBrain ${i} → ${o}.`);let u=await ut(t,n,["pull"],$i);if(u.code!==0)throw Ot(u);await De(t,n,r.port),await _r(t,n,{...r,version:o.replace(/^v/,"")});let d=await zu(t,r),p=await vi(sn(t,n)),g={...await ke(t,n),from:i,...d};if(p)throw p.with({...g},`NimbleBrain was updated, but ${Si(p.message)}`);return g}async function zu(e,t){if(!t.agent||t.agent==="none")return{};return{skill_update:await Sc(e,t.agent)}}async function Iu(e){let{deps:t,flags:n,home:r}=e,o=await Ut(t,r);if(!n.yes){if(!t.interactive||n.json)throw new x("CANCELLED","Removing deletes every conversation; pass --yes to confirm.");let s=await t.prompt("Remove NimbleBrain and every conversation in it? [y/N] ");if(!/^y/i.test(s))throw new x("CANCELLED","Nothing was removed.")}if(await Le(t,r),await en(t,r)){let s=await ut(t,r,["down","-v","--rmi","all"],$i);if(s.code!==0)throw Ot(s)}if(o.agent)await xc(t,o.agent,Yt(o));let i=dt(r);for(let s of[...Object.values(R(r)),ft(r),pr(r),i.record,i.log,i.bin,i.binDir])await t.remove(s);return await t.remove(r),{ok:!0,removed:!0}}async function Cu(e){let{deps:t,home:n}=e,o=`http://127.0.0.1:${(await de(t,n)).port}`;if(e.arg!=="on"&&e.arg!=="off")return{ok:!0,telemetry:(await ke(t,n)).telemetry};let i=Me(t);if(i)throw new x("TELEMETRY_LOCKED",i==="do_not_track"?"DO_NOT_TRACK is set, so telemetry stays off.":"This CLI has nowhere to send telemetry.");if(!await wi(t,o))throw new x("NOT_RUNNING","NimbleBrain is not running, so it cannot record the answer.");await gu(t,o,e.arg);let a=R(n);return await t.writeText(a.env,Oe(await t.readText(a.env)??"",{NB_TELEMETRY_CONSENT:e.arg}),384),await gr(t,e.version,await un(t,n)).settle(n,e.arg),{ok:!0,telemetry:hr(e.arg,me(t,n))}}async function Tu(e){if(await de(e.deps,e.home),!e.deps.interactive)throw new x("NEEDS_TERMINAL","`key` asks for a model key at a hidden prompt.");return br(e,!0)}async function br(e,t){let{deps:n,flags:r,home:o}=e,i=Jo(await n.readText(R(o).compose)??""),s=Object.keys(i),a=r.provider;if(n.say("NimbleBrain's own agents run on a model key you give it, billed by that provider."),!a)a=await n.prompt(`Model provider (${s.join(", ")}) [anthropic]: `)||"anthropic";let u=i[a];if(!u)throw new x("USAGE",`Unknown provider "${a}"; one of ${s.join(", ")}.`);let d=await n.prompt(`${u} (nothing is shown as you type): `,{hidden:!0});if(!d)throw new x("CANCELLED","No key was entered.");let p=R(o);if(await n.writeText(p.env,Oe(await n.readText(p.env)??"",{[u]:d}),384),t){let g=await pt(n,o);await De(n,o,g?.port??Rt)}return{ok:!0,provider:a,model_key:"set"}}async function Au(e){let t=await de(e.deps,e.home),n=await e.deps.readText(R(e.home).compose)??"",r=e.arg??e.flags.localModel??it,{name:o,started:i}=await yr(e,n,r);return await dn(i,()=>De(e.deps,e.home,t.port)),{ok:!0,local_model:o,ollama_started:i}}async function dn(e,t){try{return await t()}catch(n){if(n instanceof x&&e)throw n.with({ollama_started:e});throw n}}async function yr(e,t,n){let{deps:r,home:o}=e;if(!Ct(t))throw new x("RUNTIME_UNSUPPORTED","This release's runtime takes no local model; a newer release does.");let{values:i,started:s}=await Ec(r,n,{start:ht(e,!0),pull:(u)=>_b(e,u)}),a=R(o);return await r.writeText(a.env,Oe(await r.readText(a.env)??"",i),384),{name:i.NB_LOCAL_MODEL??n,started:s}}async function _b(e,t){if(!We(e))return!0;return xu(await e.deps.prompt(`Download ${t} with Ollama? It is several GB. [Y/n] `))}async function bb(e){e.say("A coding agent you connect can use NimbleBrain's tools. NimbleBrain's own agents still run on what you chose above.");let t=await e.prompt(`Connect a coding agent? (${At.join(", ")}) [none]: `);return At.includes(t)?t:"none"}function yb(e,t){return[...e.matchAll(/^\s*image:\s*(\S+)/gm)].map((n)=>(n[1]??"").replace(/\$\{NIMBLEBRAIN_TAG(:-[^}]*)?\}/g,t))}async function zb(e,t){if(t.length===0)return!1;return(await e.exec("docker",["image","inspect",...t])).code===0}async function De(e,t,n){let r=await ut(e,t,["up","-d","--no-build"],$i);if(r.code!==0)throw await xb(e,t,Ot(r));await kb(e,n)}async function xb(e,t,n){if(n.code!=="START_FAILED"||!/bind source path does not exist/i.test(n.message))return n;return await e.readText(R(t).instance)!==void 0?new x("HOME_NOT_SHARED",n.message):n}async function kb(e,t){let n=`http://127.0.0.1:${t}/v1/health`;for(let r=0;r<=lb;r+=2000){if((await e.getJson(n))?.status===200)return;await e.sleep(2000)}throw new x("HEALTH_TIMEOUT","NimbleBrain did not report healthy within 3 minutes.")}async function Ru(e,t,n,r,o,i,s={}){let a=R(t);if(await e.writeText(a.compose,i),await e.readText(a.instance)===void 0)await e.writeText(a.instance,Pc);let u=Oe(await e.readText(a.env)??"",{COMPOSE_PROJECT_NAME:n,NIMBLEBRAIN_TAG:r,NIMBLEBRAIN_WEB_PORT:String(o),...s});await e.writeText(a.env,u,384)}async function Sb(e,t){let n=await e.deps.readText(R(e.home).env)??"",r=fi(n,t),o=!e.flags.use&&r===null&&We(e),i=o?await vb(e,n,t):e.flags.use;if(!i)return{started:await Eb(e,r),asked:o};return{started:await $b(e,i,r,n,t),asked:o}}async function vb(e,t,n){let r=await an(e.deps,t,n);return r.some((o)=>o.available&&o.source!=="api")?dr(e.deps,r):"api"}async function $b(e,t,n,r,o){let{deps:i,flags:s,home:a}=e,u=n!==null&&n!==t;if(Mt(t)){await fr(i,a,t,void 0,s.model);return}if(t==="api"){if(!Ne(r,ze(o))&&i.interactive)await br(e,!1);if(u)await jt(i,a,!0);return}let d=s.localModel??it;if(!s.localModel)i.say(`Using ${d}. Another model: ${me(i,a)} use local <model>`);let{started:p}=await yr(e,o,d);if(u)await jt(i,a,!1);return p}async function Eb(e,t){if(t==="local")return(await st(e.deps,ht(e,!0))).started;if(t==="claude"||t==="codex")await sn(e.deps,e.home);return}async function _r(e,t,n){await e.writeText(R(t).install,`${JSON.stringify(n,null,2)}
136
+ `)}async function Ib(e,t){let n=await Ou(e,t);if(n)throw new x("NOT_OURS",`${n} already exists and this CLI did not write it.`)}async function Ou(e,t){if(await pt(e,t))return;for(let n of Object.values(R(t)))if(await e.readText(n)!==void 0)return n;return}async function Nu(e){let t=e.arg,n=await Ab(e,t==="add");if(t==="add")return Rb(n,e.operand??"",e.flags.name);if(t==="list")return Ob(n);return Nb(n,e.operand??"")}var Cb=["DIRECT_URL_NOT_ALLOWED","URL_NOT_LOOPBACK","URL_INVALID","INVALID_SERVER_NAME","NAME_TAKEN","NAME_IS_CATALOG_ENTRY"],Tb=60000,Ei=15000;async function Ab(e,t){let{deps:n,home:r,flags:o}=e,i=await de(n,r);if(t&&!Qn(await n.readText(R(r).compose)??""))throw new x("UPDATE_REQUIRED",`NimbleBrain ${i.version} cannot reach a server on this machine.`,{version:i.version});let s=`http://127.0.0.1:${i.port}`;if(!await ln(n,s))throw new x("NOT_RUNNING","NimbleBrain is not running.");let a=await yi(n,s),u=o.workspace?a.find((d)=>d.id===o.workspace):a[0];if(!u)throw new x("WORKSPACE_NOT_FOUND",o.workspace?`No workspace "${o.workspace}" on this install.`:"This install has no workspace.",{workspaces:a.map((d)=>d.id)});return{ctx:e,url:s,wsId:u.id}}async function Rb(e,t,n){let r=URL.canParse(t)?new URL(t).protocol:"";if(r!=="http:"&&r!=="https:")throw new x("URL_INVALID",`"${t}" is not an http or https URL.`);let o={kind:"direct-url",url:t,...n?{serverName:n}:{}},i=await zr(e,{action:"install",entry:{id:"direct-url",name:n??t,install:o}},Tb);return{ok:!0,serverName:i.serverName,url:i.url,dialed:i.dialed,placements:i.placements,wsId:i.wsId??e.wsId,...i.warning?{warning:i.warning}:{},...i.notice?{notice:i.notice}:{}}}async function Ob(e){let t=await zr(e,{action:"list_installed",scope:"workspace"},Ei),r=(Array.isArray(t.installed)?t.installed:[]).map((o)=>({serverName:o.serverName,displayName:o.displayName,url:o.url,state:o.state,status:o.status,statusReason:o.statusReason,toolCount:o.toolCount}));return{ok:!0,wsId:e.wsId,servers:r}}async function Nb(e,t){let n=await zr(e,{action:"list_installed",scope:"workspace"},Ei);if(!(Array.isArray(n.installed)?n.installed:[]).some((o)=>o.serverName===t))throw new x("SERVER_NOT_FOUND",`This workspace has no server named "${t}".`,{wsId:e.wsId});return await zr(e,{action:"uninstall",serverName:t},Ei),{ok:!0,serverName:t,wsId:e.wsId}}async function zr(e,t,n){let r=await e.ctx.deps.postJson(`${e.url}/v1/workspaces/${encodeURIComponent(e.wsId)}/tools/call`,{server:"nb",tool:"manage_connectors",arguments:t},n);if(!r)throw new x("NOT_RUNNING","NimbleBrain did not answer.");let o=r.body??{};if(r.status===404&&o.error==="workspace_error")throw new x("WORKSPACE_NOT_FOUND",`No workspace "${e.wsId}" on this install.`);if(r.status<200||r.status>=300){let s=typeof o.message==="string"?o.message:`HTTP ${r.status}`;throw new x("REQUEST_FAILED",`NimbleBrain refused the request: ${s}`,{status:r.status})}let i=o.content?.find((s)=>s.type==="text")?.text;if(o.isError){let s=o.structuredContent?.error,a=Cb.find((u)=>u===s);throw new x(a??"REQUEST_FAILED",i??"NimbleBrain refused the request.")}return o.structuredContent??{}}import{join as Pu}from"node:path";var Pb="https://registry.npmjs.org/nimblebrain/latest",Lb=86400000,Lu=5000,Mu=1000,Mb=/^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;function Du(e){let t=e.env.XDG_CACHE_HOME?.trim(),n=t?.startsWith("/")?t:Pu(e.home,".cache");return Pu(n,"nimblebrain","update-check.json")}function Db(e){let t=e.env.CI?.trim().toLowerCase();return t!==void 0&&t!==""&&t!=="false"&&t!=="0"||e.env.NIMBLEBRAIN_NO_UPDATE_CHECK==="1"||hi(e)}function ju(e){if(Db(e))return;let t=jb(e),n=!1,r=t.then(async(o)=>{if(o&&Date.now()-o.checked_at<Lb)return o;return await Ub(e,o)??o});return r.then(()=>{n=!0}),{async known(o){let i=await t;if(n)return r;let s=o>0?e.sleep(o).then(()=>i):Promise.resolve(i);return Promise.race([r,s])}}}async function jb(e){try{let t=JSON.parse(await e.readText(Du(e))??"null");if(typeof t?.checked_at!=="number")return;return{checked_at:t.checked_at,cli:Ii(t.cli),runtime:Ii(t.runtime)}}catch{return}}async function Ub(e,t){try{let[n,r]=await Promise.all([e.getJson(Pb,Lu),ki(e,Lu).catch(()=>{return})]),o=n?.status===200?Ii(n.body?.version):void 0;if(!o&&!r)return;let i={checked_at:Date.now(),cli:o??t?.cli,runtime:r??t?.runtime};return await e.writeText(Du(e),`${JSON.stringify(i)}
137
+ `),i}catch{return}}function Ii(e){return typeof e==="string"&&Mb.test(e)?e:void 0}function Ci(e,t,n){let r={};if(e?.cli)r.cli={current:t,latest:e.cli};if(e?.runtime&&n)r.runtime={current:n,latest:e.runtime.replace(/^v/,"")};return r.cli||r.runtime?r:void 0}function Uu(e,t,n="npx nimblebrain"){let r=[],o=e?.cli;if(o&&mt(o.latest,o.current)>0)r.push(`nimblebrain ${o.latest} is available (you have ${o.current}): npx nimblebrain@latest`);let i=e?.runtime;if(t&&i&&mt(i.latest,i.current)>0)r.push(`NimbleBrain v${i.latest} is available (you have v${i.current}): ${n} update`);return r}Re();async function Zu(e){let{deps:t,home:n}=e,r=e.arg===void 0?void 0:Zb(e.arg);if(e.operand!==void 0&&r!=="local")throw new x("USAGE",`Only use local takes a model, not "${e.operand}".`);if(r===void 0&&!We(e))throw cu();cn(e.flags.model,r??"claude");let o=await de(t,n),i=r??await Bb(e);if(cn(e.flags.model,i),Mt(i))return Fb(e,i,o.port);if(i==="api")return Vb(e,o.port);return qb(e,o.port)}function Zb(e){if(He.includes(e))return e;throw new x("USAGE",`use takes ${Qt}, not "${e}".`)}async function Bb(e){let t=R(e.home),n=await e.deps.readText(t.env)??"",r=await e.deps.readText(t.compose)??"";return dr(e.deps,await an(e.deps,n,r))}async function Fb(e,t,n){let{worker:r,account:o,runtime:i,moved:s}=await fr(e.deps,e.home,t,e.flags.port,e.flags.model);return await De(e.deps,e.home,n),{ok:!0,model_source:await Dt(e.deps,e.home),agent_runtime:{name:i,worker:r},billed_to:o.describe,tools:Jn[i],port_moved:s}}async function Vb(e,t){let{deps:n,home:r}=e,o=R(r),i=await n.readText(o.compose)??"";if(!Ne(await n.readText(o.env)??"",ze(i))){if(!n.interactive)throw new x("MODEL_KEY_MISSING","This install has no model key, and `key` asks for one at a hidden prompt.");await br(e,!1)}return await jt(n,r,!0),await De(n,r,t),{ok:!0,model_source:await Dt(n,r),agent_runtime:{name:"native",worker:null},provider:lt(await n.readText(o.env)??"",i)}}async function qb(e,t){let{deps:n,home:r}=e,o=R(r),i=le(await n.readText(o.env)??""),s=await n.readText(o.compose)??"",{name:a,started:u}=e.operand===void 0&&i?{name:i,started:(await st(n,ht(e,!0))).started}:await yr(e,s,e.operand??it);return await dn(u,async()=>{await jt(n,r,!1),await De(n,r,t)}),{ok:!0,model_source:await Dt(n,r),agent_runtime:{name:"native",worker:null},local_model:a,ollama_started:u}}var Hb=["status","up","init"];async function Fu(e,t){let n=Go(e),r;try{r=Ho(e)}catch(w){return Zt(Bu(w),n,Ve)}if(r.kind==="help")return r.flags.json?Zt(jc(he),!0,Ve):{stdout:Uc(he),code:0};if(r.kind==="version")return r.flags.json?Zt({ok:!0,version:he},!0,Ve):{stdout:`${he}
138
+ `,code:0};let{command:o,flags:i,arg:s,operand:a}=r,u=ju(t),d=Et(t,i.home),p=me(t,d),g;try{switch(o){case"doctor":{let w=await pt(t,d),b=i.port??w?.port??Rt,z=w?.port===b&&await er(t,d),I=!w&&i.port===void 0,k=ht({deps:t,flags:i},!1);g={...await Kb(t,d,b,z,I,k)};break}case"status":g={...await ke(t,d)};break;default:{let w={deps:t,flags:i,home:d,version:he,arg:s,operand:a};g=await{init:ku,up:Su,down:vu,logs:$u,update:Eu,uninstall:Iu,key:Tu,telemetry:Cu,"local-model":Au,use:Zu,mcp:Nu,open:_u}[o](w)}}}catch(w){g=Bu(w)}if(!g.ok)g={...g,fix:Po(g.fix,p)};if(!["init","telemetry","uninstall","doctor"].includes(o))await mu(t,d,he);return Gb(g,o,i.json,u,p)}async function Gb(e,t,n,r,o){if(!r)return Zt(e,n,o,t);let i=Wb(e)?e.version:void 0,s=Ci(await r.known(0),he,i);return{...Zt(s&&i!==void 0?{...e,updates:s}:e,n,o,t),notices:async()=>{let d=await r.known(Mu);if(n)return;let p=Uu(Ci(d,he,i),Hb.includes(t),o);return p.length>0?`${p.join(`
138
139
  `)}
139
- `:void 0}}}function _b(e){return typeof e.version==="string"&&"health"in e&&"url"in e&&"workspaces"in e}async function bb(e,t,n,r,o){let i=await qn(e,n,r),s=ue(await e.readText(R(t).env)??"");if(!s)return i;try{let a=await sc(e,s,o);return{...i,checks:[...i.checks,...a.checks],ollama_started:a.started}}catch(a){if(!(a instanceof x))throw a;let l=a.detail.checks??[];throw a.with({checks:[...i.checks,...l]})}}function xu(e){if(e instanceof x)return Mn(e);return Mn(new x("USAGE",e instanceof Error?e.message:String(e)))}function Pt(e,t,n,r){let o=nc(e);if(t)return{stdout:`${JSON.stringify(e)}
140
+ `:void 0}}}function Wb(e){return typeof e.version==="string"&&"health"in e&&"url"in e&&"workspaces"in e}async function Kb(e,t,n,r,o,i){let s=await tr(e,n,r,o?t:void 0),a=le(await e.readText(R(t).env)??"");if(!a)return s;try{let u=await Ic(e,a,i);return{...s,checks:[...s.checks,...u.checks],ollama_started:u.started}}catch(u){if(!(u instanceof x))throw u;let d=u.detail.checks??[];throw u.with({checks:[...s.checks,...d]})}}function Bu(e){if(e instanceof x)return Vn(e);return Vn(new x("USAGE",e instanceof Error?e.message:String(e)))}function Zt(e,t,n,r){let o=hc(e);if(t)return{stdout:`${JSON.stringify(e)}
140
141
  `,code:o};if(!e.ok)return{stdout:`error: ${e.message}
141
142
  fix: ${e.fix}
142
- `,code:o};return{stdout:`${(yb(e)?zb(e,n,r):r==="open"?vb(e):r==="use"?Sb(e):Tb(e)).join(`
143
+ `,code:o};return{stdout:`${(Jb(e)?Yb(e,n,r):r==="open"?ty(e):r==="use"?ey(e):sy(e)).join(`
143
144
  `)}
144
- `,code:o}}function yb(e){return"health"in e&&"url"in e&&"workspaces"in e}var Su={"claude-code":"Claude Code",cursor:"Cursor",codex:"Codex"};function zb(e,t,n){let r=[...Ib(e),` NimbleBrain ${e.version.startsWith("v")?e.version:`v${e.version}`}: ${e.health==="ok"?"running":"stopped"} at ${e.url}`,...e.workspaces.map((i)=>` workspace ${i.name}: ${i.mcp}`),kb(e,t)];if(r.push(...$b(e)),!e.host_loopback)r.push(` servers on this machine: not reachable until ${t} update`);r.push(Cb(e.telemetry)),r.push(` CLI ${e.cli_version}`);let o=xb(e,t,n);if(o)r.push("",o);return r}function xb(e,t,n){if(n==="init"&&!e.already&&e.health==="ok"){if(!dr(e))return`Next: choose what runs NimbleBrain's agents so it can chat. Run ${t} use in your own terminal: your Claude subscription, your ChatGPT plan, an API key, or a local model.`;let r=e.agent.connected,o=r?`, or ask ${Su[r]??r} what NimbleBrain can do`:"";return`Next: ${e.opened?`use NimbleBrain in your browser at ${e.url}`:`open ${e.url}`}${o}. Stop it with ${t} down.`}if(n!=="status")return;if(e.phase!=="ready")return`Next: finish installing it with ${t}, or remove it with ${t} uninstall.`;return e.health==="ok"?void 0:`Next: start it with ${t} up.`}function kb(e,t){let{label:n}=e.model_source;if(!n)return` agents run on: nothing yet (choose with ${t} use)`;let r=e.agent_runtime.worker;if(!r)return` agents run on: ${n}`;return r.running?` agents run on: ${n} (agent worker ${r.pid} at ${r.url})`:` agents run on: ${n}, but its agent worker is stopped (start it with ${t} up)`}function Sb(e){let{label:t}=e.model_source,n=e.agent_runtime,r=[` NimbleBrain's agents now run on ${t??"nothing"}.`];if(!n.worker)return r;return[...r,` billed to: ${String(e.billed_to)}`,` tools: ${String(e.tools)}`,` agent worker: ${n.worker.pid} at ${n.worker.url} (this machine only), logging to ${n.worker.log}`,...n.worker.login_item?[` starts at login: ${n.worker.login_item} (launchd starts the worker when you log in, and again if it crashes)`]:[]]}function vb(e){return[e.opened?` Opened ${String(e.url)} in your browser.`:` Open ${String(e.url)} in your browser; none could be started here.`]}function $b(e){let t=e.agent.connected;if(!t)return e.manual?[` agent: not connected; add it by hand: ${e.manual}`]:[];let r=[` ${Su[t]??t} can use NimbleBrain's tools (it loads them when its next session starts)`],o=e.skill_update&&Eb[e.skill_update];if(o)r.push(` skill: ${o}`);if(!e.agent.skill)r.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${t} -g`);return r}var Eb={updated:"updated to the newest nimblebrain skill",unchanged:"the nimblebrain skill is current",failed:"could not refresh the nimblebrain skill; try npx skills update nimblebrain -g",not_installed:void 0};function Ib(e){if(e.already)return[" already installed"];return e.from?[` updated from ${e.from}`]:[]}function Cb(e){let t=e.locked?` (${e.locked})`:e.set?` (answer with ${e.set})`:"";return` telemetry: ${e.state}${t}`}function Tb(e){return Object.entries(e).filter(([t])=>t!=="ok").flatMap(([t,n])=>vu(t,n))}function vu(e,t){if(t===void 0||t===null)return[];if(e==="servers"&&Array.isArray(t)){if(t.length===0)return[" no servers in this workspace"];return t.map((n)=>` ${n.serverName}: ${n.url??"(no URL)"}${n.status?` (${n.status})`:""}`)}if(e==="checks"&&Array.isArray(t))return t.map((n)=>` ${n.ok?"✓":"✗"} ${n.check}: ${n.detail}`);if(typeof t==="object"&&!Array.isArray(t))return Object.entries(t).flatMap(([n,r])=>vu(`${e} ${n}`,r));if(Array.isArray(t)){let n=t.map((r)=>typeof r==="object"?JSON.stringify(r):String(r));return[` ${e}: ${n.join(", ")}`]}return[` ${e}: ${String(t)}`]}function $u(e,t,n){let r=new x("INTERRUPTED",`The CLI stopped before it answered (exit code ${t}).`,{exit_code:t}),o=Ve;try{o=fe(n,Ln(n,No(e).flags.home))}catch{}let i=Mn(r);return Pt({...i,fix:To(i.fix,o)},Po(e),o)}Tt();var Ka=process.argv.slice(2);if(Ka[0]===it){await Promise.resolve().then(() => lg());await ug(Ka.slice(1))}else await Jv(Ka);async function Jv(e){let t=tc(),n=!1;process.on("exit",(i)=>{if(n)return;let s=$u(e,i,t);So(1,s.stdout),So(2,`nimblebrain: stopped before answering (exit code ${i})
145
- `),process.exitCode=s.code});for(let[i,s]of[["SIGINT",2],["SIGTERM",15],["SIGHUP",1]])process.on(i,()=>process.exit(128+s));let r=await ku(e,t);So(1,r.stdout),n=!0;let o=await r.notices?.();if(o)So(2,o);process.exit(r.code)}
145
+ `,code:o}}function Jb(e){return"health"in e&&"url"in e&&"workspaces"in e}var Vu={"claude-code":"Claude Code",cursor:"Cursor",codex:"Codex"};function Yb(e,t,n){let r=[...oy(e),` NimbleBrain ${e.version.startsWith("v")?e.version:`v${e.version}`}: ${e.health==="ok"?"running":"stopped"} at ${e.url}`,...e.workspaces.map((i)=>` workspace ${i.name}: ${i.mcp}`),Qb(e,t)];if(r.push(...ny(e)),!e.host_loopback)r.push(` servers on this machine: not reachable until ${t} update`);r.push(iy(e.telemetry)),r.push(` CLI ${e.cli_version}`);let o=Xb(e,t,n);if(o)r.push("",o);return r}function Xb(e,t,n){if(n==="init"&&!e.already&&e.health==="ok"){if(!wr(e))return`Next: choose what runs NimbleBrain's agents so it can chat. Run ${t} use in your own terminal: your Claude subscription, your ChatGPT plan, an API key, or a local model.`;let r=e.agent.connected,o=r?`, or ask ${Vu[r]??r} what NimbleBrain can do`:"";return`Next: ${e.opened?`use NimbleBrain in your browser at ${e.url}`:`open ${e.url}`}${o}. Stop it with ${t} down.`}if(n!=="status")return;if(e.phase!=="ready")return`Next: finish installing it with ${t}, or remove it with ${t} uninstall.`;return e.health==="ok"?void 0:`Next: start it with ${t} up.`}function Qb(e,t){let{label:n}=e.model_source;if(!n)return` agents run on: nothing yet (choose with ${t} use)`;let r=e.agent_runtime.worker;if(!r)return` agents run on: ${n}`;return r.running?` agents run on: ${n}; agent worker ${r.pid} at ${r.url}`:` agents run on: ${n}, but its agent worker is stopped (start it with ${t} up)`}function ey(e){let{label:t}=e.model_source,n=e.agent_runtime,r=[` NimbleBrain's agents now run on ${t??"nothing"}.`];if(!n.worker)return r;return[...r,` billed to: ${String(e.billed_to)}`,` tools: ${String(e.tools)}`,` agent worker: ${n.worker.pid} at ${n.worker.url} (this machine only), logging to ${n.worker.log}`,...n.worker.login_item?[` starts at login: ${n.worker.login_item} (launchd starts the worker when you log in, and again if it crashes)`]:[]]}function ty(e){return[e.opened?` Opened ${String(e.url)} in your browser.`:` Open ${String(e.url)} in your browser; none could be started here.`]}function ny(e){let t=e.agent.connected;if(!t)return e.manual?[` agent: not connected; add it by hand: ${e.manual}`]:[];let n=Vu[t]??t,r=e.agent.server&&e.agent.server!==ot?` as ${e.agent.server}`:"",o=[` ${n} can use NimbleBrain's tools${r} (it loads them when its next session starts)`],i=e.skill_update&&ry[e.skill_update];if(i)o.push(` skill: ${i}`);if(!e.agent.skill)o.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${t} -g`);return o}var ry={updated:"updated to the newest nimblebrain skill",unchanged:"the nimblebrain skill is current",failed:"could not refresh the nimblebrain skill; try npx skills update nimblebrain -g",not_installed:void 0};function oy(e){if(e.already)return[" already installed"];return e.from?[` updated from ${e.from}`]:[]}function iy(e){let t=e.locked?` (${e.locked})`:e.set?` (answer with ${e.set})`:"";return` telemetry: ${e.state}${t}`}function sy(e){return Object.entries(e).filter(([t])=>t!=="ok").flatMap(([t,n])=>qu(t,n))}function qu(e,t){if(t===void 0||t===null)return[];if(e==="servers"&&Array.isArray(t)){if(t.length===0)return[" no servers in this workspace"];return t.map((n)=>` ${n.serverName}: ${n.url??"(no URL)"}${n.status?` (${n.status})`:""}`)}if(e==="checks"&&Array.isArray(t))return t.map((n)=>` ${n.ok?"✓":"✗"} ${n.check}: ${n.detail}`);if(typeof t==="object"&&!Array.isArray(t))return Object.entries(t).flatMap(([n,r])=>qu(`${e} ${n}`,r));if(Array.isArray(t)){let n=t.map((r)=>typeof r==="object"?JSON.stringify(r):String(r));return[` ${e}: ${n.join(", ")}`]}return[` ${e}: ${String(t)}`]}function Hu(e,t,n){let r=new x("INTERRUPTED",`The CLI stopped before it answered (exit code ${t}).`,{exit_code:t}),o=Ve;try{o=me(n,Et(n,Ho(e).flags.home))}catch{}let i=Vn(r);return Zt({...i,fix:Po(i.fix,o)},Go(e),o)}Re();var ac=process.argv.slice(2);if(ac[0]===at){await Promise.resolve().then(() => Tg());await Cg(ac.slice(1))}else await A$(ac);async function A$(e){let t=mc(),n=!1;process.on("exit",(i)=>{if(n)return;let s=Hu(e,i,t);To(1,s.stdout),To(2,`nimblebrain: stopped before answering (exit code ${i})
146
+ `),process.exitCode=s.code});for(let[i,s]of[["SIGINT",2],["SIGTERM",15],["SIGHUP",1]])process.on(i,()=>process.exit(128+s));let r=await Fu(e,t);To(1,r.stdout),n=!0;let o=await r.notices?.();if(o)To(2,o);process.exit(r.code)}