nimblebrain 0.7.1 → 0.9.0-beta.1

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.
Files changed (3) hide show
  1. package/README.md +51 -3
  2. package/dist/nimblebrain.js +130 -2357
  3. package/package.json +6 -2
@@ -1,2372 +1,145 @@
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
7
 
3
- // src/bin.ts
4
- import { writeSync } from "node:fs";
8
+ `}function Xu(){return`:
5
9
 
6
- // src/deps.ts
7
- import { spawn } from "node:child_process";
8
- import { constants } from "node:fs";
9
- import { access, chmod, mkdir, readFile, rm, rmdir, writeFile } from "node:fs/promises";
10
- import { createServer } from "node:net";
11
- import { homedir } from "node:os";
12
- import { delimiter, dirname, join, resolve } from "node:path";
13
- var LAUNCH_WAIT_MS = 2000;
14
- function realDeps() {
15
- return {
16
- exec(cmd, args, opts = {}) {
17
- return new Promise((resolve) => {
18
- let stdout = "";
19
- let stderr = "";
20
- let missing = false;
21
- const child = spawn(cmd, args, {
22
- stdio: ["ignore", "pipe", "pipe"],
23
- timeout: opts.timeoutMs ?? 30000,
24
- cwd: opts.cwd,
25
- env: opts.env
26
- });
27
- child.stdout.on("data", (d) => {
28
- stdout += d.toString();
29
- });
30
- child.stderr.on("data", (d) => {
31
- stderr += d.toString();
32
- });
33
- child.on("error", (err) => {
34
- if (err.code === "ENOENT")
35
- missing = true;
36
- });
37
- child.on("close", (code) => resolve({ code, stdout, stderr, missing }));
38
- });
39
- },
40
- launch(cmd, args) {
41
- return new Promise((resolve) => {
42
- let child;
43
- try {
44
- child = spawn(cmd, args, { stdio: "ignore", detached: true });
45
- } catch {
46
- resolve(false);
47
- return;
48
- }
49
- const timer = setTimeout(() => {
50
- child.unref();
51
- resolve(true);
52
- }, LAUNCH_WAIT_MS);
53
- child.once("error", () => {
54
- clearTimeout(timer);
55
- resolve(false);
56
- });
57
- child.once("exit", (code) => {
58
- clearTimeout(timer);
59
- resolve(code === 0);
60
- });
61
- });
62
- },
63
- async which(cmd) {
64
- const exts = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE").split(";") : [""];
65
- for (const dir of (process.env.PATH ?? "").split(delimiter).filter(Boolean)) {
66
- for (const ext of exts) {
67
- try {
68
- await access(join(dir, cmd + ext), constants.X_OK);
69
- return true;
70
- } catch {}
71
- }
72
- }
73
- return false;
74
- },
75
- portFree(port) {
76
- return new Promise((resolve) => {
77
- const server = createServer();
78
- server.once("error", () => resolve(false));
79
- server.once("listening", () => server.close(() => resolve(true)));
80
- server.listen(port, "127.0.0.1");
81
- });
82
- },
83
- getJson: async (url, timeoutMs = 3000) => asJson(await request(url, { headers: { "user-agent": "nimblebrain-cli" } }, timeoutMs)),
84
- getText: (url, timeoutMs = 1e4) => request(url, { headers: { "user-agent": "nimblebrain-cli" } }, timeoutMs),
85
- postJson: async (url, body, timeoutMs = 5000) => asJson(await request(url, {
86
- method: "POST",
87
- headers: { "user-agent": "nimblebrain-cli", "content-type": "application/json" },
88
- body: JSON.stringify(body)
89
- }, timeoutMs)),
90
- async readText(path) {
91
- try {
92
- return await readFile(path, "utf8");
93
- } catch {
94
- return;
95
- }
96
- },
97
- async writeText(path, text, mode = 420) {
98
- await mkdir(dirname(path), { recursive: true, mode: 448 });
99
- await writeFile(path, text, { mode });
100
- await chmod(path, mode);
101
- },
102
- async remove(path) {
103
- try {
104
- await rmdir(path);
105
- } catch (err) {
106
- if (err.code === "ENOTDIR")
107
- await rm(path, { force: true });
108
- }
109
- },
110
- prompt: (question, opts = {}) => opts.hidden ? hiddenPrompt(question) : visiblePrompt(question),
111
- interactive: Boolean(process.stdin.isTTY && process.stderr.isTTY),
112
- sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
113
- say: (line) => {
114
- process.stderr.write(`${line}
115
- `);
116
- },
117
- env: process.env,
118
- platform: process.platform,
119
- home: homedir(),
120
- cwd: process.cwd()
121
- };
122
- }
123
- async function request(url, init, timeoutMs) {
124
- const abort = new AbortController;
125
- const timer = setTimeout(() => abort.abort(), timeoutMs);
126
- try {
127
- const res = await fetch(url, { ...init, signal: abort.signal });
128
- return { status: res.status, body: await res.text() };
129
- } catch {
130
- return;
131
- } finally {
132
- clearTimeout(timer);
133
- }
134
- }
135
- function asJson(res) {
136
- if (!res)
137
- return;
138
- try {
139
- return { status: res.status, body: JSON.parse(res.body) };
140
- } catch {
141
- return res;
142
- }
143
- }
144
- async function visiblePrompt(question) {
145
- const { createInterface } = await import("node:readline/promises");
146
- const rl = createInterface({ input: process.stdin, output: process.stderr });
147
- try {
148
- return (await rl.question(question)).trim();
149
- } finally {
150
- rl.close();
151
- }
152
- }
153
- function hiddenPrompt(question) {
154
- return new Promise((resolve, reject) => {
155
- const stdin = process.stdin;
156
- process.stderr.write(question);
157
- let value = "";
158
- stdin.setRawMode(true);
159
- stdin.resume();
160
- stdin.setEncoding("utf8");
161
- const done = (fn) => {
162
- stdin.setRawMode(false);
163
- stdin.pause();
164
- stdin.removeListener("data", onData);
165
- process.stderr.write(`
166
- `);
167
- fn();
168
- };
169
- const onData = (chunk) => {
170
- const step = typeHidden(value, chunk);
171
- value = step.value;
172
- if (step.end === "enter")
173
- done(() => resolve(value.trim()));
174
- if (step.end === "cancel")
175
- done(() => reject(new Error("Cancelled.")));
176
- };
177
- stdin.on("data", onData);
178
- });
179
- }
180
- function typeHidden(value, chunk) {
181
- let v = value;
182
- for (const ch of chunk) {
183
- if (ch === "\r" || ch === `
184
- `)
185
- return { value: v, end: "enter" };
186
- if (ch === "\x03")
187
- return { value: v, end: "cancel" };
188
- v = ch === "" || ch === "\b" ? v.slice(0, -1) : v + ch;
189
- }
190
- return { value: v };
191
- }
192
- function installHome(deps, flag) {
193
- return resolve(deps.cwd, flag ?? deps.env.NIMBLEBRAIN_HOME ?? join(deps.home, ".nimblebrain-local"));
194
- }
195
- var BARE_CLI = "npx nimblebrain";
196
- function invocation(deps, home) {
197
- const fallback = resolve(deps.cwd, join(deps.home, ".nimblebrain-local"));
198
- if (home === fallback && installHome(deps) === fallback)
199
- return BARE_CLI;
200
- return `${BARE_CLI} --home ${shellQuote(home)}`;
201
- }
202
- function shellQuote(s) {
203
- return /^[A-Za-z0-9_./,:@%+=-]+$/.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`;
204
- }
205
- function forInstall(text, cli) {
206
- return text.replaceAll(BARE_CLI, () => cli);
207
- }
208
-
209
- // src/args.ts
210
- import { parseArgs } from "node:util";
211
-
212
- // src/result.ts
213
- var ERRORS = {
214
- USAGE: "Run `npx nimblebrain --help` for the commands and flags.",
215
- DOCKER_MISSING: "Install Docker Desktop or Docker Engine (https://docs.docker.com/get-docker/), then run this again.",
216
- DOCKER_NOT_RUNNING: "Start Docker Desktop (or the Docker service), then run this again.",
217
- DOCKER_PERMISSION: "Let this user use Docker (https://docs.docker.com/engine/install/linux-postinstall/), sign in again, then run this again.",
218
- COMPOSE_MISSING: "Install Docker Compose v2 (https://docs.docker.com/compose/install/) or update Docker Desktop, then run this again.",
219
- ARCH_UNSUPPORTED: "NimbleBrain publishes no image for this CPU architecture.",
220
- LOW_MEMORY: "Give Docker at least 2 GB of memory in its settings, then run this again.",
221
- PORT_IN_USE: "Stop whatever holds the port, or pass --port with a free one.",
222
- NOT_INSTALLED: "Run `npx nimblebrain` to install it.",
223
- NOT_OURS: "Another install holds this name or its data. Remove it yourself, or choose a --home whose folder has another name.",
224
- NETWORK: "Check the network connection, then run the same command again.",
225
- HEALTH_TIMEOUT: "Run `npx nimblebrain logs` and look at the last error line.",
226
- AGENT_UNSUPPORTED: "Pass --agent claude-code, cursor, codex or none.",
227
- START_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again.",
228
- NEEDS_TERMINAL: "A person runs this in their own terminal; it asks for input no agent should give.",
229
- CANCELLED: "Nothing was changed. Run the command again to go ahead.",
230
- RUNTIME_UNSUPPORTED: "Pass a newer runtime with --runtime, or leave it out to install the newest release.",
231
- NOT_RUNNING: "Run `npx nimblebrain up`, then run this again.",
232
- TELEMETRY_LOCKED: "Nothing to change: DO_NOT_TRACK or the install's configuration decides telemetry here.",
233
- LOCAL_MODEL_UNREACHABLE: "Install Ollama (https://ollama.com/download) and start it, then run this again.",
234
- LOCAL_MODEL_MISSING: "Download the model with `ollama pull <model>`, or check that Ollama has disk space, then run this again.",
235
- 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.",
236
- LOCAL_CONTEXT_SMALL: "Run `npx nimblebrain local-model` to prepare the model again with a 32k context window.",
237
- INTERRUPTED: "Run `npx nimblebrain status` to see what is in place, then run the same command again.",
238
- UPDATE_REQUIRED: "Run `npx nimblebrain update`; this install's NimbleBrain cannot reach servers on this machine yet.",
239
- WORKSPACE_NOT_FOUND: "Run `npx nimblebrain status` for the workspace ids, then pass one with --workspace.",
240
- SERVER_NOT_FOUND: "Run `npx nimblebrain mcp list` for the server names in this workspace.",
241
- 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.",
242
- 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.",
243
- URL_INVALID: "Pass the server's full MCP URL, such as http://127.0.0.1:8000/mcp.",
244
- INVALID_SERVER_NAME: "Pass another name with --name: lowercase letters, digits and hyphens.",
245
- NAME_TAKEN: "Pass another name with --name, or remove the existing one with `npx nimblebrain mcp remove <serverName>`.",
246
- NAME_IS_CATALOG_ENTRY: "Pass another name with --name; this one belongs to a catalog connector.",
247
- REQUEST_FAILED: "Run `npx nimblebrain logs` and look at the last error line, then run this again."
248
- };
249
- var FIX_VARIANTS = {
250
- DOCKER_MISSING: {
251
- mac_brew: "Install Docker Desktop with `brew install --cask docker`, open it once from Applications, then run this again.",
252
- mac: "Install Docker Desktop (https://docs.docker.com/desktop/setup/install/mac-install/), open it once, then run this again."
253
- },
254
- COMPOSE_MISSING: {
255
- brew: "Install Compose with `brew install docker-compose`, then run this again."
256
- },
257
- LOW_MEMORY: {
258
- colima: "Restart Colima with more memory: `colima stop && colima start --memory 4`, then run this again.",
259
- docker_desktop: "In Docker Desktop, open Settings > Resources, set Memory to at least 2 GB, apply, then run this again."
260
- },
261
- LOCAL_MODEL_UNREACHABLE: {
262
- brew_install: "Install Ollama with `brew install ollama`, then run this again; it offers to start Ollama for you.",
263
- app: "Open the Ollama app, then run this again.",
264
- brew: "Run `brew services start ollama` (it then also starts at login), then run this again.",
265
- systemd: "Run `sudo systemctl start ollama`, then run this again.",
266
- serve: "Run `ollama serve` in another terminal, then run this again."
267
- }
268
- };
269
-
270
- class CliError extends Error {
271
- code;
272
- fix;
273
- detail;
274
- variant;
275
- constructor(code, message, detail = {}, variant) {
276
- super(message ?? code);
277
- this.code = code;
278
- const variants = FIX_VARIANTS[code];
279
- this.fix = variant && variants?.[variant] || ERRORS[code];
280
- this.variant = variant;
281
- this.detail = detail;
282
- }
283
- with(detail, message = this.message) {
284
- return new CliError(this.code, message, { ...this.detail, ...detail }, this.variant);
285
- }
286
- }
287
- function failure(err) {
288
- return { ...err.detail, ok: false, error: err.code, message: err.message, fix: err.fix };
289
- }
290
- function exitCodeFor(result) {
291
- return result.ok ? 0 : exitCodeOf(result.error);
292
- }
293
- function exitCodeOf(code) {
294
- return code === "USAGE" ? 2 : 1;
295
- }
296
-
297
- // src/local-model.ts
298
- var OLLAMA_URL = "http://127.0.0.1:11434";
299
- var OLLAMA_FROM_CONTAINER = "http://host.docker.internal:11434/v1";
300
- var DEFAULT_LOCAL_MODEL = "gemma4:e4b";
301
- var LOCAL_CONTEXT = 32768;
302
- var PULL_TIMEOUT_MS = 60 * 60 * 1000;
303
- var OLLAMA_START_TIMEOUT_MS = 30000;
304
- var CREATE_TIMEOUT_MS = 2 * 60 * 1000;
305
- function takesLocalModel(composeText) {
306
- return composeText.includes("NB_LOCAL_MODEL_URL");
307
- }
308
- function nimblebrainModelName(model) {
309
- return `nimblebrain-${model.replace(/[^A-Za-z0-9._-]+/g, "-")}`;
310
- }
311
- function localModelOf(envText) {
312
- const line = envText.split(`
313
- `).find((l) => l.startsWith("NB_LOCAL_MODEL="));
314
- const value = line?.slice("NB_LOCAL_MODEL=".length).trim();
315
- return value ? value : undefined;
316
- }
317
- async function show(deps, model) {
318
- const res = await deps.postJson(`${OLLAMA_URL}/api/show`, { model });
319
- return res?.status === 200 ? res.body : undefined;
320
- }
321
- function numCtxOf(parameters) {
322
- const match = parameters?.match(/^num_ctx\s+(\d+)/m);
323
- return match ? Number(match[1]) : undefined;
324
- }
325
- async function ollamaVersion(deps) {
326
- const res = await deps.getJson(`${OLLAMA_URL}/api/version`);
327
- const version = res?.body?.version;
328
- return res?.status === 200 && typeof version === "string" ? version : undefined;
329
- }
330
- var SYSTEMD_UNITS = [
331
- "/etc/systemd/system/ollama.service",
332
- "/usr/lib/systemd/system/ollama.service"
333
- ];
334
- async function findOllama(deps) {
335
- const apps = ["/Applications", `${deps.home}/Applications`].map((dir) => `${dir}/Ollama.app/Contents/Info.plist`);
336
- if (deps.platform === "darwin" && await anyFile(deps, apps))
337
- return { kind: "app", start: ["open", "-g", "-a", "Ollama"], fix: "app" };
338
- if (deps.platform === "linux" && await anyFile(deps, SYSTEMD_UNITS))
339
- return {
340
- kind: "systemd",
341
- start: ["systemctl", "start", "--no-ask-password", "ollama"],
342
- fix: "systemd"
343
- };
344
- const brew = await deps.exec("brew", ["list", "--versions", "ollama"]);
345
- if (brew.code === 0 && brew.stdout.trim())
346
- return { kind: "brew", start: ["brew", "services", "start", "ollama"], fix: "brew" };
347
- if (await deps.which("ollama"))
348
- return { kind: "binary", fix: "serve" };
349
- return { kind: "none", fix: brew.missing ? undefined : "brew_install" };
350
- }
351
- async function anyFile(deps, files) {
352
- for (const file of files)
353
- if (await deps.readText(file) !== undefined)
354
- return true;
355
- return false;
356
- }
357
- async function ensureOllama(deps, confirm) {
358
- const running = await ollamaVersion(deps);
359
- if (running)
360
- return { version: running };
361
- const install = await findOllama(deps);
362
- const down = (message, extra = {}) => new CliError("LOCAL_MODEL_UNREACHABLE", message, { check: "ollama", ollama: install.kind, ...extra }, install.fix);
363
- if (!install.start) {
364
- throw down(install.kind === "none" ? `Ollama does not answer at ${OLLAMA_URL}, and it does not look installed.` : `Ollama does not answer at ${OLLAMA_URL}.`);
365
- }
366
- const command = install.start.join(" ");
367
- if (!await confirm(command)) {
368
- throw down(`Ollama is installed but not running at ${OLLAMA_URL}; it was not started.`);
369
- }
370
- deps.say(`Starting Ollama: ${command}`);
371
- const [cmd = "", ...args] = install.start;
372
- const res = await deps.exec(cmd, args, { timeoutMs: 60000 });
373
- if (res.code !== 0 || res.missing) {
374
- const why = res.stderr.trim().split(`
375
- `)[0];
376
- throw down(`\`${command}\` did not start Ollama${why ? `: ${why}` : "."}`);
377
- }
378
- for (let waited = 0;waited < OLLAMA_START_TIMEOUT_MS; waited += 1000) {
379
- await deps.sleep(1000);
380
- const version = await ollamaVersion(deps);
381
- if (version) {
382
- deps.say(`Ollama ${version} is running.`);
383
- if (deps.platform === "linux")
384
- deps.say("On Linux, NimbleBrain's container reaches Ollama only when it listens beyond 127.0.0.1 (OLLAMA_HOST=0.0.0.0).");
385
- return { version, started: command };
386
- }
387
- }
388
- throw down(`Ollama was started with \`${command}\` but did not answer at ${OLLAMA_URL} within 30 seconds.`, { ollama_started: command });
389
- }
390
- async function setupLocalModel(deps, model, asks) {
391
- const { started } = await ensureOllama(deps, asks.start);
392
- try {
393
- return { values: await prepareModel(deps, model, asks.pull), started };
394
- } catch (err) {
395
- if (err instanceof CliError && started)
396
- throw err.with({ ollama_started: started });
397
- throw err;
398
- }
399
- }
400
- async function prepareModel(deps, model, pull) {
401
- let found = await show(deps, model);
402
- if (!found) {
403
- if (!await pull(model)) {
404
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`, {
405
- check: "model"
406
- });
407
- }
408
- deps.say(`Downloading ${model} with Ollama. A model is several GB; this can take a while.`);
409
- const pulled = await deps.postJson(`${OLLAMA_URL}/api/pull`, { model, stream: false }, PULL_TIMEOUT_MS);
410
- found = pulled?.status === 200 ? await show(deps, model) : undefined;
411
- if (!found) {
412
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not download "${model}".`, {
413
- check: "model"
414
- });
415
- }
416
- }
417
- if (!found.capabilities?.includes("tools")) {
418
- throw new CliError("LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling, which NimbleBrain's agents need.`, { check: "tools" });
419
- }
420
- const name = nimblebrainModelName(model);
421
- const created = await deps.postJson(`${OLLAMA_URL}/api/create`, { model: name, from: model, parameters: { num_ctx: LOCAL_CONTEXT }, stream: false }, CREATE_TIMEOUT_MS);
422
- if (created?.status !== 200) {
423
- throw new CliError("LOCAL_MODEL_MISSING", `Ollama could not prepare ${name} from ${model}.`, {
424
- check: "model"
425
- });
426
- }
427
- return {
428
- NB_LOCAL_MODEL_URL: OLLAMA_FROM_CONTAINER,
429
- NB_LOCAL_MODEL: name,
430
- NB_LOCAL_MODEL_CONTEXT: String(LOCAL_CONTEXT)
431
- };
432
- }
433
- async function checkLocalModel(deps, model, start) {
434
- const checks = [];
435
- const { version, started } = await ensureOllama(deps, start).catch((err) => {
436
- if (!(err instanceof CliError))
437
- throw err;
438
- checks.push({ check: "ollama", ok: false, detail: err.message });
439
- throw err.with({ check: "ollama", checks });
440
- });
441
- checks.push({
442
- check: "ollama",
443
- ok: true,
444
- detail: started ? `${version} (started: ${started})` : version
445
- });
446
- const found = await show(deps, model);
447
- const fail = (check, code, detail) => {
448
- checks.push({ check, ok: false, detail });
449
- throw new CliError(code, detail, { check, checks, ollama_started: started });
450
- };
451
- if (!found)
452
- fail("model", "LOCAL_MODEL_MISSING", `Ollama has no model "${model}".`);
453
- checks.push({ check: "model", ok: true, detail: model });
454
- if (!found?.capabilities?.includes("tools"))
455
- fail("tools", "LOCAL_MODEL_NO_TOOLS", `${model} does not support tool calling.`);
456
- checks.push({ check: "tools", ok: true, detail: "tool calling" });
457
- const ctx = numCtxOf(found?.parameters);
458
- if (ctx === undefined || ctx < LOCAL_CONTEXT)
459
- fail("context", "LOCAL_CONTEXT_SMALL", `${model} has a context window of ${ctx ?? "Ollama's default"}, below ${LOCAL_CONTEXT}.`);
460
- checks.push({ check: "context", ok: true, detail: `${ctx} tokens` });
461
- return { checks, started };
462
- }
463
-
464
- // src/args.ts
465
- var COMMAND_SPECS = {
466
- init: {
467
- args: [],
468
- description: "Check this machine, start NimbleBrain, connect your coding agent (default)"
469
- },
470
- doctor: {
471
- args: [],
472
- description: "Check Docker, Compose, architecture, memory and the port; installs nothing"
473
- },
474
- status: { args: [], description: "Version, health, URL and each workspace's MCP URL" },
475
- open: { args: [], description: "Open NimbleBrain's web UI in the default browser" },
476
- key: { args: [], description: "Enter the model key at a hidden prompt" },
477
- "local-model": {
478
- args: ["[model]"],
479
- description: `Run NimbleBrain's agents on a model served by Ollama (default ${DEFAULT_LOCAL_MODEL})`
480
- },
481
- telemetry: {
482
- args: ["[on|off|status]"],
483
- description: "Whether this install sends anonymous usage data"
484
- },
485
- up: { args: [], description: "Start NimbleBrain" },
486
- down: { args: [], description: "Stop NimbleBrain; data survives down" },
487
- logs: { args: [], description: "Recent runtime log lines" },
488
- update: {
489
- args: [],
490
- description: "Move to the newest release, keeping data, and refresh the connected agent's nimblebrain skill"
491
- },
492
- uninstall: { args: [], description: "Remove NimbleBrain and its data" },
493
- mcp: {
494
- args: ["<add|list|remove>"],
495
- description: "MCP servers in development; see mcp add, list and remove"
496
- }
497
- };
498
- var COMMANDS = Object.keys(COMMAND_SPECS);
499
- var TELEMETRY_ARGS = ["on", "off", "status"];
500
- var AGENTS = ["claude-code", "cursor", "codex", "none"];
501
- var DEFAULT_PORT = 27246;
502
- var FLAG_SPECS = {
503
- json: {
504
- type: "boolean",
505
- description: "One JSON object on stdout; progress and notices go to stderr"
506
- },
507
- yes: {
508
- type: "boolean",
509
- short: "y",
510
- description: "Take every default; implied when no terminal is attached"
511
- },
512
- agent: {
513
- type: "string",
514
- takes: "name",
515
- description: `The coding agent to connect: ${AGENTS.slice(0, -1).join(", ")} or ${AGENTS.at(-1)}`,
516
- commands: ["init"]
517
- },
518
- port: {
519
- type: "string",
520
- takes: "n",
521
- description: `Local port (default ${DEFAULT_PORT})`,
522
- commands: ["init", "doctor"]
523
- },
524
- home: {
525
- type: "string",
526
- takes: "dir",
527
- description: "Where the install lives (default ~/.nimblebrain-local, or NIMBLEBRAIN_HOME); a home with another folder name is a separate install"
528
- },
529
- provider: {
530
- type: "string",
531
- takes: "name",
532
- description: "The model provider for key (default anthropic); the installed release decides which it takes, and key lists them",
533
- commands: ["key"]
534
- },
535
- "local-model": {
536
- type: "string",
537
- takes: "model",
538
- description: "Run on this Ollama model instead of a hosted key",
539
- commands: ["init"]
540
- },
541
- runtime: {
542
- type: "string",
543
- takes: "tag",
544
- description: "The NimbleBrain release to install or update to (default the newest)",
545
- commands: ["init", "update"]
546
- },
547
- "no-open": {
548
- type: "boolean",
549
- description: "Do not open the web UI in the browser when init finishes",
550
- commands: ["init"]
551
- },
552
- telemetry: {
553
- type: "string",
554
- takes: "on|off",
555
- description: "The person's answer to sending anonymous usage data; without it, init asks or leaves it undecided",
556
- commands: ["init"]
557
- },
558
- name: {
559
- type: "string",
560
- takes: "name",
561
- description: "The server name (default from the server's card, else its URL)",
562
- commands: ["mcp add"]
563
- },
564
- workspace: {
565
- type: "string",
566
- takes: "id",
567
- description: "The workspace (default the one init connected, the first in status)",
568
- commands: ["mcp add", "mcp list", "mcp remove"]
569
- },
570
- help: {
571
- type: "boolean",
572
- short: "h",
573
- description: "The commands and flags; with --json, these, each command's answer and every error code as JSON"
574
- },
575
- version: { type: "boolean", short: "v", description: "This CLI's version" }
576
- };
577
- var options = Object.fromEntries(Object.entries(FLAG_SPECS).map(([name, f]) => [
578
- name,
579
- f.short ? { type: f.type, short: f.short } : { type: f.type }
580
- ]));
581
- function parse(argv) {
582
- const { values, positionals } = parseStrict(argv);
583
- const json = values.json === true;
584
- const port = values.port === undefined ? DEFAULT_PORT : Number(values.port);
585
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
586
- throw new CliError("USAGE", `--port must be a port number, not "${values.port}".`);
587
- }
588
- let agent;
589
- if (values.agent !== undefined) {
590
- if (!AGENTS.includes(values.agent)) {
591
- throw new CliError("AGENT_UNSUPPORTED", `Unknown agent "${values.agent}".`);
592
- }
593
- agent = values.agent;
594
- }
595
- const telemetry = telemetryFlag(values.telemetry);
596
- const flags = {
597
- json,
598
- yes: values.yes === true,
599
- agent,
600
- port,
601
- home: values.home,
602
- provider: values.provider,
603
- localModel: values["local-model"],
604
- runtime: values.runtime,
605
- telemetry,
606
- noOpen: values["no-open"] === true,
607
- name: values.name,
608
- workspace: values.workspace
609
- };
610
- if (values.help)
611
- return { kind: "help", flags };
612
- if (values.version)
613
- return { kind: "version", flags };
614
- const name = positionals[0] ?? "init";
615
- if (name === "help")
616
- return { kind: "help", flags };
617
- return {
618
- kind: "run",
619
- command: command(name, positionals),
620
- flags,
621
- arg: positionals[1],
622
- operand: positionals[2]
623
- };
624
- }
625
- function telemetryFlag(value) {
626
- if (value === undefined || value === "on" || value === "off")
627
- return value;
628
- throw new CliError("USAGE", `--telemetry must be on or off, not "${value}".`);
629
- }
630
- var MCP_SUBCOMMANDS = {
631
- add: { operand: "url", description: "Add an MCP server you run on this machine to a workspace" },
632
- list: { operand: null, description: "The servers in a workspace" },
633
- remove: { operand: "serverName", description: "Remove a server from a workspace" }
634
- };
635
- function command(name, positionals) {
636
- if (!COMMANDS.includes(name))
637
- throw new CliError("USAGE", `Unknown command "${name}".`);
638
- if (name === "mcp")
639
- return mcpCommand(positionals);
640
- const maxArgs = name === "telemetry" || name === "local-model" ? 2 : 1;
641
- if (positionals.length > maxArgs)
642
- throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
643
- const arg = positionals[1];
644
- if (name === "telemetry" && arg !== undefined && !TELEMETRY_ARGS.includes(arg))
645
- throw new CliError("USAGE", `telemetry takes on, off or status, not "${arg}".`);
646
- return name;
647
- }
648
- function mcpCommand(positionals) {
649
- const sub = positionals[1];
650
- if (sub === undefined || !Object.hasOwn(MCP_SUBCOMMANDS, sub))
651
- throw new CliError("USAGE", `mcp takes add <url>, list or remove <serverName>${sub === undefined ? "" : `, not "${sub}"`}.`);
652
- const { operand } = MCP_SUBCOMMANDS[sub];
653
- const maxArgs = operand === null ? 2 : 3;
654
- if (positionals.length > maxArgs)
655
- throw new CliError("USAGE", `Unexpected argument "${positionals[maxArgs]}".`);
656
- if (operand !== null && positionals[2] === undefined)
657
- throw new CliError("USAGE", `mcp ${sub} needs a ${operand}.`);
658
- return "mcp";
659
- }
660
- function parseStrict(argv) {
661
- try {
662
- return parseArgs({ args: argv, options, allowPositionals: true, strict: true });
663
- } catch (err) {
664
- throw new CliError("USAGE", err instanceof Error ? err.message : String(err));
665
- }
666
- }
667
- function wantsJson(argv) {
668
- return argv.includes("--json");
669
- }
670
-
671
- // src/compose.ts
672
- import { basename, join as join2 } from "node:path";
673
- var DEFAULT_PROJECT = "nimblebrain-local";
674
- function projectFor(home) {
675
- const slug = basename(home).toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^[^a-z0-9]+/, "").replace(/[^a-z0-9]+$/, "");
676
- if (!slug)
677
- return "nimblebrain";
678
- return slug.startsWith("nimblebrain") ? slug : `nimblebrain-${slug}`;
679
- }
680
- var volumeOf = (project) => `${project}_workspace`;
681
- var RAW = "https://raw.githubusercontent.com/NimbleBrainInc/nimblebrain";
682
- async function fetchCompose(deps, tag) {
683
- const res = await deps.getText(`${RAW}/${tag}/docker-compose.yml`, 15000);
684
- if (!res)
685
- throw new CliError("NETWORK", `Could not download the Compose file for ${tag}.`);
686
- if (res.status === 404) {
687
- throw new CliError("RUNTIME_UNSUPPORTED", `NimbleBrain ${tag} has no Compose file to install.`);
688
- }
689
- if (res.status !== 200) {
690
- throw new CliError("NETWORK", `Downloading the Compose file for ${tag} answered ${res.status}.`);
691
- }
692
- if (!res.body.includes("${NIMBLEBRAIN_TAG") || !res.body.includes("NIMBLEBRAIN_WEB_PORT")) {
693
- throw new CliError("RUNTIME_UNSUPPORTED", `NimbleBrain ${tag}'s Compose file does not take its image tag and port from .env.`);
694
- }
695
- return res.body;
696
- }
697
- function keyVars(composeText) {
698
- return [
699
- ...new Set([...composeText.matchAll(/\b([A-Z][A-Z0-9_]*_API_KEY)=\$\{\1\b/g)].map((m) => m[1] ?? ""))
700
- ];
701
- }
702
- function asksConsent(composeText) {
703
- return composeText.includes("NB_TELEMETRY_CONSENT");
704
- }
705
- function hostLoopback(composeText) {
706
- return composeText.includes("NB_HOST_LOOPBACK");
707
- }
708
- function providers(composeText) {
709
- return Object.fromEntries(keyVars(composeText).map((v) => [
710
- v.replace(/_API_KEY$/, "").replace(/_GENERATIVE_AI$/, "").toLowerCase(),
711
- v
712
- ]));
713
- }
714
- function composeEnv(deps, vars) {
715
- const env = { ...deps.env };
716
- for (const v of [
717
- ...vars,
718
- "NIMBLEBRAIN_TAG",
719
- "NIMBLEBRAIN_WEB_PORT",
720
- "COMPOSE_PROJECT_NAME",
721
- "NB_TELEMETRY_KEY",
722
- "NB_TELEMETRY_ID",
723
- "NB_TELEMETRY_CONSENT",
724
- "NB_LOCAL_MODEL_URL",
725
- "NB_LOCAL_MODEL",
726
- "NB_LOCAL_MODEL_CONTEXT"
727
- ]) {
728
- delete env[v];
729
- }
730
- return env;
731
- }
732
- var PLUGIN = { cmd: "docker", args: ["compose"] };
733
- var found = new WeakMap;
734
- function findCompose(deps) {
735
- let lookup = found.get(deps);
736
- if (!lookup) {
737
- lookup = lookUpCompose(deps);
738
- found.set(deps, lookup);
739
- }
740
- return lookup;
741
- }
742
- async function lookUpCompose(deps) {
743
- for (const program of [PLUGIN, { cmd: "docker-compose", args: [] }]) {
744
- const res = await deps.exec(program.cmd, [...program.args, "version", "--short"]);
745
- if (res.code === 0 && majorOf(res.stdout) >= 2)
746
- return { ...program, version: res.stdout.trim() };
747
- }
748
- return;
749
- }
750
- function majorOf(version) {
751
- return Number.parseInt(version.trim().replace(/^v/, ""), 10);
752
- }
753
- async function composeExec(deps, args, opts) {
754
- const program = await findCompose(deps) ?? PLUGIN;
755
- return deps.exec(program.cmd, [...program.args, ...args], opts);
756
- }
757
- async function compose(deps, home, args, timeoutMs = 120000) {
758
- const vars = keyVars(await deps.readText(paths(home).compose) ?? "");
759
- return composeExec(deps, args, {
760
- cwd: home,
761
- env: composeEnv(deps, vars),
762
- timeoutMs
763
- });
764
- }
765
- function startError(res) {
766
- const text = `${res.stderr}
767
- ${res.stdout}`;
768
- const last = text.trim().split(`
769
- `).filter((l) => l.trim()).pop() ?? "Compose failed.";
770
- if (/no such host|timeout|TLS handshake|connection refused|network is unreachable/i.test(text)) {
771
- return new CliError("NETWORK", last);
772
- }
773
- if (/port is already allocated|address already in use/i.test(text)) {
774
- return new CliError("PORT_IN_USE", last);
775
- }
776
- return new CliError("START_FAILED", last);
777
- }
778
- function setEnvLines(text, values) {
779
- const lines = text === "" ? [] : text.replace(/\n$/, "").split(`
780
- `);
781
- const seen = new Set;
782
- const out = lines.map((line) => {
783
- const name = line.match(/^([A-Z][A-Z0-9_]*)=/)?.[1];
784
- if (name && name in values) {
785
- seen.add(name);
786
- return `${name}=${values[name]}`;
787
- }
788
- return line;
789
- });
790
- for (const [name, value] of Object.entries(values))
791
- if (!seen.has(name))
792
- out.push(`${name}=${value}`);
793
- return `${out.join(`
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(`
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
+ ${t.join(`
794
13
  `)}
795
- `;
796
- }
797
- function keyProvider(envText, composeText) {
798
- const set = Object.entries(providers(composeText)).find(([, v]) => hasKey(envText, [v]));
799
- return set ? set[0] : null;
800
- }
801
- function hasKey(envText, vars) {
802
- return vars.some((v) => new RegExp(`^${v}=\\S`, "m").test(envText));
803
- }
804
- var paths = (home) => ({
805
- compose: join2(home, "docker-compose.yml"),
806
- env: join2(home, ".env"),
807
- instance: join2(home, "instance.json"),
808
- install: join2(home, "install.json")
809
- });
810
- var INSTANCE_JSON = `${JSON.stringify({ auth: { adapter: "dev" } }, null, 2)}
811
- `;
812
-
813
- // src/doctor.ts
814
- var SUPPORTED_ARCH = ["x86_64", "amd64", "aarch64", "arm64"];
815
- var MIN_MEMORY = 1.75 * 1024 ** 3;
816
- async function doctor(deps, port, portInUseByUs = false) {
817
- const log = recorder();
818
- await checkDocker(deps, log);
819
- const facts = await checkDaemon(deps, log);
820
- await checkCompose(deps, log);
821
- checkArch(facts.arch, log);
822
- checkMemory(facts, log);
823
- await checkPort(deps, port, portInUseByUs, log);
824
- return { ok: true, checks: log.checks, arch: facts.arch };
825
- }
826
- function recorder() {
827
- const checks = [];
828
- return {
829
- checks,
830
- pass: (check, detail) => {
831
- checks.push({ check, ok: true, detail });
832
- },
833
- fail: (check, code, detail, variant) => {
834
- checks.push({ check, ok: false, detail });
835
- throw new CliError(code, detail, { check, checks }, variant);
836
- }
837
- };
838
- }
839
- async function checkDocker(deps, log) {
840
- const version = await deps.exec("docker", ["--version"]);
841
- if (version.missing) {
842
- const variant = deps.platform !== "darwin" ? undefined : await deps.which("brew") ? "mac_brew" : "mac";
843
- log.fail("docker", "DOCKER_MISSING", "Docker is not installed.", variant);
844
- }
845
- log.pass("docker", version.stdout.trim());
846
- }
847
- async function checkDaemon(deps, log) {
848
- const info = await deps.exec("docker", ["info", "--format", "{{json .}}"]);
849
- if (info.code !== 0) {
850
- if (/permission denied/i.test(`${info.stderr}
851
- ${info.stdout}`)) {
852
- log.fail("docker-daemon", "DOCKER_PERMISSION", "This user may not use Docker.");
853
- }
854
- log.fail("docker-daemon", "DOCKER_NOT_RUNNING", "Docker is installed but not running.");
855
- }
856
- log.pass("docker-daemon", "running");
857
- return parseInfo(info.stdout);
858
- }
859
- async function checkCompose(deps, log) {
860
- const program = await findCompose(deps);
861
- if (!program) {
862
- const variant = deps.platform === "darwin" && await deps.which("brew") ? "brew" : undefined;
863
- log.fail("compose", "COMPOSE_MISSING", "Docker Compose v2 is not available.", variant);
864
- }
865
- log.pass("compose", program.cmd === "docker" ? program.version : `${program.version} (${program.cmd})`);
866
- }
867
- function checkArch(arch, log) {
868
- if (!SUPPORTED_ARCH.includes(arch)) {
869
- log.fail("arch", "ARCH_UNSUPPORTED", `No NimbleBrain image is published for ${arch || "this architecture"}.`);
870
- }
871
- log.pass("arch", arch);
872
- }
873
- function checkMemory({ memory, kind }, log) {
874
- if (memory > 0 && memory < MIN_MEMORY) {
875
- log.fail("memory", "LOW_MEMORY", `Docker has ${gib(memory)} of memory; NimbleBrain needs 2 GB.`, kind);
876
- }
877
- log.pass("memory", memory > 0 ? gib(memory) : "unknown");
878
- }
879
- async function checkPort(deps, port, ours, log) {
880
- if (ours)
881
- return log.pass("port", `${port} (this install)`);
882
- if (!await deps.portFree(port))
883
- log.fail("port", "PORT_IN_USE", `Port ${port} is in use.`);
884
- log.pass("port", String(port));
885
- }
886
- function parseInfo(stdout) {
887
- try {
888
- const info = JSON.parse(stdout);
889
- return {
890
- arch: typeof info.Architecture === "string" ? info.Architecture : "",
891
- memory: typeof info.MemTotal === "number" ? info.MemTotal : 0,
892
- kind: info.OperatingSystem === "Docker Desktop" ? "docker_desktop" : info.Name === "colima" ? "colima" : undefined
893
- };
894
- } catch {
895
- return { arch: "", memory: 0 };
896
- }
897
- }
898
- function gib(bytes) {
899
- return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
900
- }
901
-
902
- // src/answers.ts
903
- var STATE = {
904
- version: "The NimbleBrain runtime release installed, without the leading v",
905
- cli_version: "This CLI's version; it moves independently of the runtime",
906
- health: "ok when NimbleBrain answers, else down",
907
- url: "Where the web UI and API answer, on 127.0.0.1",
908
- workspaces: "Each workspace as {id, name, mcp}, mcp being its MCP URL; empty while down",
909
- agent: "{connected, skill}: the coding agent init connected (or null), and the nimblebrain skill's name when that agent has it (else null)",
910
- model_key: "set or missing: whether the install's .env holds a model key (never the key)",
911
- host_loopback: "Whether this release can reach a server on this machine; mcp add needs it, update brings it",
912
- local_model: "The Ollama model NimbleBrain's agents run on, or null for a hosted model key",
913
- 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",
914
- updates: "{cli?, runtime?}, each {current, latest}: what the last cached lookup found; absent when nothing is known or the check is off"
915
- };
916
- var OLLAMA_STARTED = "The command that started Ollama, when this run started it";
917
- var ANSWER_FIELDS = {
918
- init: {
919
- ...STATE,
920
- already: "true when an install was already here; it was reported, not changed",
921
- manual: "The settings to add to the coding agent by hand, when connecting it failed",
922
- opened: "Whether the browser opened, when init tried (a new install, a person at a terminal)",
923
- ollama_started: OLLAMA_STARTED
924
- },
925
- doctor: {
926
- checks: "Each check run, in order, as {check, ok, detail}",
927
- arch: "The CPU architecture Docker reports",
928
- ollama_started: `${OLLAMA_STARTED}; on a local model only`
929
- },
930
- status: STATE,
931
- open: {
932
- url: "The web UI's URL, to open by hand when opened is false",
933
- opened: "Whether a browser was started"
934
- },
935
- key: {
936
- provider: "The provider the key was entered for",
937
- model_key: "set"
938
- },
939
- "local-model": {
940
- local_model: "The model NimbleBrain's agents now run on (nimblebrain-<model>)",
941
- ollama_started: OLLAMA_STARTED
942
- },
943
- telemetry: { telemetry: STATE.telemetry },
944
- up: { ...STATE, ollama_started: OLLAMA_STARTED },
945
- down: { health: "down" },
946
- logs: { lines: "The runtime's last log lines, up to 100" },
947
- update: {
948
- ...STATE,
949
- already: "true when the install was already on that release",
950
- from: "The release moved from, as vX.Y.Z, when it moved",
951
- skill_update: "What happened to the connected agent's nimblebrain skill: updated, unchanged, not_installed or failed; absent with no agent"
952
- },
953
- uninstall: { removed: "true" },
954
- "mcp add": {
955
- serverName: "The name the server was added under",
956
- url: "The URL as given",
957
- dialed: "Where NimbleBrain, inside Docker, connects to it",
958
- placements: "Where the server's UI appears, from its Server Card",
959
- wsId: "The workspace it was added to",
960
- warning: "Why the server is not connected yet (it was added anyway), when it is not",
961
- notice: "Anything else NimbleBrain says about the server, when it says something"
962
- },
963
- "mcp list": {
964
- wsId: "The workspace listed",
965
- servers: "Each server as {serverName, displayName?, url?, state?, status?, statusReason?, toolCount?}"
966
- },
967
- "mcp remove": {
968
- serverName: "The server removed",
969
- wsId: "The workspace it was removed from"
970
- },
971
- help: {
972
- cli_version: "This CLI's version",
973
- commands: "Each command as {name, args, description, answer}",
974
- flags: "Each flag as {name, short?, takes, description, commands?}",
975
- errors: "Each error code as {code, fix, exit}"
976
- }
977
- };
978
-
979
- // src/help.ts
980
- var HELP_COMMAND = {
981
- name: "help",
982
- args: [],
983
- description: "These commands and flags; with --json, these, each command's answer and every error code as JSON",
984
- answer: { ...ANSWER_FIELDS.help }
985
- };
986
- function commands() {
987
- const list = Object.keys(COMMAND_SPECS).flatMap((name) => {
988
- if (name === "mcp") {
989
- return Object.keys(MCP_SUBCOMMANDS).map((sub) => {
990
- const spec = MCP_SUBCOMMANDS[sub];
991
- return {
992
- name: `mcp ${sub}`,
993
- args: spec.operand ? [`<${spec.operand}>`] : [],
994
- description: spec.description,
995
- answer: { ...ANSWER_FIELDS[`mcp ${sub}`] }
996
- };
997
- });
998
- }
999
- const spec = COMMAND_SPECS[name];
1000
- return [
1001
- {
1002
- name,
1003
- args: [...spec.args],
1004
- description: spec.description,
1005
- answer: { ...ANSWER_FIELDS[name] }
1006
- }
1007
- ];
1008
- });
1009
- return [...list, HELP_COMMAND];
1010
- }
1011
- function flags() {
1012
- return Object.entries(FLAG_SPECS).map(([name, spec]) => {
1013
- const f = {
1014
- name: `--${name}`,
1015
- takes: "takes" in spec ? spec.takes : null,
1016
- description: spec.description
1017
- };
1018
- if ("short" in spec)
1019
- f.short = `-${spec.short}`;
1020
- if ("commands" in spec)
1021
- f.commands = [...spec.commands];
1022
- return f;
1023
- });
1024
- }
1025
- function errors() {
1026
- return Object.keys(ERRORS).map((code) => ({
1027
- code,
1028
- fix: ERRORS[code],
1029
- exit: exitCodeOf(code)
1030
- }));
1031
- }
1032
- function describe(version) {
1033
- return {
1034
- ok: true,
1035
- cli_version: version,
1036
- commands: commands(),
1037
- flags: flags(),
1038
- errors: errors()
1039
- };
1040
- }
1041
- function helpText(version) {
1042
- const cmds = commands().map((c) => [[c.name, ...c.args].join(" "), c.description]);
1043
- const fls = flags().map((f) => [
1044
- [f.takes ? `${f.name} <${f.takes}>` : f.name, f.short].filter(Boolean).join(", "),
1045
- f.commands ? `${f.description}; for ${f.commands.join(", ")}` : f.description
1046
- ]);
1047
- const width = Math.max(...[...cmds, ...fls].map(([left]) => left.length)) + 2;
1048
- const row = ([left, right]) => ` ${left.padEnd(width)}${right}`;
1049
- return [
1050
- `nimblebrain ${version}: install and run NimbleBrain on this machine`,
1051
- "",
1052
- "Usage: npx nimblebrain [command] [flags]",
1053
- "",
1054
- "Commands:",
1055
- ...cmds.map(row),
1056
- "",
1057
- "Flags:",
1058
- ...fls.map(row),
1059
- "",
1060
- "What each command answers, and every error code and its fix: npx nimblebrain help --json",
1061
- ""
1062
- ].join(`
1063
- `);
1064
- }
1065
-
1066
- // src/agents.ts
1067
- import { join as join3 } from "node:path";
1068
- var SERVER_NAME = "nimblebrain";
1069
- async function connectAgent(deps, agent, mcpUrl) {
1070
- if (agent === "none")
1071
- return { connected: null };
1072
- const manual = manualSettings(agent, mcpUrl);
1073
- try {
1074
- if (agent === "claude-code") {
1075
- await deps.exec("claude", ["mcp", "remove", "-s", "user", SERVER_NAME]);
1076
- const res = await deps.exec("claude", [
1077
- "mcp",
1078
- "add",
1079
- "--transport",
1080
- "http",
1081
- "-s",
1082
- "user",
1083
- SERVER_NAME,
1084
- mcpUrl
1085
- ]);
1086
- return res.code === 0 ? { connected: agent } : { connected: null, manual };
1087
- }
1088
- if (agent === "codex") {
1089
- await deps.exec("codex", ["mcp", "remove", SERVER_NAME]);
1090
- const res = await deps.exec("codex", ["mcp", "add", SERVER_NAME, "--url", mcpUrl]);
1091
- return res.code === 0 ? { connected: agent } : { connected: null, manual };
1092
- }
1093
- await connectCursor(deps, mcpUrl);
1094
- return { connected: agent };
1095
- } catch {
1096
- return { connected: null, manual };
1097
- }
1098
- }
1099
- async function connectCursor(deps, mcpUrl) {
1100
- const path = join3(deps.home, ".cursor", "mcp.json");
1101
- const text = await deps.readText(path);
1102
- const config = text ? JSON.parse(text) : {};
1103
- config.mcpServers = { ...config.mcpServers ?? {}, [SERVER_NAME]: { url: mcpUrl } };
1104
- await deps.writeText(path, `${JSON.stringify(config, null, 2)}
1105
- `, 384);
1106
- }
1107
- function manualSettings(agent, mcpUrl) {
1108
- if (agent === "claude-code")
1109
- return `claude mcp add --transport http -s user ${SERVER_NAME} ${mcpUrl}`;
1110
- if (agent === "codex")
1111
- return `codex mcp add ${SERVER_NAME} --url ${mcpUrl}`;
1112
- return `Add to ~/.cursor/mcp.json: {"mcpServers":{"${SERVER_NAME}":{"url":"${mcpUrl}"}}}`;
1113
- }
1114
- async function installSkill(deps, agent) {
1115
- if (agent === "none")
1116
- return;
1117
- await deps.exec("npx", [
1118
- "-y",
1119
- "skills",
1120
- "add",
1121
- "nimblebraininc/skills",
1122
- "--skill",
1123
- SKILL_NAME,
1124
- "--agent",
1125
- agent,
1126
- "-g",
1127
- "-y"
1128
- ], { timeoutMs: 120000 });
1129
- }
1130
- async function refreshSkill(deps, agent) {
1131
- if (!await skillInstalled(deps, agent))
1132
- return "not_installed";
1133
- try {
1134
- const res = await deps.exec("npx", ["-y", "skills", "update", SKILL_NAME, "-g", "-y"], {
1135
- timeoutMs: 120000
1136
- });
1137
- if (res.code !== 0)
1138
- return "failed";
1139
- return /Updated \d+ skill/.test(res.stdout) ? "updated" : "unchanged";
1140
- } catch {
1141
- return "failed";
1142
- }
1143
- }
1144
- var SKILL_NAME = "nimblebrain";
1145
- function globalSkillsDir(deps, agent) {
1146
- if (agent === "claude-code")
1147
- return join3(deps.env.CLAUDE_CONFIG_DIR?.trim() || join3(deps.home, ".claude"), "skills");
1148
- if (agent === "codex")
1149
- return join3(deps.home, ".agents", "skills");
1150
- if (agent === "cursor")
1151
- return join3(deps.home, ".cursor", "skills");
1152
- return;
1153
- }
1154
- async function skillInstalled(deps, agent) {
1155
- const dir = globalSkillsDir(deps, agent);
1156
- if (!dir)
1157
- return null;
1158
- return await deps.readText(join3(dir, SKILL_NAME, "SKILL.md")) === undefined ? null : SKILL_NAME;
1159
- }
1160
-
1161
- // src/status.ts
1162
- import { join as join5 } from "node:path";
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}];
19
+ payload.issues.push(iss);
20
+ if (iss.continue !== true) ${G}_ab = true;
21
+ }
22
+ if (${G}_ab && ctx && ctx.abortEarly) {
23
+ payload.value = newResult;
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)}
29
+ }
30
+
31
+ if (${pg}) {
32
+ newResult[${ze}] = ${j}.value;
33
+ }
34
+ }
1163
35
 
1164
- // src/telemetry.ts
1165
- import { randomUUID } from "node:crypto";
1166
- import { join as join4 } from "node:path";
1167
- var TELEMETRY_KEY = "phc_qKmpYhdDtcFYZchu3KAKFFmYHG88nfUDPCFqxoAmbS7E";
1168
- var ENDPOINT = "https://us.i.posthog.com/batch/";
1169
- var QUESTION = "Help improve NimbleBrain by sending anonymous usage data? No prompts, content, names or keys are sent.";
1170
- var reportPath = (home) => join4(home, "telemetry-report.jsonl");
1171
- var idPath = (home) => join4(home, "telemetry-id");
1172
- var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1173
- var RELEASED = true;
1174
- function telemetryKey(deps) {
1175
- return deps.env.NIMBLEBRAIN_TELEMETRY_KEY ?? (RELEASED ? TELEMETRY_KEY : "");
1176
- }
1177
- function doNotTrack(deps) {
1178
- return deps.env.DO_NOT_TRACK === "1";
1179
- }
1180
- function lockedHere(deps) {
1181
- if (doNotTrack(deps) || deps.env.NB_TELEMETRY_DISABLED === "1")
1182
- return "do_not_track";
1183
- if (!telemetryKey(deps))
1184
- return "no_destination";
1185
- return;
1186
- }
1187
- function field(state, cli, locked) {
1188
- if (locked)
1189
- return { state: state === "undecided" ? "off" : state, locked };
1190
- if (state !== "undecided")
1191
- return { state };
1192
- return { state, ask: QUESTION, set: `${cli} telemetry on|off` };
1193
- }
1194
- function recorder2(deps, version, id) {
1195
- const events = [];
1196
- const self = {
1197
- id: id ?? randomUUID(),
1198
- record(event, properties = {}) {
1199
- if (lockedHere(deps))
1200
- return;
1201
- events.push({
1202
- event,
1203
- distinct_id: self.id,
1204
- timestamp: new Date().toISOString(),
1205
- properties: {
1206
- cli_version: version,
1207
- os: process.platform,
1208
- arch: process.arch,
1209
- node_version: process.version,
1210
- ...properties
36
+ `)}else if(!Ya)E.write(`
37
+ const ${j}_present = ${vo};
38
+ if (${j}.issues.length) {${X(j,ze)}
1211
39
  }
1212
- });
1213
- },
1214
- async settle(home, consent) {
1215
- try {
1216
- if (consent === "off" || lockedHere(deps)) {
1217
- await deps.remove(reportPath(home));
1218
- return;
40
+ if (!${j}_present && !${j}.issues.length) {
41
+ payload.issues.push({
42
+ code: "invalid_type",
43
+ expected: "nonoptional",
44
+ input: undefined,
45
+ path: [${ze}]
46
+ });
47
+ if (ctx && ctx.abortEarly) {
48
+ payload.value = newResult;
49
+ return payload;
50
+ }
1219
51
  }
1220
- const waiting = await readReport(deps, home);
1221
- const batch = [...waiting, ...events].map((e) => ({ ...e, distinct_id: self.id }));
1222
- if (consent === "on")
1223
- await send(deps, home, batch);
1224
- else if (events.length > 0)
1225
- await deps.writeText(reportPath(home), toLines(batch), 384);
1226
- } catch {} finally {
1227
- events.length = 0;
1228
- }
1229
- }
1230
- };
1231
- return self;
1232
- }
1233
- async function send(deps, home, batch) {
1234
- if (batch.length === 0)
1235
- return;
1236
- const res = await deps.postJson(ENDPOINT, { api_key: telemetryKey(deps), batch });
1237
- if (res && res.status < 300)
1238
- await deps.remove(reportPath(home));
1239
- else
1240
- await deps.writeText(reportPath(home), toLines(batch), 384);
1241
- }
1242
- async function installId(deps, home) {
1243
- if (lockedHere(deps))
1244
- return;
1245
- try {
1246
- const kept = (await deps.readText(idPath(home)))?.trim();
1247
- if (kept && UUID.test(kept))
1248
- return kept.toLowerCase();
1249
- const id = await reportId(deps, home) ?? randomUUID();
1250
- await deps.writeText(idPath(home), `${id}
1251
- `, 384);
1252
- return id;
1253
- } catch {
1254
- return;
1255
- }
1256
- }
1257
- async function reportId(deps, home) {
1258
- return (await readReport(deps, home))[0]?.distinct_id;
1259
- }
1260
- async function readReport(deps, home) {
1261
- const text = await deps.readText(reportPath(home));
1262
- if (!text)
1263
- return [];
1264
- return text.split(`
1265
- `).filter((l) => l.trim()).flatMap((l) => {
1266
- try {
1267
- return [JSON.parse(l)];
1268
- } catch {
1269
- return [];
1270
- }
1271
- });
1272
- }
1273
- var toLines = (events) => `${events.map((e) => JSON.stringify(e)).join(`
1274
- `)}
1275
- `;
1276
- function parseAnswer(answer) {
1277
- return /^n/i.test(answer.trim()) ? "off" : "on";
1278
- }
1279
- function seededConsent(envText) {
1280
- const seed = envText.match(/^NB_TELEMETRY_CONSENT=(on|off)\s*$/m)?.[1];
1281
- return seed === "on" || seed === "off" ? seed : "undecided";
1282
- }
1283
- async function currentTelemetry(deps, home, url) {
1284
- const here = lockedHere(deps);
1285
- const rt = await runtimeTelemetry(deps, url);
1286
- const state = rt?.consent ?? seededConsent(await deps.readText(join4(home, ".env")) ?? "");
1287
- const lock = here ?? (rt?.locked === "operator" || rt?.locked === "no_destination" ? rt.locked : undefined);
1288
- return field(state, invocation(deps, home), lock);
1289
- }
1290
- async function settleWaiting(deps, home, version) {
1291
- try {
1292
- const id = await reportId(deps, home);
1293
- if (!id)
1294
- return;
1295
- const install = JSON.parse(await deps.readText(join4(home, "install.json")) ?? "{}");
1296
- if (typeof install.port !== "number")
1297
- return;
1298
- const t = await currentTelemetry(deps, home, `http://127.0.0.1:${install.port}`);
1299
- await recorder2(deps, version, id).settle(home, t.locked ? "off" : t.state);
1300
- } catch {}
1301
- }
1302
- function envValues(deps, id, consent, asksFirst) {
1303
- const values = {
1304
- NB_TELEMETRY_KEY: asksFirst ? telemetryKey(deps) : ""
1305
- };
1306
- if (id)
1307
- values.NB_TELEMETRY_ID = id;
1308
- if (consent !== "undecided")
1309
- values.NB_TELEMETRY_CONSENT = consent;
1310
- return values;
1311
- }
1312
- async function runtimeTelemetry(deps, url) {
1313
- const res = await deps.postJson(`${url}/v1/tools/call`, {
1314
- server: "nb",
1315
- tool: "workspace_info",
1316
- arguments: {}
1317
- });
1318
- const t = res?.body?.structuredContent?.telemetry;
1319
- if (t?.consent !== "on" && t?.consent !== "off" && t?.consent !== "undecided")
1320
- return;
1321
- return { consent: t.consent, locked: typeof t.locked === "string" ? t.locked : undefined };
1322
- }
1323
- async function setRuntimeTelemetry(deps, url, consent) {
1324
- const res = await deps.postJson(`${url}/v1/tools/call`, {
1325
- server: "nb",
1326
- tool: "set_telemetry",
1327
- arguments: { consent }
1328
- });
1329
- const body = res?.body;
1330
- if (!res || res.status >= 300 || body?.isError) {
1331
- throw new CliError("TELEMETRY_LOCKED", body?.content?.[0]?.text ?? "NimbleBrain did not accept the answer.");
1332
- }
1333
- }
1334
- // package.json
1335
- var package_default = {
1336
- name: "nimblebrain",
1337
- version: "0.7.1",
1338
- description: "Install, run and connect NimbleBrain, the open-source runtime for agents and MCP apps, on this machine.",
1339
- license: "Apache-2.0",
1340
- type: "module",
1341
- repository: {
1342
- type: "git",
1343
- url: "git+https://github.com/NimbleBrainInc/nimblebrain.git",
1344
- directory: "packages/cli"
1345
- },
1346
- homepage: "https://nimblebrain.ai/developers",
1347
- bin: {
1348
- nimblebrain: "dist/nimblebrain.js"
1349
- },
1350
- files: ["dist"],
1351
- engines: {
1352
- node: ">=20"
1353
- },
1354
- scripts: {
1355
- build: "bun build src/bin.ts --target=node --outfile=dist/nimblebrain.js --banner='#!/usr/bin/env node'",
1356
- "build:release": "bun run build --define NIMBLEBRAIN_CLI_RELEASE=true",
1357
- test: "bun test --no-env-file test/"
1358
- }
1359
- };
1360
-
1361
- // src/version.ts
1362
- var VERSION = package_default.version;
1363
-
1364
- // src/status.ts
1365
- async function readInstall(deps, home) {
1366
- const text = await deps.readText(join5(home, "install.json"));
1367
- if (text === undefined)
1368
- return;
1369
- try {
1370
- const state = JSON.parse(text);
1371
- if (typeof state.version !== "string" || typeof state.port !== "number" || typeof state.project !== "string") {
1372
- return;
1373
- }
1374
- return state;
1375
- } catch {
1376
- return;
1377
- }
1378
- }
1379
- async function status(deps, home) {
1380
- const install = await readInstall(deps, home);
1381
- if (!install)
1382
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1383
- const url = installUrl(install);
1384
- const up = await isUp(deps, url);
1385
- const workspaces = up ? await readWorkspaces(deps, url) : [];
1386
- const composeText = await deps.readText(join5(home, "docker-compose.yml")) ?? "";
1387
- const vars = keyVars(composeText);
1388
- const envText = await deps.readText(join5(home, ".env")) ?? "";
1389
- const modelKey = hasKey(envText, vars) ? "set" : "missing";
1390
- return {
1391
- ok: true,
1392
- version: install.version,
1393
- cli_version: VERSION,
1394
- health: up ? "ok" : "down",
1395
- url,
1396
- workspaces,
1397
- agent: {
1398
- connected: install.agent ?? null,
1399
- skill: install.agent ? await skillInstalled(deps, install.agent) : null
1400
- },
1401
- model_key: modelKey,
1402
- host_loopback: hostLoopback(composeText),
1403
- local_model: localModelOf(envText) ?? null,
1404
- telemetry: await currentTelemetry(deps, home, url)
1405
- };
1406
- }
1407
- function installUrl(install) {
1408
- return `http://127.0.0.1:${install.port}`;
1409
- }
1410
- async function isUp(deps, url) {
1411
- const health = await deps.getJson(`${url}/v1/health`);
1412
- return health?.status === 200 && health.body?.status === "ok";
1413
- }
1414
- async function readWorkspaces(deps, url) {
1415
- const boot = await deps.getJson(`${url}/v1/bootstrap`);
1416
- if (boot?.status !== 200)
1417
- return [];
1418
- const body = boot.body;
1419
- return (body.workspaces ?? []).filter((w) => typeof w.id === "string" && typeof w.name === "string").map((w) => ({ id: w.id, name: w.name, mcp: `${url}/mcp/${w.id}` }));
1420
- }
1421
- function hasModelIn(r) {
1422
- return r.model_key === "set" || r.local_model !== null;
1423
- }
1424
52
 
1425
- // src/open.ts
1426
- function browserCommand(deps, url) {
1427
- const { env } = deps;
1428
- if (env.SSH_CONNECTION || env.SSH_TTY)
1429
- return;
1430
- if (deps.platform === "darwin")
1431
- return { cmd: "open", args: [url] };
1432
- if (deps.platform === "linux" && (env.DISPLAY || env.WAYLAND_DISPLAY))
1433
- return { cmd: "xdg-open", args: [url] };
1434
- return;
1435
- }
1436
- async function openBrowser(deps, url) {
1437
- const command = browserCommand(deps, url);
1438
- if (!command)
1439
- return false;
1440
- return deps.launch(command.cmd, command.args);
1441
- }
1442
- async function open(ctx) {
1443
- const { deps, home } = ctx;
1444
- const install = await readInstall(deps, home);
1445
- if (!install)
1446
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1447
- const url = installUrl(install);
1448
- if (!await isUp(deps, url))
1449
- throw new CliError("NOT_RUNNING", "NimbleBrain is not running.", { url });
1450
- return { ok: true, url, opened: await openBrowser(deps, url) };
1451
- }
53
+ if (${j}_present) {
54
+ newResult[${ze}] = ${j}.value;
55
+ }
1452
56
 
1453
- // src/release.ts
1454
- var REFS_URL = "https://github.com/NimbleBrainInc/nimblebrain.git/info/refs?service=git-upload-pack";
1455
- var VERSION2 = /^v\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;
1456
- var MIN_RUNTIME = "v0.73.0";
1457
- async function runtimeTag(deps, requested) {
1458
- const pinned = requested ?? deps.env.NIMBLEBRAIN_TAG;
1459
- let tag;
1460
- if (pinned) {
1461
- if (!VERSION2.test(pinned)) {
1462
- throw new CliError("USAGE", `"${pinned}" is not a runtime release tag like v1.2.3.`);
1463
- }
1464
- tag = pinned;
1465
- } else {
1466
- tag = await newestRuntime(deps);
1467
- }
1468
- if (compareVersions(tag, MIN_RUNTIME) < 0) {
1469
- throw new CliError("RUNTIME_UNSUPPORTED", `This CLI installs NimbleBrain ${MIN_RUNTIME} or newer, not ${tag}.`);
1470
- }
1471
- return tag;
1472
- }
1473
- async function newestRuntime(deps, timeoutMs = 1e4) {
1474
- const res = await deps.getText(REFS_URL, timeoutMs);
1475
- if (res && res.status !== 200) {
1476
- throw new CliError("NETWORK", `GitHub answered ${res.status} when asked for the newest NimbleBrain release. Pass --runtime vX.Y.Z to skip the lookup.`);
1477
- }
1478
- const names = [...(res?.body ?? "").matchAll(/refs\/tags\/([^\s\0^]+)/g)].map((m) => m[1] ?? "");
1479
- const newest = newestRelease(names);
1480
- if (!newest)
1481
- throw new CliError("NETWORK", "Could not find the newest NimbleBrain release.");
1482
- return newest;
1483
- }
1484
- function newestRelease(tags) {
1485
- const plain = tags.filter((t) => /^v\d+\.\d+\.\d+$/.test(t));
1486
- return plain.sort(compareVersions).pop();
1487
- }
1488
- function compareVersions(a, b) {
1489
- const [coreA = "", preA] = a.replace(/^v/, "").split(/-(.*)/s);
1490
- const [coreB = "", preB] = b.replace(/^v/, "").split(/-(.*)/s);
1491
- const core = compareIdentifiers(coreA.split("."), coreB.split("."));
1492
- if (core !== 0 || !preA && !preB)
1493
- return core;
1494
- if (!preA || !preB)
1495
- return preA ? -1 : 1;
1496
- return compareIdentifiers(preA.split("."), preB.split("."));
1497
- }
1498
- function compareIdentifiers(a, b) {
1499
- for (let i = 0;i < Math.min(a.length, b.length); i++) {
1500
- const order = compareIdentifier(a[i] ?? "", b[i] ?? "");
1501
- if (order !== 0)
1502
- return order;
1503
- }
1504
- return a.length - b.length;
1505
- }
1506
- function compareIdentifier(x, y) {
1507
- if (x === y)
1508
- return 0;
1509
- const xn = /^\d+$/.test(x);
1510
- const yn = /^\d+$/.test(y);
1511
- if (xn && yn)
1512
- return Number(x) - Number(y);
1513
- if (xn !== yn)
1514
- return xn ? -1 : 1;
1515
- return x < y ? -1 : 1;
1516
- }
57
+ `);else if(E.write(`
58
+ if (${j}.issues.length) {${X(j,ze)}
59
+ }
60
+ `),$o==="defaulted")E.write(`newResult[${ze}] = ${j}.value;`);else E.write(`
61
+ if (${j}.value !== undefined || ${vo}) {
62
+ newResult[${ze}] = ${j}.value;
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>
1517
65
 
1518
- // src/lifecycle.ts
1519
- var START_TIMEOUT_MS = 15 * 60000;
1520
- var HEALTH_TIMEOUT_MS = 3 * 60000;
1521
- var asks = ({ deps, flags }) => deps.interactive && !flags.yes && !flags.json;
1522
- var yes = (answer) => /^(y|yes)?$/i.test(answer.trim());
1523
- function confirmOllamaStart(ctx, unasked) {
1524
- return async (command) => {
1525
- if (!asks(ctx))
1526
- return unasked;
1527
- const login = command.startsWith("brew services") ? " It then also starts at login." : "";
1528
- return yes(await ctx.deps.prompt(`Ollama isn't running. Start it with \`${command}\`?${login} [Y/n] `));
1529
- };
1530
- }
1531
- async function init(ctx) {
1532
- const { deps, flags, home } = ctx;
1533
- if (await readInstall(deps, home))
1534
- return { ...await status(deps, home), already: true };
1535
- const consent = await chooseConsent(ctx);
1536
- const id = await foreignFile(deps, home) ? undefined : await installId(deps, home);
1537
- const rec = recorder2(deps, ctx.version, id ?? await reportId(deps, home));
1538
- const begun = Date.now();
1539
- rec.record("cli.init_started", { agent: flags.agent ?? null, interactive: deps.interactive });
1540
- try {
1541
- return await openWhenDone(ctx, await install(ctx, consent, rec, begun));
1542
- } catch (err) {
1543
- if (!(err instanceof CliError))
1544
- throw err;
1545
- if (err.code !== "CANCELLED" || consent !== "undecided")
1546
- await settleFailure(rec, home, consent, err);
1547
- throw err.with({ telemetry: field(consent, invocation(deps, home), lockedHere(deps)) });
1548
- }
1549
- }
1550
- async function openWhenDone(ctx, result) {
1551
- const { deps, flags } = ctx;
1552
- if (!deps.interactive || flags.json || flags.noOpen)
1553
- return result;
1554
- if (result.health !== "ok" || !hasModelIn(result))
1555
- return result;
1556
- return { ...result, opened: await openBrowser(deps, result.url) };
1557
- }
1558
- async function settleFailure(rec, home, consent, err) {
1559
- const check = typeof err.detail.check === "string" ? err.detail.check : undefined;
1560
- rec.record(check ? "cli.doctor_failed" : "cli.init_failed", { error: err.code, check });
1561
- await rec.settle(home, consent);
1562
- }
1563
- async function chooseConsent(ctx) {
1564
- if (lockedHere(ctx.deps))
1565
- return "off";
1566
- if (ctx.flags.telemetry)
1567
- return ctx.flags.telemetry;
1568
- if (!asks(ctx))
1569
- return "undecided";
1570
- const consent = parseAnswer(await ctx.deps.prompt(`${QUESTION} [Y/n] `));
1571
- const cli = invocation(ctx.deps, ctx.home);
1572
- ctx.deps.say(consent === "on" ? `Sending anonymous usage data. Turn it off any time: ${cli} telemetry off` : `No usage data will be sent. Turn it on any time: ${cli} telemetry on`);
1573
- return consent;
1574
- }
1575
- async function install(ctx, consent, rec, begun) {
1576
- const { deps, flags, home } = ctx;
1577
- await doctor(deps, flags.port);
1578
- const project = await guardOurs(deps, home);
1579
- const tag = await runtimeTag(deps, flags.runtime);
1580
- const composeText = await fetchCompose(deps, tag);
1581
- await confirmStart(ctx, tag);
1582
- await writeInstallFiles(deps, home, project, tag, flags.port, composeText, envValues(deps, lockedHere(deps) ? undefined : rec.id, consent, asksConsent(composeText)));
1583
- const envText = await deps.readText(paths(home).env) ?? "";
1584
- const hasModel = hasKey(envText, keyVars(composeText)) || localModelOf(envText) !== undefined;
1585
- const local = flags.localModel ?? (!hasModel && asks(ctx) && takesLocalModel(composeText) ? await chooseModelSource(deps) : undefined);
1586
- let ollamaStarted;
1587
- if (local)
1588
- ollamaStarted = (await useLocalModel(ctx, composeText, local)).started;
1589
- else if (!hasModel && asks(ctx))
1590
- await enterKey(ctx, false);
1591
- return carryingStarted(ollamaStarted, async () => {
1592
- deps.say(`Starting NimbleBrain ${tag}. The first start downloads about 2 GB of images.`);
1593
- await start(deps, home, flags.port);
1594
- const state = {
1595
- version: tag.replace(/^v/, ""),
1596
- port: flags.port,
1597
- project
1598
- };
1599
- await writeState(deps, home, state);
1600
- const manual = await connectChosenAgent(ctx, state);
1601
- if (state.agent)
1602
- rec.record("cli.agent_connected", { agent: state.agent });
1603
- const result = {
1604
- ...await status(deps, home),
1605
- manual,
1606
- ollama_started: ollamaStarted
1607
- };
1608
- const finalEnv = await deps.readText(paths(home).env) ?? "";
1609
- rec.record("cli.init_completed", {
1610
- duration_ms: Date.now() - begun,
1611
- model_key: result.model_key,
1612
- provider: localModelOf(finalEnv) ? "ollama" : keyProvider(finalEnv, composeText),
1613
- agent: state.agent ?? null
1614
- });
1615
- await rec.settle(home, consent);
1616
- return { ...result };
1617
- });
1618
- }
1619
- async function confirmStart(ctx, tag) {
1620
- if (!asks(ctx))
1621
- return;
1622
- const answer = await ctx.deps.prompt(`Start NimbleBrain ${tag} at http://127.0.0.1:${ctx.flags.port}? [Y/n] `);
1623
- if (/^n/i.test(answer))
1624
- throw new CliError("CANCELLED", "Nothing was installed.");
1625
- }
1626
- async function connectChosenAgent(ctx, state) {
1627
- const { deps, flags, home } = ctx;
1628
- const agent = flags.agent ?? (asks(ctx) ? await chooseAgent(deps) : undefined);
1629
- if (!agent || agent === "none")
1630
- return;
1631
- const first = (await status(deps, home)).workspaces[0];
1632
- if (!first)
1633
- return;
1634
- const conn = await connectAgent(deps, agent, first.mcp);
1635
- if (conn.connected) {
1636
- state.agent = conn.connected;
1637
- await installSkill(deps, conn.connected);
1638
- await writeState(deps, home, state);
1639
- }
1640
- return conn.manual;
1641
- }
1642
- async function up(ctx) {
1643
- const { deps, home } = ctx;
1644
- const install = await requireInstall(ctx);
1645
- const local = localModelOf(await deps.readText(paths(home).env) ?? "");
1646
- const ollama = local ? await ensureOllama(deps, confirmOllamaStart(ctx, true)).catch((err) => {
1647
- if (err instanceof CliError)
1648
- return err;
1649
- throw err;
1650
- }) : undefined;
1651
- const started = ollama instanceof CliError ? ollama.detail.ollama_started : ollama?.started;
1652
- const result = await carryingStarted(started, async () => {
1653
- await start(deps, home, install.port);
1654
- return status(deps, home);
1655
- });
1656
- if (ollama instanceof CliError) {
1657
- throw ollama.with({ ...result }, `NimbleBrain is running, but ${lowerFirst(ollama.message)}`);
1658
- }
1659
- return { ...result, ollama_started: ollama?.started };
1660
- }
1661
- var lowerFirst = (s) => s.charAt(0).toLowerCase() + s.slice(1);
1662
- async function down(ctx) {
1663
- await requireInstall(ctx);
1664
- const res = await compose(ctx.deps, ctx.home, ["down"]);
1665
- if (res.code !== 0)
1666
- throw startError(res);
1667
- return { ok: true, health: "down" };
1668
- }
1669
- async function logs(ctx) {
1670
- await requireInstall(ctx);
1671
- const res = await compose(ctx.deps, ctx.home, [
1672
- "logs",
1673
- "--no-color",
1674
- "--tail",
1675
- "100",
1676
- "platform"
1677
- ]);
1678
- if (res.code !== 0)
1679
- throw startError(res);
1680
- return { ok: true, lines: res.stdout.split(`
1681
- `).filter((l) => l.trim()) };
1682
- }
1683
- async function update(ctx) {
1684
- const { deps, home } = ctx;
1685
- const install = await requireInstall(ctx);
1686
- const tag = await runtimeTag(deps, ctx.flags.runtime);
1687
- const from = `v${install.version}`;
1688
- const order = compareVersions(tag, from);
1689
- if (order === 0) {
1690
- const skill_update = await refreshAgentSkill(deps, install);
1691
- return { ...await status(deps, home), already: true, ...skill_update };
1692
- }
1693
- if (order < 0) {
1694
- throw new CliError("USAGE", `${tag} is older than the installed ${from}; NimbleBrain does not move backwards.`);
1695
- }
1696
- const composeText = await fetchCompose(deps, tag);
1697
- await writeInstallFiles(deps, home, install.project, tag, install.port, composeText);
1698
- deps.say(`Updating NimbleBrain ${from} → ${tag}.`);
1699
- const pull = await compose(deps, home, ["pull"], START_TIMEOUT_MS);
1700
- if (pull.code !== 0)
1701
- throw startError(pull);
1702
- await start(deps, home, install.port);
1703
- await writeState(deps, home, { ...install, version: tag.replace(/^v/, "") });
1704
- const skill_update = await refreshAgentSkill(deps, install);
1705
- return { ...await status(deps, home), from, ...skill_update };
1706
- }
1707
- async function refreshAgentSkill(deps, install) {
1708
- if (!install.agent || install.agent === "none")
1709
- return {};
1710
- return { skill_update: await refreshSkill(deps, install.agent) };
1711
- }
1712
- async function uninstall(ctx) {
1713
- const { deps, flags, home } = ctx;
1714
- const install = await requireInstall(ctx);
1715
- if (!flags.yes) {
1716
- if (!deps.interactive || flags.json) {
1717
- throw new CliError("CANCELLED", "Removing deletes every conversation; pass --yes to confirm.");
1718
- }
1719
- const answer = await deps.prompt("Remove NimbleBrain and every conversation in it? [y/N] ");
1720
- if (!/^y/i.test(answer))
1721
- throw new CliError("CANCELLED", "Nothing was removed.");
1722
- }
1723
- const res = await compose(deps, home, ["down", "-v", "--rmi", "all"], START_TIMEOUT_MS);
1724
- if (res.code !== 0)
1725
- throw startError(res);
1726
- if (install.agent === "claude-code")
1727
- await deps.exec("claude", ["mcp", "remove", "-s", "user", SERVER_NAME]);
1728
- if (install.agent === "codex")
1729
- await deps.exec("codex", ["mcp", "remove", SERVER_NAME]);
1730
- for (const file of [...Object.values(paths(home)), reportPath(home), idPath(home)])
1731
- await deps.remove(file);
1732
- await deps.remove(home);
1733
- return { ok: true, removed: true };
1734
- }
1735
- async function telemetry(ctx) {
1736
- const { deps, home } = ctx;
1737
- const install = await requireInstall(ctx);
1738
- const url = `http://127.0.0.1:${install.port}`;
1739
- if (ctx.arg !== "on" && ctx.arg !== "off") {
1740
- return { ok: true, telemetry: (await status(deps, home)).telemetry };
1741
- }
1742
- const here = lockedHere(deps);
1743
- if (here) {
1744
- throw new CliError("TELEMETRY_LOCKED", here === "do_not_track" ? "DO_NOT_TRACK (or NB_TELEMETRY_DISABLED) is set, so telemetry stays off." : "This CLI has nowhere to send telemetry.");
1745
- }
1746
- const rt = await runtimeTelemetry(deps, url);
1747
- if (!rt)
1748
- throw new CliError("NOT_RUNNING", "NimbleBrain is not running, so it cannot record the answer.");
1749
- await setRuntimeTelemetry(deps, url, ctx.arg);
1750
- const p = paths(home);
1751
- await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { NB_TELEMETRY_CONSENT: ctx.arg }), 384);
1752
- const rec = recorder2(deps, ctx.version, await reportId(deps, home));
1753
- await rec.settle(home, ctx.arg);
1754
- return { ok: true, telemetry: field(ctx.arg, invocation(deps, home)) };
1755
- }
1756
- async function key(ctx) {
1757
- if (!ctx.deps.interactive) {
1758
- throw new CliError("NEEDS_TERMINAL", "`key` asks for a model key at a hidden prompt.");
1759
- }
1760
- await requireInstall(ctx);
1761
- return enterKey(ctx, true);
1762
- }
1763
- async function enterKey(ctx, restart) {
1764
- const { deps, flags, home } = ctx;
1765
- const offered = providers(await deps.readText(paths(home).compose) ?? "");
1766
- const names = Object.keys(offered);
1767
- let provider = flags.provider;
1768
- deps.say("NimbleBrain's own agents run on a model key you give it, billed by that provider.");
1769
- if (!provider) {
1770
- const answer = await deps.prompt(`Model provider (${names.join(", ")}) [anthropic]: `);
1771
- provider = answer || "anthropic";
1772
- }
1773
- const variable = offered[provider];
1774
- if (!variable)
1775
- throw new CliError("USAGE", `Unknown provider "${provider}"; one of ${names.join(", ")}.`);
1776
- const value = await deps.prompt(`${variable} (nothing is shown as you type): `, { hidden: true });
1777
- if (!value)
1778
- throw new CliError("CANCELLED", "No key was entered.");
1779
- const p = paths(home);
1780
- await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", { [variable]: value }), 384);
1781
- if (restart) {
1782
- const install = await readInstall(deps, home);
1783
- await start(deps, home, install?.port ?? flags.port);
1784
- }
1785
- return { ok: true, provider, model_key: "set" };
1786
- }
1787
- async function localModel(ctx) {
1788
- const install = await requireInstall(ctx);
1789
- const composeText = await ctx.deps.readText(paths(ctx.home).compose) ?? "";
1790
- const model = ctx.arg ?? ctx.flags.localModel ?? DEFAULT_LOCAL_MODEL;
1791
- const { name, started } = await useLocalModel(ctx, composeText, model);
1792
- await carryingStarted(started, () => start(ctx.deps, ctx.home, install.port));
1793
- return { ok: true, local_model: name, ollama_started: started };
1794
- }
1795
- async function carryingStarted(started, next) {
1796
- try {
1797
- return await next();
1798
- } catch (err) {
1799
- if (err instanceof CliError && started)
1800
- throw err.with({ ollama_started: started });
1801
- throw err;
1802
- }
1803
- }
1804
- async function chooseModelSource(deps) {
1805
- deps.say("NimbleBrain's own agents need a model: a hosted one with your API key, or a local one through Ollama (free, slower; https://docs.nimblebrain.ai/config/local-models/).");
1806
- const answer = (await deps.prompt("Model (hosted, local) [hosted]: ")).trim().toLowerCase();
1807
- return answer === "local" ? DEFAULT_LOCAL_MODEL : undefined;
1808
- }
1809
- async function useLocalModel(ctx, composeText, model) {
1810
- const { deps, home } = ctx;
1811
- if (!takesLocalModel(composeText)) {
1812
- throw new CliError("RUNTIME_UNSUPPORTED", "This release's runtime takes no local model; a newer release does.");
1813
- }
1814
- const { values, started } = await setupLocalModel(deps, model, {
1815
- start: confirmOllamaStart(ctx, true),
1816
- pull: (m) => confirmPull(ctx, m)
1817
- });
1818
- const p = paths(home);
1819
- await deps.writeText(p.env, setEnvLines(await deps.readText(p.env) ?? "", values), 384);
1820
- return { name: values.NB_LOCAL_MODEL ?? model, started };
1821
- }
1822
- async function confirmPull(ctx, model) {
1823
- if (!asks(ctx))
1824
- return true;
1825
- return yes(await ctx.deps.prompt(`Download ${model} with Ollama? It is several GB. [Y/n] `));
1826
- }
1827
- async function chooseAgent(deps) {
1828
- deps.say("A coding agent you connect can use NimbleBrain's tools. NimbleBrain's own agents still run on the model key above.");
1829
- const answer = await deps.prompt(`Connect a coding agent? (${AGENTS.join(", ")}) [none]: `);
1830
- return AGENTS.includes(answer) ? answer : "none";
1831
- }
1832
- async function start(deps, home, port) {
1833
- const res = await compose(deps, home, ["up", "-d", "--no-build"], START_TIMEOUT_MS);
1834
- if (res.code !== 0)
1835
- throw startError(res);
1836
- await waitHealthy(deps, port);
1837
- }
1838
- async function waitHealthy(deps, port) {
1839
- const url = `http://127.0.0.1:${port}/v1/health`;
1840
- for (let waited = 0;waited <= HEALTH_TIMEOUT_MS; waited += 2000) {
1841
- const res = await deps.getJson(url);
1842
- if (res?.status === 200)
1843
- return;
1844
- await deps.sleep(2000);
1845
- }
1846
- throw new CliError("HEALTH_TIMEOUT", "NimbleBrain did not report healthy within 3 minutes.");
1847
- }
1848
- async function writeInstallFiles(deps, home, project, tag, port, composeText, extra = {}) {
1849
- const p = paths(home);
1850
- await deps.writeText(p.compose, composeText);
1851
- if (await deps.readText(p.instance) === undefined)
1852
- await deps.writeText(p.instance, INSTANCE_JSON);
1853
- const env = setEnvLines(await deps.readText(p.env) ?? "", {
1854
- COMPOSE_PROJECT_NAME: project,
1855
- NIMBLEBRAIN_TAG: tag,
1856
- NIMBLEBRAIN_WEB_PORT: String(port),
1857
- ...extra
1858
- });
1859
- await deps.writeText(p.env, env, 384);
1860
- }
1861
- async function writeState(deps, home, state) {
1862
- await deps.writeText(paths(home).install, `${JSON.stringify(state, null, 2)}
1863
- `);
1864
- }
1865
- async function requireInstall({ deps, home }) {
1866
- const install = await readInstall(deps, home);
1867
- if (!install)
1868
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1869
- return install;
1870
- }
1871
- async function guardOurs(deps, home) {
1872
- const project = projectFor(home);
1873
- const marked = await markedProject(deps, home);
1874
- if (marked)
1875
- return marked;
1876
- const file = await foreignFile(deps, home);
1877
- if (file)
1878
- throw new CliError("NOT_OURS", `${file} already exists and this CLI did not write it.`);
1879
- const projects = await composeExec(deps, ["ls", "-a", "--format", "json"]);
1880
- const taken = projects.code === 0 && listsProject(projects.stdout, project);
1881
- const volumes = await deps.exec("docker", [
1882
- "volume",
1883
- "ls",
1884
- "-q",
1885
- "--filter",
1886
- `name=^${volumeOf(project)}$`
1887
- ]);
1888
- if (taken || volumes.stdout.trim() !== "") {
1889
- throw new CliError("NOT_OURS", `Docker already has a "${project}" project or volume that this install did not make.`);
1890
- }
1891
- return project;
1892
- }
1893
- async function markedProject(deps, home) {
1894
- const env = await deps.readText(paths(home).env);
1895
- const marked = env?.match(/^COMPOSE_PROJECT_NAME=(.*?)\r?$/m)?.[1];
1896
- return marked === projectFor(home) || marked === DEFAULT_PROJECT ? marked : undefined;
1897
- }
1898
- async function foreignFile(deps, home) {
1899
- if (await markedProject(deps, home))
1900
- return;
1901
- for (const file of Object.values(paths(home))) {
1902
- if (await deps.readText(file) !== undefined)
1903
- return file;
1904
- }
1905
- return;
1906
- }
1907
- function listsProject(stdout, project) {
1908
- try {
1909
- const list = JSON.parse(stdout);
1910
- return Array.isArray(list) && list.some((p) => p?.Name === project);
1911
- } catch {
1912
- return false;
1913
- }
1914
- }
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(`
1915
67
 
1916
- // src/mcp.ts
1917
- async function mcp(ctx) {
1918
- const sub = ctx.arg;
1919
- const target = await reach(ctx, sub === "add");
1920
- if (sub === "add")
1921
- return add(target, ctx.operand ?? "", ctx.flags.name);
1922
- if (sub === "list")
1923
- return list(target);
1924
- return remove(target, ctx.operand ?? "");
1925
- }
1926
- var RUNTIME_CODES = [
1927
- "DIRECT_URL_NOT_ALLOWED",
1928
- "URL_NOT_LOOPBACK",
1929
- "URL_INVALID",
1930
- "INVALID_SERVER_NAME",
1931
- "NAME_TAKEN",
1932
- "NAME_IS_CATALOG_ENTRY"
1933
- ];
1934
- var ADD_TIMEOUT_MS = 60000;
1935
- var CALL_TIMEOUT_MS = 15000;
1936
- async function reach(ctx, adding) {
1937
- const { deps, home, flags } = ctx;
1938
- const install = await readInstall(deps, home);
1939
- if (!install)
1940
- throw new CliError("NOT_INSTALLED", `No NimbleBrain install in ${home}.`);
1941
- if (adding && !hostLoopback(await deps.readText(paths(home).compose) ?? "")) {
1942
- throw new CliError("UPDATE_REQUIRED", `NimbleBrain ${install.version} cannot reach a server on this machine.`, { version: install.version });
1943
- }
1944
- const url = `http://127.0.0.1:${install.port}`;
1945
- if (!await isUp(deps, url))
1946
- throw new CliError("NOT_RUNNING", "NimbleBrain is not running.");
1947
- const workspaces = await readWorkspaces(deps, url);
1948
- const ws = flags.workspace ? workspaces.find((w) => w.id === flags.workspace) : workspaces[0];
1949
- if (!ws) {
1950
- throw new CliError("WORKSPACE_NOT_FOUND", flags.workspace ? `No workspace "${flags.workspace}" on this install.` : "This install has no workspace.", { workspaces: workspaces.map((w) => w.id) });
1951
- }
1952
- return { ctx, url, wsId: ws.id };
1953
- }
1954
- async function add(t, serverUrl, name) {
1955
- const protocol = URL.canParse(serverUrl) ? new URL(serverUrl).protocol : "";
1956
- if (protocol !== "http:" && protocol !== "https:") {
1957
- throw new CliError("URL_INVALID", `"${serverUrl}" is not an http or https URL.`);
1958
- }
1959
- const install = { kind: "direct-url", url: serverUrl, ...name ? { serverName: name } : {} };
1960
- const s = await call(t, {
1961
- action: "install",
1962
- entry: { id: "direct-url", name: name ?? serverUrl, install }
1963
- }, ADD_TIMEOUT_MS);
1964
- return {
1965
- ok: true,
1966
- serverName: s.serverName,
1967
- url: s.url,
1968
- dialed: s.dialed,
1969
- placements: s.placements,
1970
- wsId: s.wsId ?? t.wsId,
1971
- ...s.warning ? { warning: s.warning } : {},
1972
- ...s.notice ? { notice: s.notice } : {}
1973
- };
1974
- }
1975
- async function list(t) {
1976
- const s = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1977
- const installed = Array.isArray(s.installed) ? s.installed : [];
1978
- const servers = installed.map((e) => ({
1979
- serverName: e.serverName,
1980
- displayName: e.displayName,
1981
- url: e.url,
1982
- state: e.state,
1983
- status: e.status,
1984
- statusReason: e.statusReason,
1985
- toolCount: e.toolCount
1986
- }));
1987
- return { ok: true, wsId: t.wsId, servers };
1988
- }
1989
- async function remove(t, serverName) {
1990
- const listed = await call(t, { action: "list_installed", scope: "workspace" }, CALL_TIMEOUT_MS);
1991
- const installed = Array.isArray(listed.installed) ? listed.installed : [];
1992
- if (!installed.some((e) => e.serverName === serverName)) {
1993
- throw new CliError("SERVER_NOT_FOUND", `This workspace has no server named "${serverName}".`, {
1994
- wsId: t.wsId
1995
- });
1996
- }
1997
- await call(t, { action: "uninstall", serverName }, CALL_TIMEOUT_MS);
1998
- return { ok: true, serverName, wsId: t.wsId };
1999
- }
2000
- async function call(t, args, timeoutMs) {
2001
- const res = await t.ctx.deps.postJson(`${t.url}/v1/workspaces/${encodeURIComponent(t.wsId)}/tools/call`, { server: "nb", tool: "manage_connectors", arguments: args }, timeoutMs);
2002
- if (!res)
2003
- throw new CliError("NOT_RUNNING", "NimbleBrain did not answer.");
2004
- const body = res.body ?? {};
2005
- if (res.status === 404 && body.error === "workspace_error") {
2006
- throw new CliError("WORKSPACE_NOT_FOUND", `No workspace "${t.wsId}" on this install.`);
2007
- }
2008
- if (res.status < 200 || res.status >= 300) {
2009
- const why = typeof body.message === "string" ? body.message : `HTTP ${res.status}`;
2010
- throw new CliError("REQUEST_FAILED", `NimbleBrain refused the request: ${why}`, {
2011
- status: res.status
2012
- });
2013
- }
2014
- const text = body.content?.find((c) => c.type === "text")?.text;
2015
- if (body.isError) {
2016
- const code = body.structuredContent?.error;
2017
- const known = RUNTIME_CODES.find((c) => c === code);
2018
- throw new CliError(known ?? "REQUEST_FAILED", text ?? "NimbleBrain refused the request.");
2019
- }
2020
- return body.structuredContent ?? {};
2021
- }
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(`
2022
69
 
2023
- // src/updates.ts
2024
- import { join as join6 } from "node:path";
2025
- var NPM_LATEST = "https://registry.npmjs.org/nimblebrain/latest";
2026
- var FRESH_MS = 24 * 60 * 60000;
2027
- var LOOKUP_TIMEOUT_MS = 5000;
2028
- var NOTICE_WAIT_MS = 1000;
2029
- var SEMVER = /^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
2030
- function cachePath(deps) {
2031
- const xdg = deps.env.XDG_CACHE_HOME?.trim();
2032
- const base = xdg?.startsWith("/") ? xdg : join6(deps.home, ".cache");
2033
- return join6(base, "nimblebrain", "update-check.json");
2034
- }
2035
- function updateCheckOff(deps) {
2036
- const ci = deps.env.CI?.trim().toLowerCase();
2037
- return ci !== undefined && ci !== "" && ci !== "false" && ci !== "0" || deps.env.NIMBLEBRAIN_NO_UPDATE_CHECK === "1" || doNotTrack(deps);
2038
- }
2039
- function startUpdateCheck(deps) {
2040
- if (updateCheckOff(deps))
2041
- return;
2042
- const cached = readCache(deps);
2043
- let settled = false;
2044
- const refreshed = cached.then(async (old) => {
2045
- if (old && Date.now() - old.checked_at < FRESH_MS)
2046
- return old;
2047
- return await lookup(deps, old) ?? old;
2048
- });
2049
- refreshed.then(() => {
2050
- settled = true;
2051
- });
2052
- return {
2053
- async known(waitMs) {
2054
- const old = await cached;
2055
- if (settled)
2056
- return refreshed;
2057
- const deadline = waitMs > 0 ? deps.sleep(waitMs).then(() => old) : Promise.resolve(old);
2058
- return Promise.race([refreshed, deadline]);
2059
- }
2060
- };
2061
- }
2062
- async function readCache(deps) {
2063
- try {
2064
- const raw = JSON.parse(await deps.readText(cachePath(deps)) ?? "null");
2065
- if (typeof raw?.checked_at !== "number")
2066
- return;
2067
- return {
2068
- checked_at: raw.checked_at,
2069
- cli: version(raw.cli),
2070
- runtime: version(raw.runtime)
2071
- };
2072
- } catch {
2073
- return;
2074
- }
2075
- }
2076
- async function lookup(deps, old) {
2077
- try {
2078
- const [npm, runtime] = await Promise.all([
2079
- deps.getJson(NPM_LATEST, LOOKUP_TIMEOUT_MS),
2080
- newestRuntime(deps, LOOKUP_TIMEOUT_MS).catch(() => {
2081
- return;
2082
- })
2083
- ]);
2084
- const cli = npm?.status === 200 ? version(npm.body?.version) : undefined;
2085
- if (!cli && !runtime)
2086
- return;
2087
- const known = {
2088
- checked_at: Date.now(),
2089
- cli: cli ?? old?.cli,
2090
- runtime: runtime ?? old?.runtime
2091
- };
2092
- await deps.writeText(cachePath(deps), `${JSON.stringify(known)}
2093
- `);
2094
- return known;
2095
- } catch {
2096
- return;
2097
- }
2098
- }
2099
- function version(value) {
2100
- return typeof value === "string" && SEMVER.test(value) ? value : undefined;
2101
- }
2102
- function updatesField(known, cliVersion, runtimeVersion) {
2103
- const updates = {};
2104
- if (known?.cli)
2105
- updates.cli = { current: cliVersion, latest: known.cli };
2106
- if (known?.runtime && runtimeVersion) {
2107
- updates.runtime = { current: runtimeVersion, latest: known.runtime.replace(/^v/, "") };
2108
- }
2109
- return updates.cli || updates.runtime ? updates : undefined;
2110
- }
2111
- function noticeLines(updates, withRuntime, run = "npx nimblebrain") {
2112
- const lines = [];
2113
- const cli = updates?.cli;
2114
- if (cli && compareVersions(cli.latest, cli.current) > 0) {
2115
- lines.push(`nimblebrain ${cli.latest} is available (you have ${cli.current}): npx nimblebrain@latest`);
2116
- }
2117
- const rt = updates?.runtime;
2118
- if (withRuntime && rt && compareVersions(rt.latest, rt.current) > 0) {
2119
- lines.push(`NimbleBrain v${rt.latest} is available (you have v${rt.current}): ${run} update`);
2120
- }
2121
- return lines;
2122
- }
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>]
71
+ Runs NimbleBrain's agent turns on the Claude Code or Codex you are signed in to,
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(`
74
+ Not started: ${o}
2123
75
 
2124
- // src/main.ts
2125
- var RUNTIME_NOTICE = ["status", "up", "init"];
2126
- async function run(argv, deps) {
2127
- const json = wantsJson(argv);
2128
- let parsed;
2129
- try {
2130
- parsed = parse(argv);
2131
- } catch (err) {
2132
- return render(toFailure(err), json, BARE_CLI);
2133
- }
2134
- if (parsed.kind === "help") {
2135
- return parsed.flags.json ? render(describe(VERSION), true, BARE_CLI) : { stdout: helpText(VERSION), code: 0 };
2136
- }
2137
- if (parsed.kind === "version") {
2138
- return parsed.flags.json ? render({ ok: true, version: VERSION }, true, BARE_CLI) : { stdout: `${VERSION}
2139
- `, code: 0 };
2140
- }
2141
- const { command, flags, arg, operand } = parsed;
2142
- const check = startUpdateCheck(deps);
2143
- const home = installHome(deps, flags.home);
2144
- const cli = invocation(deps, home);
2145
- let result;
2146
- try {
2147
- switch (command) {
2148
- case "doctor": {
2149
- const install = await readInstall(deps, home);
2150
- const ours = install !== undefined && install.port === flags.port && await isHealthy(deps, flags.port);
2151
- const startOllama = confirmOllamaStart({ deps, flags }, false);
2152
- result = { ...await doctorInstall(deps, home, flags.port, ours, startOllama) };
2153
- break;
2154
- }
2155
- case "status":
2156
- result = { ...await status(deps, home) };
2157
- break;
2158
- default: {
2159
- const ctx = { deps, flags, home, version: VERSION, arg, operand };
2160
- const commands = {
2161
- init,
2162
- up,
2163
- down,
2164
- logs,
2165
- update,
2166
- uninstall,
2167
- key,
2168
- telemetry,
2169
- "local-model": localModel,
2170
- mcp,
2171
- open
2172
- };
2173
- result = await commands[command](ctx);
2174
- }
2175
- }
2176
- } catch (err) {
2177
- result = toFailure(err);
2178
- }
2179
- if (!result.ok)
2180
- result = { ...result, fix: forInstall(result.fix, cli) };
2181
- if (!["init", "telemetry", "uninstall", "doctor"].includes(command)) {
2182
- await settleWaiting(deps, home, VERSION);
2183
- }
2184
- return answerWithUpdates(result, command, flags.json, check, cli);
2185
- }
2186
- async function answerWithUpdates(result, command, json, check, cli) {
2187
- if (!check)
2188
- return render(result, json, cli, command);
2189
- const runtime = isStatusShaped(result) ? result.version : undefined;
2190
- const updates = updatesField(await check.known(0), VERSION, runtime);
2191
- const answer = render(updates && runtime !== undefined ? { ...result, updates } : result, json, cli, command);
2192
- const notices = async () => {
2193
- const known = await check.known(NOTICE_WAIT_MS);
2194
- if (json)
2195
- return;
2196
- const lines = noticeLines(updatesField(known, VERSION, runtime), RUNTIME_NOTICE.includes(command), cli);
2197
- return lines.length > 0 ? `${lines.join(`
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(`
2198
77
  `)}
2199
- ` : undefined;
2200
- };
2201
- return { ...answer, notices };
2202
- }
2203
- function isStatusShaped(result) {
2204
- return typeof result.version === "string" && "health" in result && "url" in result && "workspaces" in result;
2205
- }
2206
- async function doctorInstall(deps, home, port, ours, startOllama) {
2207
- const machine = await doctor(deps, port, ours);
2208
- const model = localModelOf(await deps.readText(paths(home).env) ?? "");
2209
- if (!model)
2210
- return machine;
2211
- try {
2212
- const local = await checkLocalModel(deps, model, startOllama);
2213
- return {
2214
- ...machine,
2215
- checks: [...machine.checks, ...local.checks],
2216
- ollama_started: local.started
2217
- };
2218
- } catch (err) {
2219
- if (!(err instanceof CliError))
2220
- throw err;
2221
- const local = err.detail.checks ?? [];
2222
- throw err.with({ checks: [...machine.checks, ...local] });
2223
- }
2224
- }
2225
- async function isHealthy(deps, port) {
2226
- const res = await deps.getJson(`http://127.0.0.1:${port}/v1/health`);
2227
- return res?.status === 200;
2228
- }
2229
- function toFailure(err) {
2230
- if (err instanceof CliError)
2231
- return failure(err);
2232
- return failure(new CliError("USAGE", err instanceof Error ? err.message : String(err)));
2233
- }
2234
- function render(result, json, cli, command) {
2235
- const code = exitCodeFor(result);
2236
- if (json)
2237
- return { stdout: `${JSON.stringify(result)}
2238
- `, code };
2239
- if (!result.ok)
2240
- return { stdout: `error: ${result.message}
2241
- fix: ${result.fix}
2242
- `, code };
2243
- const lines = isStatus(result) ? statusLines(result, cli, command) : command === "open" ? openLines(result) : genericLines(result);
2244
- return { stdout: `${lines.join(`
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}
84
+ ${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(`
86
+ `),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(`
2245
87
  `)}
2246
- `, code };
2247
- }
2248
- function isStatus(result) {
2249
- return "health" in result && "url" in result && "workspaces" in result;
2250
- }
2251
- var AGENT_NAMES = {
2252
- "claude-code": "Claude Code",
2253
- cursor: "Cursor",
2254
- codex: "Codex"
2255
- };
2256
- function statusLines(r, cli, command) {
2257
- const lines = [
2258
- ...changeLines(r),
2259
- ` NimbleBrain ${r.version.startsWith("v") ? r.version : `v${r.version}`}: ${r.health === "ok" ? "running" : "stopped"} at ${r.url}`,
2260
- ...r.workspaces.map((w) => ` workspace ${w.name}: ${w.mcp}`),
2261
- r.local_model ? ` model: ${r.local_model} on Ollama (NimbleBrain's own agents use it)` : ` model key: ${r.model_key === "set" ? "set (NimbleBrain's own agents use it)" : `missing (run ${cli} key)`}`
2262
- ];
2263
- const agent = r.agent.connected;
2264
- lines.push(...agentLines(r));
2265
- if (!r.host_loopback)
2266
- lines.push(` servers on this machine: not reachable until ${cli} update`);
2267
- lines.push(telemetryLine(r.telemetry));
2268
- lines.push(` CLI ${r.cli_version}`);
2269
- if (command === "init" && !r.already && r.health === "ok" && !hasModelIn(r)) {
2270
- lines.push("", `Next: give NimbleBrain a model so it can chat. Run ${cli} key in your own terminal to enter a model key, or ${cli} local-model to run one on this machine with Ollama.`);
2271
- } else if (command === "init" && !r.already && r.health === "ok") {
2272
- const ask = agent ? `, or ask ${AGENT_NAMES[agent] ?? agent} what NimbleBrain can do` : "";
2273
- const use = r.opened ? `use NimbleBrain in your browser at ${r.url}` : `open ${r.url}`;
2274
- lines.push("", `Next: ${use}${ask}. Stop it with ${cli} down.`);
2275
- }
2276
- return lines;
2277
- }
2278
- function openLines(r) {
2279
- return [
2280
- r.opened ? ` Opened ${String(r.url)} in your browser.` : ` Open ${String(r.url)} in your browser; none could be started here.`
2281
- ];
2282
- }
2283
- function agentLines(r) {
2284
- const agent = r.agent.connected;
2285
- if (!agent)
2286
- return r.manual ? [` agent: not connected; add it by hand: ${r.manual}`] : [];
2287
- const name = AGENT_NAMES[agent] ?? agent;
2288
- const lines = [
2289
- ` ${name} can use NimbleBrain's tools (it loads them when its next session starts)`
2290
- ];
2291
- const refresh = r.skill_update && SKILL_REFRESH_LINES[r.skill_update];
2292
- if (refresh)
2293
- lines.push(` skill: ${refresh}`);
2294
- if (!r.agent.skill)
2295
- lines.push(` skill: not installed; add it with npx skills add nimblebraininc/skills --skill nimblebrain --agent ${agent} -g`);
2296
- return lines;
2297
- }
2298
- var SKILL_REFRESH_LINES = {
2299
- updated: "updated to the newest nimblebrain skill",
2300
- unchanged: "the nimblebrain skill is current",
2301
- failed: "could not refresh the nimblebrain skill; try npx skills update nimblebrain -g",
2302
- not_installed: undefined
2303
- };
2304
- function changeLines(r) {
2305
- if (r.already)
2306
- return [" already installed"];
2307
- return r.from ? [` updated from ${r.from}`] : [];
2308
- }
2309
- function telemetryLine(t) {
2310
- const how = t.locked ? ` (${t.locked})` : t.set ? ` (answer with ${t.set})` : "";
2311
- return ` telemetry: ${t.state}${how}`;
2312
- }
2313
- function genericLines(result) {
2314
- return Object.entries(result).filter(([key]) => key !== "ok").flatMap(([key, value]) => field2(key, value));
2315
- }
2316
- function field2(key, value) {
2317
- if (value === undefined || value === null)
2318
- return [];
2319
- if (key === "servers" && Array.isArray(value)) {
2320
- if (value.length === 0)
2321
- return [" no servers in this workspace"];
2322
- return value.map((s) => ` ${s.serverName}: ${s.url ?? "(no URL)"}${s.status ? ` (${s.status})` : ""}`);
2323
- }
2324
- if (key === "checks" && Array.isArray(value)) {
2325
- return value.map((c) => ` ${c.ok ? "✓" : "✗"} ${c.check}: ${c.detail}`);
2326
- }
2327
- if (typeof value === "object" && !Array.isArray(value)) {
2328
- return Object.entries(value).flatMap(([k, v]) => field2(`${key} ${k}`, v));
2329
- }
2330
- if (Array.isArray(value)) {
2331
- const items = value.map((v) => typeof v === "object" ? JSON.stringify(v) : String(v));
2332
- return [` ${key}: ${items.join(", ")}`];
2333
- }
2334
- return [` ${key}: ${String(value)}`];
2335
- }
2336
- function interrupted(argv, exitCode, deps) {
2337
- const err = new CliError("INTERRUPTED", `The CLI stopped before it answered (exit code ${exitCode}).`, { exit_code: exitCode });
2338
- let cli = BARE_CLI;
2339
- try {
2340
- cli = invocation(deps, installHome(deps, parse(argv).flags.home));
2341
- } catch {}
2342
- const result = failure(err);
2343
- return render({ ...result, fix: forInstall(result.fix, cli) }, wantsJson(argv), cli);
2344
- }
2345
-
2346
- // src/bin.ts
2347
- var argv = process.argv.slice(2);
2348
- var deps = realDeps();
2349
- var answered = false;
2350
- process.on("exit", (code) => {
2351
- if (answered)
2352
- return;
2353
- const out = interrupted(argv, code, deps);
2354
- writeSync(1, out.stdout);
2355
- writeSync(2, `nimblebrain: stopped before answering (exit code ${code})
2356
- `);
2357
- process.exitCode = out.code;
2358
- });
2359
- for (const [signal, n] of [
2360
- ["SIGINT", 2],
2361
- ["SIGTERM", 15],
2362
- ["SIGHUP", 1]
2363
- ]) {
2364
- process.on(signal, () => process.exit(128 + n));
2365
- }
2366
- var answer = await run(argv, deps);
2367
- writeSync(1, answer.stdout);
2368
- answered = true;
2369
- var notices = await answer.notices?.();
2370
- if (notices)
2371
- writeSync(2, notices);
2372
- process.exit(answer.code);
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"?>
93
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
94
+ <plist version="1.0">
95
+ <dict>
96
+ <key>Label</key>
97
+ <string>${Jt(e.label)}</string>
98
+ <key>ProgramArguments</key>
99
+ <array>
100
+ ${t.map((i)=>` <string>${Jt(i)}</string>`).join(`
101
+ `)}
102
+ </array>
103
+ <key>EnvironmentVariables</key>
104
+ <dict>
105
+ ${o.join(`
106
+ `)}
107
+ </dict>
108
+ <key>RunAtLoad</key>
109
+ <true/>
110
+ <key>KeepAlive</key>
111
+ <dict>
112
+ <key>SuccessfulExit</key>
113
+ <false/>
114
+ </dict>
115
+ <key>ThrottleInterval</key>
116
+ <integer>10</integer>
117
+ <key>ProcessType</key>
118
+ <string>Background</string>
119
+ <key>StandardOutPath</key>
120
+ <string>${Jt(n)}</string>
121
+ <key>StandardErrorPath</key>
122
+ <string>${Jt(n)}</string>
123
+ </dict>
124
+ </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(`
132
+ `)}
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(`
138
+ `)}
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
+ `,code:o};if(!e.ok)return{stdout:`error: ${e.message}
141
+ 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
+ `)}
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)}