typebulb 0.63.0 → 0.63.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -326,7 +326,7 @@ Sec-WebSocket-Version: 13\r
326
326
  `))if(n.trim())try{let r=JSON.parse(n);if(r.type==="turn_context"&&typeof r.payload?.model=="string")return{model:r.payload.model,effort:r.payload.effort}}catch{}}var tP,qs,hd,iP,lP,pP,oa,mb,md,ur,mP,yb,gd=k(()=>{"use strict";Ms();Zo();Qo();ud();ub();tP=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<node_repl_review_evidence>","# AGENTS.md instructions for "];qs=t=>!!t&&typeof t=="object"&&!Array.isArray(t),hd=t=>t==="shell_command"||t==="exec_command",iP=new Set(["max_output_tokens","yield_time_ms","timeout_ms"]);lP={n:`
327
327
  `,t:" ",r:"\r",b:"\b",f:"\f",v:"\v",0:"\0"};pP=t=>t?t.replace(/\r?\n$/,"").split(`
328
328
  `).length:0;oa=t=>{let e=eP(t);return process.platform==="win32"?e.toLowerCase():e},mb=12e4,md=t=>t.slice(-36),ur=class t extends Ut{constructor(n=pd(fb(),".codex","sessions")){super();this.root=n}displayName="Codex Mirror";#t=0;#s;#e=!1;#r;#c=0;#n=new Map;#o=new Map;#l=new Map;#u=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}forRead(){return new t(this.root)}callerSessionId(n){let r=process.env.CODEX_THREAD_ID;return r?this.listSessionFiles(n).find(s=>s.sessionId.endsWith(r))?.sessionId:void 0}async wakeRoute(n){try{return(await fd()).includes(md(n))?{hosted:!0}:{hosted:!1,error:"this Codex session is not hosted by the shared app server, so nothing can wake it"}}catch(r){return{error:r instanceof Error?r.message:String(r)}}}async wake(n,r,s){if(!(await fd()).includes(md(n)))throw new Error("the Codex session is not loaded by its app server now");await lb(md(n),r,s)}detectsInstalled(){return ZO(pd(fb(),".codex"))}sessionsDir(n){return this.root}listSessionFiles(n){let r=oa(n),s=[];for(let i of this.#f()){let o=0,a=0;try{let f=ia(i);if(!f.isFile())continue;o=f.size,a=f.mtimeMs}catch{continue}let c=this.#n.get(i);if(c===void 0){if(c=gb(i),c===void 0)continue;this.#n.set(i,c)}if(c.subagent||oa(c.cwd)!==r)continue;let l=db(i,".jsonl");this.#l.set(l,i),s.push({sessionId:l,file:i,mtime:this.#i(i,o,a)})}return s}listChildren(n,r){let s=oa(n),i=new Map,o;for(let l of this.#f()){let f=0,u=0,d;try{let b=ia(l);if(!b.isFile())continue;f=b.size,u=b.mtimeMs,d=b.birthtimeMs||void 0}catch{continue}let p=this.#n.get(l);if(p===void 0||p.modelPending){if(p=gb(l),p===void 0)continue;this.#n.set(l,p)}if(db(l,".jsonl")===r&&(o=p.id),!p.spawn||oa(p.cwd)!==s)continue;let{running:h,tokens:m,turn:g}=this.#a(l,f,u);i.set(p.spawn.id,{file:l,mtime:this.#i(l,f,u),started:d,running:h,tokens:m,spawn:p.spawn,turn:g??p.turn})}if(!o)return[];let a=(l,f=new Set)=>{if(l.parent===o)return!0;if(f.has(l.id))return!1;f.add(l.id);let u=i.get(l.parent);return u?a(u.spawn,f):!1},c=[];for(let{file:l,mtime:f,started:u,running:d,tokens:p,spawn:h,turn:m}of i.values())a(h)&&c.push({id:h.id,file:l,mtime:f,started:u,tokens:p,label:h.path.split("/").filter(Boolean).pop()??h.path,kind:h.role||void 0,model:m?.model,effort:m?.effort,parentId:i.has(h.parent)?h.parent:void 0,depth:h.depth,stopped:!1,running:d});return c}sessionsWorking(n){let r=new Set,s=Date.now();for(let{sessionId:i,file:o,mtime:a}of this.listSessionFiles(n)){if(s-a>=mb)continue;let c;try{let l=ia(o);c=this.#a(o,l.size,l.mtimeMs)}catch{continue}c.running&&r.add(i)}return r}#i(n,r,s){return Math.max(s,this.#a(n,r,s).ms??0)}#a(n,r,s){let i=this.#o.get(n);if(i&&i.size===r&&i.mtime===s)return i;let o=gP(n),a={size:r,mtime:s,...o,turn:o.turn??i?.turn};return this.#o.set(n,a),a}#f(){let n=[],r=s=>{try{return QO(s).map(i=>pd(s,i))}catch{return[]}};for(let s of r(this.root))for(let i of r(s))for(let o of r(i))for(let a of r(o))a.endsWith(".jsonl")&&n.push(a);return n}parseEntry(n){let r;try{r=JSON.parse(n)}catch{return null}return!r||typeof r.type!="string"?null:r}idOf(n){return n.ord===void 0&&(this.#d(n),n.ord=String(this.#t++),n.parent=this.#s,this.#s=n.ord),n.ord}#d(n){let r=n.payload;if(n.type==="session_meta"){if(++this.#c===1){let s=typeof r?.source=="object"?r.source?.subagent?.thread_spawn:void 0;this.#r=s?.agent_path,this.#e=!!s}}else this.#c=0,this.#e&&r?.type==="agent_message"&&r.recipient===this.#r&&(this.#e=!1);n.inherited=this.#e}parentOf(n){return n.parent}timestampOf(n){return n.timestamp}isSidechain(n,r){return r==="child"&&!!n.inherited}isLeafType(n){return!0}isRecoveryNoise(n){return!1}apply(n,r){let s=[],i=n.payload;if(!i)return{events:s};let o=()=>{let a=Date.parse(n.timestamp??"");return!isNaN(a)&&a>=r};if(n.type==="response_item"){if(i.type==="message"){if(i.role==="user"){let a=lr(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=lr(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=lr(i.summary,!1);return a&&s.push({type:"assistant",text:"",thinking:a,tools:[],live:o()}),{events:s}}if(i.type==="custom_tool_call"||i.type==="function_call"){let a=i.call_id??"",{pending:c,...l}=i.type==="custom_tool_call"?sP(i.name??"",i.input):{name:i.name??"",input:hP(i.arguments)};return c&&this.#u.set(a,c),s.push({type:"assistant",text:"",thinking:"",tools:[{id:a,...l}],live:o()}),{events:s}}if(i.type==="custom_tool_call_output"||i.type==="function_call_output"){let a=i.call_id??"",c=this.#u.get(a);return this.#u.delete(a),s.push({type:"tool_result",id:a,...dP(rP(i.output),c)}),{events:s}}return{events:s}}if(n.type==="event_msg"){if(i.type==="token_count"){let a=i.info?.last_token_usage;return a?{events:s,usage:kb(a)}:{events:s}}return i.type==="task_complete"&&s.push({type:"turn_end"}),{events:s}}return n.type==="turn_context"?{events:s,model:i.model}:{events:s}}chainWorking(n){let r=!1;for(let s of n){if(s.type!=="event_msg")continue;let i=s.payload?.type;i==="task_started"?r=!0:(i==="task_complete"||i==="turn_aborted")&&(r=!1)}return r}sessionAlive(n){let r=this.#l.get(n);if(!r)return;let s;try{let i=ia(r);s=this.#i(r,i.size,i.mtimeMs)}catch{return}return Date.now()-s<mb}readPreview(n){for(let r of(ar(n,256*1024)?.text??"").split(`
329
- `))if(!(!r.includes('"user_message"')&&!r.includes('"UserMessage"')))try{let s=JSON.parse(r);if(s?.type!=="event_msg")continue;let i=s.payload,a=((i?.type==="user_message"?i.message:i?.type==="item_completed"&&i.item?.type==="UserMessage"?lr(i.item.content,!0):void 0)??"").replace(/\s+/g," ").trim();if(a)return a.slice(0,200)}catch{}return""}searchText(n){if(n?.type!=="response_item"||n.payload?.type!=="message")return"";let r=n.payload.role;return r!=="user"&&r!=="assistant"?"":lr(n.payload.content,r==="user").replace(/\s+/g," ").trim()}},mP=[64*1024,1024*1024];yb=512*1024});import{realpathSync as bP}from"fs";import{createHash as wP}from"crypto";import{join as ca,resolve as vP}from"path";import{homedir as SP}from"os";function Ee(){let t=process.env.TYPEBULB_SERVERS_DIR;return t?ca(t,".."):ca(SP(),".typebulb")}function yt(){xb||(xb=!0,console.error(`${Ee()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function bt(){return process.env.TYPEBULB_SERVERS_DIR||ca(Ee(),"servers")}function Eb(t){let e=ae(t),n=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return ca(Ee(),"canvas",`${n}-${Js(t)}.png`)}function Js(t){return wP("sha1").update(ae(t)).digest("hex").slice(0,8)}function ae(t){let e=vP(t),n=e;try{n=bP.native(e)}catch{}return(process.platform==="win32"?n.toLowerCase():n).replace(/\\/g,"/")}function Ab(t,e){let n=ae(t),r=ae(e);return n.startsWith(r.endsWith("/")?r:r+"/")?!n.includes("/node_modules/"):!1}var xb,Ue=k(()=>{"use strict";xb=!1});import*as Ob from"net";import{mkdir as kP,readFile as xP,writeFile as Pb}from"fs/promises";import{existsSync as EP}from"fs";import{join as _b}from"path";function $b(){return _b(Ee(),"blocks")}function yd(t){return _b($b(),`${t}.json`)}function ua(t){return new Promise(e=>{let n=Ob.createServer();n.once("error",()=>e(!1)),n.listen(t,"127.0.0.1",()=>n.close(()=>e(!0)))})}async function OP(t){for(let e=t;e<65535;e++)if(await ua(e))return e;throw new Error(`No free port found above ${t}`)}async function bd(t){let{listBulbServers:e}=await Promise.resolve().then(()=>($e(),Nb)),n=(await e()).find(s=>s.port===t),r=n?` (pid ${n.pid}, ${n.agent?`agent:${n.agent}`:n.file})`:"";console.error(`port ${t} in use${r}`),process.exit(1)}async function da(t){try{let e=JSON.parse(await xP(yd(t),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function fa(t,e){try{return await Pb(yd(t),JSON.stringify(e,null,2)),!0}catch{return yt(),!1}}async function PP(t){let e=ae(t);try{await kP($b(),{recursive:!0})}catch{return}let n=[];for(let o=0;o<Ib;o++)n.push(Rb+o*bn);let r=await Promise.all(n.map(async o=>({base:o,block:await da(o)})));for(let{base:o,block:a}of r)if(a?.cwd===e)return o;let s={cwd:e,slots:{},mirrors:{}};for(let{base:o,block:a}of r){if(!a)try{return await Pb(yd(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(c){if((await da(o))?.cwd===e)return o;c.code!=="EEXIST"&&yt();continue}if(!EP(a.cwd))return await fa(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Tb(o.block)-Tb(a.block))[0];if(i)return await fa(i.base,s)?i.base:void 0}function Tb(t){return Object.values(t.slots).reduce((e,n)=>Math.max(e,n.usedAt??0),0)}async function _P(t,e){let n=await da(t)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=n.mirrors[e.agent];if(i!==void 0)return i;let o=Cb(n),a=o.has(0)?TP:0;for(;a>la&&o.has(a);)a--;return n.mirrors[e.agent]=a,await fa(t,n),a}let r=ae(e.file),s=n.slots[r]?.offset;if(s===void 0){let i=Cb(n);for(s=la;s<bn&&i.has(s);)s++;if(s>=bn){let o=Object.entries(n.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:la,o&&delete n.slots[o[0]]}}return n.slots[r]={offset:s,usedAt:Date.now()},await fa(t,n),s}function Cb(t){return new Set([...Object.values(t.mirrors),...Object.values(t.slots).map(e=>e.offset)])}async function dr(t,e){let n=await PP(e);return n===void 0?void 0:n+await _P(n,t)}async function wn(t){let e=ae(t);for(let n=0;n<Ib;n++){let r=await da(Rb+n*bn);if(r?.cwd===e)return s=>r.slots[ae(s)]?.usedAt??0}return()=>0}async function pa(t){if(t.explicit!==void 0)return await ua(t.explicit)||await bd(t.explicit),t.target.kind==="bulb"&&await dr(t.target,t.cwd),{port:t.explicit};let e=await dr(t.target,t.cwd);if(e!==void 0){let r=e-e%bn,s=Date.now()+CP;do{if(await ua(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=la;i<bn;i++){let o=r+i;if(o!==e&&await ua(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await OP(AP),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Rb,bn,Ib,AP,la,TP,CP,vn=k(()=>{"use strict";Ue();Rb=20100,bn=100,Ib=19,AP=23e3,la=1,TP=bn-1,CP=3e3});var Pe,ha=k(()=>{"use strict";Pe="0.63.0"});var Nb={};qi(Nb,{agentViewerCommand:()=>Wb,bulbServerCommand:()=>Jb,clearServerLog:()=>xd,findProjectViewer:()=>ya,isAlive:()=>Jt,isMirror:()=>we,isProjectBulb:()=>Od,isProjectMirror:()=>hr,launchAgentViewer:()=>Hs,launchBulbServer:()=>xn,listBulbServers:()=>Q,probePageCount:()=>_d,readServerLog:()=>Ze,readWaitCursor:()=>ga,recordDenial:()=>Cd,registerServer:()=>Td,relayOpen:()=>Pd,runMarker:()=>Ed,serverLogPath:()=>pr,serversForBulb:()=>kn,sliceRunLog:()=>Ad,startServerLog:()=>Ks,stopBulbServer:()=>fr,stopServer:()=>wt,stopServersForBulb:()=>ba,typebulbBinPath:()=>mr,unregisterServer:()=>Sn,writeWaitCursor:()=>Ws});import{spawn as Lb}from"child_process";import{readdir as RP,readFile as Bb,writeFile as jb,unlink as wd,mkdir as IP}from"fs/promises";import{mkdirSync as Fb,writeFileSync as ma,appendFileSync as $P,readFileSync as vd}from"fs";import*as Ne from"path";import{fileURLToPath as NP}from"url";function Sd(t){return Ne.join(bt(),`${t}.json`)}function pr(t){return Ne.join(bt(),`${t}.log`)}function kd(t){return Ne.join(bt(),`${t}.wait.json`)}function Ub(t){try{let e=JSON.parse(vd(kd(t),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function ga(t,e=""){let n=Ub(t)[e];return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function Ws(t,e,n=""){try{Fb(bt(),{recursive:!0});let r=Ub(t);r[n]=e,ma(kd(t),JSON.stringify({cursors:r}))}catch{}}function Ks(t){let e=pr(t);try{Fb(bt(),{recursive:!0}),ma(e,"")}catch{return()=>{}}let n=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if($P(e,c),s+=c.length,s>2*Mb){let l=vd(e),f=l.subarray(Math.max(0,l.length-Mb));ma(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),n(a,...c))),process.stderr.write=((a,...c)=>(o(a),r(a,...c))),()=>{process.stdout.write=n,process.stderr.write=r}}function xd(t){try{ma(pr(t),"")}catch{}}function Ze(t,e=0){try{let n=vd(pr(t)),r=e>=0&&e<=n.length?e:0;return{text:n.subarray(r).toString("utf8"),offset:n.length}}catch{return{text:"",offset:0}}}function Ed(t){return`\u2500\u2500 run ${t} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function MP(t){let e=LP.exec(t);return e?Number(e[1]):void 0}function Ad(t,e){let n=t.split(`
329
+ `))if(!(!r.includes('"user_message"')&&!r.includes('"UserMessage"')))try{let s=JSON.parse(r);if(s?.type!=="event_msg")continue;let i=s.payload,a=((i?.type==="user_message"?i.message:i?.type==="item_completed"&&i.item?.type==="UserMessage"?lr(i.item.content,!0):void 0)??"").replace(/\s+/g," ").trim();if(a)return a.slice(0,200)}catch{}return""}searchText(n){if(n?.type!=="response_item"||n.payload?.type!=="message")return"";let r=n.payload.role;return r!=="user"&&r!=="assistant"?"":lr(n.payload.content,r==="user").replace(/\s+/g," ").trim()}},mP=[64*1024,1024*1024];yb=512*1024});import{realpathSync as bP}from"fs";import{createHash as wP}from"crypto";import{join as ca,resolve as vP}from"path";import{homedir as SP}from"os";function Ee(){let t=process.env.TYPEBULB_SERVERS_DIR;return t?ca(t,".."):ca(SP(),".typebulb")}function yt(){xb||(xb=!0,console.error(`${Ee()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function bt(){return process.env.TYPEBULB_SERVERS_DIR||ca(Ee(),"servers")}function Eb(t){let e=ae(t),n=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return ca(Ee(),"canvas",`${n}-${Js(t)}.png`)}function Js(t){return wP("sha1").update(ae(t)).digest("hex").slice(0,8)}function ae(t){let e=vP(t),n=e;try{n=bP.native(e)}catch{}return(process.platform==="win32"?n.toLowerCase():n).replace(/\\/g,"/")}function Ab(t,e){let n=ae(t),r=ae(e);return n.startsWith(r.endsWith("/")?r:r+"/")?!n.includes("/node_modules/"):!1}var xb,Ue=k(()=>{"use strict";xb=!1});import*as Ob from"net";import{mkdir as kP,readFile as xP,writeFile as Pb}from"fs/promises";import{existsSync as EP}from"fs";import{join as _b}from"path";function $b(){return _b(Ee(),"blocks")}function yd(t){return _b($b(),`${t}.json`)}function ua(t){return new Promise(e=>{let n=Ob.createServer();n.once("error",()=>e(!1)),n.listen(t,"127.0.0.1",()=>n.close(()=>e(!0)))})}async function OP(t){for(let e=t;e<65535;e++)if(await ua(e))return e;throw new Error(`No free port found above ${t}`)}async function bd(t){let{listBulbServers:e}=await Promise.resolve().then(()=>($e(),Nb)),n=(await e()).find(s=>s.port===t),r=n?` (pid ${n.pid}, ${n.agent?`agent:${n.agent}`:n.file})`:"";console.error(`port ${t} in use${r}`),process.exit(1)}async function da(t){try{let e=JSON.parse(await xP(yd(t),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function fa(t,e){try{return await Pb(yd(t),JSON.stringify(e,null,2)),!0}catch{return yt(),!1}}async function PP(t){let e=ae(t);try{await kP($b(),{recursive:!0})}catch{return}let n=[];for(let o=0;o<Ib;o++)n.push(Rb+o*bn);let r=await Promise.all(n.map(async o=>({base:o,block:await da(o)})));for(let{base:o,block:a}of r)if(a?.cwd===e)return o;let s={cwd:e,slots:{},mirrors:{}};for(let{base:o,block:a}of r){if(!a)try{return await Pb(yd(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(c){if((await da(o))?.cwd===e)return o;c.code!=="EEXIST"&&yt();continue}if(!EP(a.cwd))return await fa(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Tb(o.block)-Tb(a.block))[0];if(i)return await fa(i.base,s)?i.base:void 0}function Tb(t){return Object.values(t.slots).reduce((e,n)=>Math.max(e,n.usedAt??0),0)}async function _P(t,e){let n=await da(t)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=n.mirrors[e.agent];if(i!==void 0)return i;let o=Cb(n),a=o.has(0)?TP:0;for(;a>la&&o.has(a);)a--;return n.mirrors[e.agent]=a,await fa(t,n),a}let r=ae(e.file),s=n.slots[r]?.offset;if(s===void 0){let i=Cb(n);for(s=la;s<bn&&i.has(s);)s++;if(s>=bn){let o=Object.entries(n.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:la,o&&delete n.slots[o[0]]}}return n.slots[r]={offset:s,usedAt:Date.now()},await fa(t,n),s}function Cb(t){return new Set([...Object.values(t.mirrors),...Object.values(t.slots).map(e=>e.offset)])}async function dr(t,e){let n=await PP(e);return n===void 0?void 0:n+await _P(n,t)}async function wn(t){let e=ae(t);for(let n=0;n<Ib;n++){let r=await da(Rb+n*bn);if(r?.cwd===e)return s=>r.slots[ae(s)]?.usedAt??0}return()=>0}async function pa(t){if(t.explicit!==void 0)return await ua(t.explicit)||await bd(t.explicit),t.target.kind==="bulb"&&await dr(t.target,t.cwd),{port:t.explicit};let e=await dr(t.target,t.cwd);if(e!==void 0){let r=e-e%bn,s=Date.now()+CP;do{if(await ua(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=la;i<bn;i++){let o=r+i;if(o!==e&&await ua(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await OP(AP),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Rb,bn,Ib,AP,la,TP,CP,vn=k(()=>{"use strict";Ue();Rb=20100,bn=100,Ib=19,AP=23e3,la=1,TP=bn-1,CP=3e3});var Pe,ha=k(()=>{"use strict";Pe="0.63.2"});var Nb={};qi(Nb,{agentViewerCommand:()=>Wb,bulbServerCommand:()=>Jb,clearServerLog:()=>xd,findProjectViewer:()=>ya,isAlive:()=>Jt,isMirror:()=>we,isProjectBulb:()=>Od,isProjectMirror:()=>hr,launchAgentViewer:()=>Hs,launchBulbServer:()=>xn,listBulbServers:()=>Q,probePageCount:()=>_d,readServerLog:()=>Ze,readWaitCursor:()=>ga,recordDenial:()=>Cd,registerServer:()=>Td,relayOpen:()=>Pd,runMarker:()=>Ed,serverLogPath:()=>pr,serversForBulb:()=>kn,sliceRunLog:()=>Ad,startServerLog:()=>Ks,stopBulbServer:()=>fr,stopServer:()=>wt,stopServersForBulb:()=>ba,typebulbBinPath:()=>mr,unregisterServer:()=>Sn,writeWaitCursor:()=>Ws});import{spawn as Lb}from"child_process";import{readdir as RP,readFile as Bb,writeFile as jb,unlink as wd,mkdir as IP}from"fs/promises";import{mkdirSync as Fb,writeFileSync as ma,appendFileSync as $P,readFileSync as vd}from"fs";import*as Ne from"path";import{fileURLToPath as NP}from"url";function Sd(t){return Ne.join(bt(),`${t}.json`)}function pr(t){return Ne.join(bt(),`${t}.log`)}function kd(t){return Ne.join(bt(),`${t}.wait.json`)}function Ub(t){try{let e=JSON.parse(vd(kd(t),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function ga(t,e=""){let n=Ub(t)[e];return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function Ws(t,e,n=""){try{Fb(bt(),{recursive:!0});let r=Ub(t);r[n]=e,ma(kd(t),JSON.stringify({cursors:r}))}catch{}}function Ks(t){let e=pr(t);try{Fb(bt(),{recursive:!0}),ma(e,"")}catch{return()=>{}}let n=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if($P(e,c),s+=c.length,s>2*Mb){let l=vd(e),f=l.subarray(Math.max(0,l.length-Mb));ma(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),n(a,...c))),process.stderr.write=((a,...c)=>(o(a),r(a,...c))),()=>{process.stdout.write=n,process.stderr.write=r}}function xd(t){try{ma(pr(t),"")}catch{}}function Ze(t,e=0){try{let n=vd(pr(t)),r=e>=0&&e<=n.length?e:0;return{text:n.subarray(r).toString("utf8"),offset:n.length}}catch{return{text:"",offset:0}}}function Ed(t){return`\u2500\u2500 run ${t} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function MP(t){let e=LP.exec(t);return e?Number(e[1]):void 0}function Ad(t,e){let n=t.split(`
330
330
  `),r=[];if(n.forEach((o,a)=>{let c=MP(o);c!==void 0&&r.push({id:c,idx:a})}),!r.length)return e==="latest"?t:"";let s=e==="latest"?r[r.length-1]:r.find(o=>o.id===e);if(!s)return"";let i=r.find(o=>o.idx>s.idx);return n.slice(s.idx,i?i.idx:n.length).join(`
331
331
  `)}function Jt(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function Td(t){try{await IP(bt(),{recursive:!0}),await jb(Sd(t.pid),JSON.stringify({version:Pe,...t}))}catch{yt()}}async function Cd(t,e){let n=Sd(t);try{let r=JSON.parse(await Bb(n,"utf8"));if(r.denied===e)return;r.denied=e,await jb(n,JSON.stringify(r))}catch{}}async function Sn(t){await wd(Sd(t)).catch(()=>{}),await wd(pr(t)).catch(()=>{}),await wd(kd(t)).catch(()=>{})}function we(t){return t.agent!=null}function hr(t,e){return we(t)&&t.cwd!=null&&ae(t.cwd)===ae(e)}function Od(t,e){return!we(t)&&Ab(t.file,e)}async function Q(t){let e;try{e=await RP(bt())}catch{return[]}let n=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Bb(Ne.join(bt(),s),"utf8"))}catch{await Sn(i);return}o&&typeof o.pid=="number"&&Jt(o.pid)?n.push(o):await Sn(i)})),(t?n.filter(s=>Od(s,t)):n).sort((s,i)=>s.startedAt-i.startedAt)}async function ya(t,e){return(await Q()).find(n=>hr(n,t)&&(e?n.agent===e:!0))}async function Pd(t,e){let n=new URL(t).port,r=(await Q()).filter(a=>String(a.port)!==n),s=r.filter(a=>hr(a,e)),i=r.filter(a=>Od(a,e)),o=0;for(let a of[...s,...i])try{let c=await fetch(`${a.url}/__open`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t}),signal:AbortSignal.timeout(2e3)});if(!c.ok)continue;let{opened:l,pages:f}=await c.json();if(l)return{where:"editor",via:a.agent?"the agent mirror":`${Ne.basename(a.file)}'s page`};we(a)&&(o+=f??0)}catch{}return o>0?{where:"external"}:void 0}async function fr(t){try{process.kill(t,"SIGTERM")}catch{}await Sn(t)}async function _d(t){try{let e=await fetch(`${t.url}/__pages`,{signal:AbortSignal.timeout(DP)});if(!e.ok)return;let{pages:n}=await e.json();return typeof n=="number"?n:void 0}catch{return}}async function wt(t,e=we(t)?"keep":"close"){try{let n=await fetch(`${t.url}/__stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pages:e}),signal:AbortSignal.timeout(Db)});if(!n.ok)throw new Error(`/__stop ${n.status}`);let{closed:r=0,stuck:s=0}=await n.json(),i=Date.now()+Db;for(;Jt(t.pid)&&Date.now()<i;)await qb(100);return Jt(t.pid)?(await fr(t.pid),"killed"):(await Sn(t.pid),{closed:r,stuck:s})}catch{return await fr(t.pid),"killed"}}function kn(t,e){let n=ae(e);return t.filter(r=>!we(r)&&r.pid!==process.pid&&ae(r.file)===n)}async function ba(t,e){let n=kn(await Q(),t);for(let r of n)await wt(r,e!==void 0&&r.port===e?"keep":"close");return n}function BP(t,e,n){(process.platform==="win32"?Lb("cmd",["/c","start","","/b",t,...e],{cwd:n,stdio:"ignore",windowsHide:!0}):Lb(t,e,{cwd:n,detached:!0,stdio:"ignore"})).unref()}function mr(){return Ne.join(Ne.dirname(NP(import.meta.url)),"index.js")}function Jb(t,e={}){return{command:process.execPath,args:[mr(),...e.trust?["--trust"]:[],...e.noTrust?["--no-trust"]:[],...e.mode?["--mode",e.mode]:[],...e.watch===!1?["--no-watch"]:[],...e.replace?["--replace",e.replace]:[],t,...e.open===!1?["--no-open"]:[]]}}function Wb(t){return{command:process.execPath,args:[mr(),`agent:${t}`,"--no-open"]}}async function Kb(t,e,n,r){let s=await t();if(s)return s;BP(e.command,e.args,n);let i=Date.now()+2e4;for(;Date.now()<i;){await qb(150);let o=await t();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function xn(t,e={}){let n=e.cwd??process.cwd(),r=Ne.resolve(n,t),s=await dr({kind:"bulb",file:r},n),[i]=await ba(r,s),o={...e,mode:e.mode??i?.mode};return Kb(async()=>kn(await Q(),r)[0],Jb(t,o),n,Ne.basename(t))}async function Hs(t,e=process.cwd()){return Kb(()=>ya(e,t),Wb(t),e,`the ${t} mirror`)}var Mb,LP,Db,DP,qb,$e=k(()=>{"use strict";Ue();vn();ha();Mb=1e6;LP=/^── run (\d+) ── /;Db=6e3,DP=500;qb=t=>new Promise(e=>setTimeout(e,t))});function gr(t){return{...ch(t),server:t.files.get("server.ts")??""}}function wa(t){return!!t.server&&!t.code}var zs=k(()=>{"use strict";re();re()});function va(t){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(t),n=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return n?n[1].replace(/^["']|["']$/g,""):void 0}function Rd(t){return sr(va(t)??"bulb")||"bulb"}var Id=k(()=>{"use strict";re()});import{readdirSync as jP,readFileSync as FP,statSync as UP}from"fs";import{join as Hb,basename as qP}from"path";function Yb(t,e,n){if(e>8)return n;let r;try{r=jP(t,{withFileTypes:!0})}catch{return n}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Yb(Hb(t,s.name),e+1,n)}else s.isFile()&&s.name.endsWith(".bulb.md")&&n.push(Hb(t,s.name));return n}function JP(t,e){let n,r=!1;try{let s=FP(t,"utf8");n=va(s.slice(0,1024));let i=Ge(s);r=!!i&&wa(gr(i))}catch{}return{mtime:e,name:n??qP(t).replace(/\.bulb\.md$/,""),serverOnly:r}}function Sa(t){let e=new Map,n=Yb(t,0,[]).map(r=>{let s=0;try{s=UP(r).mtimeMs}catch{}let i=s?zb.get(r):void 0,o=i?.mtime===s?i:JP(r,s);return s&&e.set(r,o),{path:r,...o}});return zb=e,n}var zb,Vb=k(()=>{"use strict";re();zs();Id();zb=new Map});function yr(t){if(t.server.trim())return"server-side code (server.ts)";let e=t.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||t.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var ka=k(()=>{"use strict"});import{readFile as WP}from"fs/promises";async function $d(t){try{let e=Ge(await WP(t,"utf-8"));return e?yr(gr(e)):void 0}catch{return}}var Gb=k(()=>{"use strict";zs();ka()});function Nd(t){let e=t.split(""),n=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
332
332
  `&&(e[a]=" ")},r=0,s="";for(;r<t.length;){let i=t[r],o=t[r+1];if(i==="/"&&o==="/"){let a=r;for(;a<t.length&&t[a]!==`
@@ -538,11 +538,11 @@ ${r}
538
538
  Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),n.join(`
539
539
 
540
540
  `)}function Zs(t){try{return JSON.parse(t)}catch{return}}function pw(t,e){let n="",r=0,s=!1,i=!1;for(let o=0;o<t.length;o++){let a=t[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(n+=t.slice(r,o+1),r=o+1):(n+=e(t.slice(r,o))+'"',r=o+1),s=!s)}return n+=s?t.slice(r):e(t.slice(r)),n}function A_(t){let e=pw(t,n=>n.replace(/,(\s*[}\]])/g,"$1"));return e!==t?e:void 0}function T_(t){let e=pw(t,n=>n.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,r=>{if(!/[+\-*/]/.test(r.replace(/^-/,""))||r.length>64||!/^[\d\s.+\-*/()]+$/.test(r))return r;try{let s=Function(`"use strict"; return (${r})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):r}catch{return r}}));return e!==t?e:void 0}function C_(t,e){let n=0,r=!1,s=!1;for(let i=e;i<t.length;i++){let o=t[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){r=!r;continue}if(!r){if(o==="{"||o==="[")n++;else if((o==="}"||o==="]")&&(n--,n===0))return i}}return-1}function O_(t){let e,n=0;for(;n<t.length;){let r=t[n];if(r==="{"||r==="["){let s=C_(t,n);if(s!==-1){let i=t.slice(n,s+1),o=Zs(i);o!==void 0&&(e={parsed:o,json:i}),n=s+1;continue}}n++}return e}function ef(t){let e=[],n=t.trim();n.startsWith("```")&&(n=n.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let r=Zs(n);if(r!==void 0)return{parsed:r,json:n,fixesApplied:e};let s=n.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(n=s[1].trim(),e.push("preamble before fenced JSON"),r=Zs(n),r!==void 0))return{parsed:r,json:n,fixesApplied:e};if(!n.startsWith("{")&&!n.startsWith("[")){let o=n.indexOf("{"),a=n.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(n=n.slice(c),e.push("preamble text"),r=Zs(n),r!==void 0))return{parsed:r,json:n,fixesApplied:e}}for(let[o,a]of E_){let c=a(n);if(c!==void 0){let l=Zs(c);if(l!==void 0)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=O_(t);return i!==void 0?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:void 0,json:n,fixesApplied:e}}function tf(t){try{let e={};if(t.insight!==void 0&&(e.i=t.insight),t.data!==void 0&&(e.d=t.data),e.i===void 0&&e.d===void 0)return"";let n=JSON.stringify(e),r=k_(v_(n),{level:9}),s=__(r),i=`${hw}:${s}`;return i.length>P_?"":"#"+Qd+i}catch{return""}}function nf(t){try{let e=t.startsWith("#")?t.slice(1):t;if(!e.startsWith(Qd))return;let n=e.slice(Qd.length),r=n.indexOf(":");if(r===-1||n.slice(0,r)!==hw)return;let s=R_(n.slice(r+1)),i=JSON.parse(S_(x_(s)));if(!i||typeof i!="object")return;let o=i.i!==void 0,a=Array.isArray(i.d);if(!o&&!a)return;let c={};return o&&(c.insight=i.i,c.insightJson=JSON.stringify(i.i,null,2)),a&&(c.data=i.d),c}catch{return}}function __(t){let e="";for(let n=0;n<t.length;n+=32768)e+=String.fromCharCode(...t.subarray(n,n+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function R_(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}var E_,Qd,hw,P_,mw=k(()=>{E_=[["orphan quote",t=>{let e=t.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==t?e:void 0}],["trailing }",t=>t.endsWith("}}")?t.slice(0,-1):void 0],["trailing ]",t=>t.endsWith("]]")?t.slice(0,-1):void 0],["trailing },",t=>t.endsWith("},")?t.slice(0,-1):void 0],["trailing ],",t=>t.endsWith("],")?t.slice(0,-1):void 0],["trailing commas",A_],["arithmetic constants",T_]];Qd="tb=",hw="1",P_=6e4});var Wt=k(()=>{On();Sr();Vd();fw();mw();Ca();Kd();Hd();qd();Wd();zd()});import{readFileSync as gw,existsSync as I_}from"fs";import*as ut from"path";function yw(t){return[...t?[`.env.${t}.local`,`.env.${t}`]:[],".env.local",".env"]}function ve(t,e=process.cwd()){let n={},r=[];for(let s of yw(t)){let i;try{i=gw(ut.resolve(e,s),"utf-8")}catch{continue}r.push(s);for(let[o,a]of bw(i))process.env[o]===void 0&&(process.env[o]=a,n[o]=s)}return{mode:t,sources:n,loaded:r}}function*bw(t){for(let e of t.split(`
541
- `)){let n=e.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let s=n.slice(0,r).trim(),i=n.slice(r+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function Ia(t,e=process.cwd()){for(let n of yw()){let r;try{r=gw(ut.resolve(e,n),"utf-8")}catch{continue}for(let[s,i]of bw(r))if(s===t)return i}return process.env[t]}function $_(t){let e=new Set,n=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let r;r=n.exec(t);)e.add(r[1]??r[2]);return[...e]}function ww(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}function Kt(t,e,n){let{sources:r,mode:s,loaded:i}=t,o=process.cwd(),a=ut.dirname(e),c=`(mode: ${s??"none"})`,l=n?$_(n):[],f=l.filter(p=>r[p]).map(p=>`${p} \u2190 ${r[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=ut.resolve(a)!==ut.resolve(o);if(u)for(let p of[".env.local",".env"])I_(ut.join(a,p))&&console.log(`env: ${ut.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var tt=k(()=>{"use strict"});function St(t,e){let n=t??process.env.TB_AI_PROVIDER,r=e??process.env.TB_AI_MODEL;if(!n)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!r)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=Pn(n)}catch{return`Unknown provider '${n}'.`}if(n==="ollama")return{apiKey:"",baseUrl:`${vr(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:n,model:r,isFreeModel:!1};if(n==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:n,model:r,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=wr[n];if(!i)return`Unknown provider '${n}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:n,model:r,isFreeModel:!1}:`No API key for '${n}'. Set ${i} \u2014 ${ww()}.`}function Ht(t,e){let n=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return Yd(t,{messages:n,stream:!0,effort:aw(e.effort),webSearch:e.webSearch,signal:e.signal})}var $a=k(()=>{"use strict";Wt();Wt();tt();Cn()});import{readFileSync as A2,existsSync as N_}from"fs";import*as Ar from"path";import{fileURLToPath as L_}from"url";function M_(){let t=Ar.dirname(L_(import.meta.url));for(;!N_(Ar.join(t,"package.json"));){let e=Ar.dirname(t);if(e===t)break;t=e}return t}function ei(){return Ar.join(M_(),"SKILL.md")}var rf=k(()=>{"use strict"});import{transform as D_}from"sucrase";function sf(t,e={}){let n=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=D_(t,{transforms:n,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var vw=k(()=>{});function B_(t){return t.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
541
+ `)){let n=e.trim();if(!n||n.startsWith("#"))continue;let r=n.indexOf("=");if(r===-1)continue;let s=n.slice(0,r).trim(),i=n.slice(r+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function Ia(t,e=process.cwd()){for(let n of yw()){let r;try{r=gw(ut.resolve(e,n),"utf-8")}catch{continue}for(let[s,i]of bw(r))if(s===t)return i}return process.env[t]}function $_(t){let e=new Set,n=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let r;r=n.exec(t);)e.add(r[1]??r[2]);return[...e]}function ww(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}function Kt(t,e,n){let{sources:r,mode:s,loaded:i}=t,o=process.cwd(),a=ut.dirname(e),c=`(mode: ${s??"none"})`,l=n?$_(n):[],f=l.filter(p=>r[p]).map(p=>`${p} \u2190 ${r[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=ut.resolve(a)!==ut.resolve(o);if(u)for(let p of[".env.local",".env"])I_(ut.join(a,p))&&console.log(`env: ${ut.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var tt=k(()=>{"use strict"});function St(t,e){let n=t??process.env.TB_AI_PROVIDER,r=e??process.env.TB_AI_MODEL;if(!n)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!r)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=Pn(n)}catch{return`Unknown provider '${n}'.`}if(n==="ollama")return{apiKey:"",baseUrl:`${vr(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:n,model:r,isFreeModel:!1};if(n==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:n,model:r,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=wr[n];if(!i)return`Unknown provider '${n}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:n,model:r,isFreeModel:!1}:`No API key for '${n}'. Set ${i} \u2014 ${ww()}.`}function Ht(t,e){let n=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return Yd(t,{messages:n,stream:!0,effort:aw(e.effort),webSearch:e.webSearch,signal:e.signal})}var $a=k(()=>{"use strict";Wt();Wt();tt();Cn()});import{readFileSync as T2,existsSync as N_}from"fs";import*as Ar from"path";import{fileURLToPath as L_}from"url";function M_(){let t=Ar.dirname(L_(import.meta.url));for(;!N_(Ar.join(t,"package.json"));){let e=Ar.dirname(t);if(e===t)break;t=e}return t}function ei(){return Ar.join(M_(),"SKILL.md")}var rf=k(()=>{"use strict"});import{transform as D_}from"sucrase";function sf(t,e={}){let n=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=D_(t,{transforms:n,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var vw=k(()=>{});function B_(t){return t.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
542
542
  `)[0]}`).join(`
543
543
  `)}function Sw(t,e){let n=Ys(t,{target:"client",dependencies:e}).filter(r=>r.type==="UNDECLARED_IMPORT");if(n.length)throw new Error(`Lint failed:
544
544
  ${B_(n)}`)}var kw=k(()=>{"use strict";xa()});var zt,ti,of,ni=k(()=>{zt="https://esm.sh",ti="https://cdn.jsdelivr.net/npm/",of="https://data.jsdelivr.com/v1/package/npm/"});function xw(t){let e=(t||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var U,Tr,Ew,ri=k(()=>{ni();U=class t{constructor(e,n,r){let s=typeof e=="string"?t.parse(e):e;this.name=s.name,this.version=Tr(n??s.version),this.subpath=Tr(r??s.subpath)}static parse(e){let n=xw(e||"");if(!n.length)return new t({name:""});if(n[0].startsWith("@")){let s=n[0],[i,o]=Ew(n[1]??""),a=Tr(n.slice(2).join("/"));return new t({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Ew(n[0]),o=Tr(n.slice(1).join("/"));return new t({name:s,version:i,subpath:o})}}static fromUrl(e){try{let n=new URL(e),r=new URL(zt).host,s=new URL(ti).host;if(n.host===r){let i=xw(n.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return t.parse(o)}if(n.host===s){let i=n.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return t.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return t.parse(e).name}withVersion(e){return new t({name:this.name,version:Tr(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},Tr=t=>t&&t.length?t:void 0,Ew=t=>{let e=t.indexOf("@");return e<0?[t,void 0]:[t.slice(0,e),Tr(t.slice(e+1))]}});async function _e(t){try{return await t()}catch{return}}var Na=k(()=>{});function Rn(t){let e=t||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function af(t){return t.startsWith("./")?t:`./${t}`}var si,cf=k(()=>{ri();Na();ni();si=class{constructor(e,n){this.cache=e,this.http=n,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let n=typeof e=="string"?new U(e):e;return`${ti}${n.name}${n.version?`@${n.version}`:""}/`}file(e,n){return new URL(Rn(n),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,n={}){let{target:r="es2022",bundle:s=!1,external:i}=n,o=new URLSearchParams({target:r});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${zt}/${e}?${o.toString()}`}async resolveExactVersion(e){let n=Date.now(),r=this.pinCache.get(e);if(r&&n-r.ts<this.pinMs)return r.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${zt}/${e}`]);return this.pinCache.set(e,{value:s,ts:n}),s}async tryResolveFromUrls(e){for(let n of e){let r=await _e(()=>this.http.head(n)),s=this.parseVersionFromUrl(r?.url||n);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let n=await this.cache.getIndex(e);if(n&&Date.now()-n.updatedAt<this.versionsIndexMs)return{versions:n.versions,distTags:n.distTags};let r=await _e(()=>this.http.getJson(`${of}${encodeURIComponent(e)}`));if(!r?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=r.tags&&Object.keys(r.tags).length?r.tags:void 0;return await this.cache.setIndex(e,r.versions,s),{versions:r.versions,distTags:s}}parseVersionFromUrl(e){let n=U.fromUrl(e)?.version;return n&&/\d+\.\d+\.\d+/.test(n)?n:void 0}async fetchPackageMeta(e,n){let r=await this.cache.getMeta(e,n);if(r&&Date.now()-r.updatedAt<this.metaTtlMs){let{dependencies:f,peerDependencies:u,peerDependenciesMeta:d}=r;return{name:e,version:n,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new U(`${e}@${n}`)),i=await _e(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,n,a,c,l),{name:e,version:n,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var Aw,ii,lf,j_,oi,La=k(()=>{Aw=t=>t.startsWith("@types/"),ii=t=>Object.keys(t?.peerDependencies||{}).filter(e=>!Aw(e)),lf=t=>Object.keys(t?.dependencies||{}).filter(e=>!Aw(e)),j_=t=>ii(t).filter(e=>!t?.peerDependenciesMeta?.[e]?.optional),oi=class{constructor(e){this.cdn=e}async resolve(e,n){let r=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(r,n),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:n,version:r})=>({name:n,version:r,meta:await this.cdn.fetchPackageMeta(n,r)})))}async expandWithPeers(e,n){let r=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of j_(i.meta))!r.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await n(i),c=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let n=new Set(e.flatMap(i=>ii(i.meta))),r=new Map;for(let i of e)for(let o of lf(i.meta))r.set(o,(r.get(o)||0)+1);let s=new Set([...r.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:n.has(i.name),hasPeers:ii(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var ai,uf=k(()=>{ri();Na();ai=class{constructor(e,n,r){this.cache=e,this.cdn=n,this.semver=r}async learnExactVersion(e){let n=await _e(()=>this.cdn.fetchVersionsIndex(e));if(n?.versions?.length){let r=this.semver.selectBestVersion(n.versions,{distTags:n.distTags});if(r)return r}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,n){if(!n)return this.learnExactVersion(e);let r=a=>!this.semver.isRange(n)||this.semver.satisfies(n,a),s=await this.cache.getPinnedExact(e,n);if(s){if(this.semver.isExactVersion(s)&&r(s))return s;console.debug("[typebulb] cached version for",e,"is not exact or not in",n,"(",s,"); re-resolving from registry")}let i=async a=>{if(a&&this.semver.isExactVersion(a)&&r(a))return await this.cache.setPinnedExact(e,n,a),a},o=await _e(()=>this.cdn.fetchVersionsIndex(e));if(o?.versions?.length){let a=this.semver.selectBestVersion(o.versions,{range:n,distTags:o.distTags});if(a){let c=await i(a);if(c)return c}else{console.debug("[typebulb] refreshing version cache for",e,"(",n,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let c=await _e(()=>this.cdn.fetchVersionsIndex(e));if(c?.versions?.length){let l=await i(this.semver.selectBestVersion(c.versions,{range:n,distTags:c.distTags}));if(l)return l}}}return i(await this.cdn.resolveExactVersion(`${e}@${n}`))}async effectivePackage(e,n){let r=new U(e),s=r.root(),i=n[s],o=i?await _e(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as F_,parse as U_}from"es-module-lexer";var Cr,df=k(()=>{ri();ni();La();Cr=class t{constructor(e,n,r){this.version=e,this.cdn=n,this.peer=r}extractImportsSync(e){let n=new Set;for(let r of t.importPatterns){r.lastIndex=0;for(let s of e.matchAll(r))U.isBare(s[1])&&n.add(s[1])}return Array.from(n)}async extractImports(e){let n=new Set,r=s=>{U.isBare(s)&&n.add(s)};try{await F_;let[s]=U_(e);s.forEach(i=>r(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(n)}async buildImportMap(e,n,r){let s=(await this.extractImports(e)).filter(u=>!r?.has(U.rootOf(u))),i=[...new Set(s.map(U.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,n)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,n)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,n){let r=n[e],s=await this.version.resolveExactForRoot(e,r);if(!s)throw new Error(`Cannot resolve ${r?`${e}@${r}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,n,r){let s=new Map(n.map(p=>[p.name,p])),i=p=>{let h=s.get(U.rootOf(p));return new U(p).withVersion(h.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==U.rootOf(p)).map(U.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===U.rootOf(p))),u=new Set;for(let p of e){let h=U.rootOf(p),m=s.get(h),{isPeerRoot:g,hasPeers:b,isSharedDep:C}=r.get(h),T=a.has(h),E=p!==h,O=!(g||C)&&(T||!b),_=this.singletonDepsOf(m,o),x=E&&f.has(h);x&&u.add(h);let M=x?[..._,h]:_.length?_:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:O,external:M})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${zt}/${i(p)}/`]));return c}singletonDepsOf(e,n){return[...new Set([...ii(e.meta),...lf(e.meta)])].filter(r=>n.has(r))}};Cr.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as Tw,satisfies as q_,maxSatisfying as Cw,major as J_,valid as W_,validRange as K_}from"semver";var Ma,In,ff=k(()=>{Ma=class{cmp(e,n){return e===n?0:Tw(e,n)?1:Tw(n,e)?-1:0}satisfies(e,n){return!e||!e.trim()?!0:!!q_(n,e,{includePrerelease:!0})}selectBestVersion(e,n){if(!e?.length)return;let r=n?.range?.trim()||"*",s=n?.preferStable??!0,i=n?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(r,i))return i;if(s){let a=Cw(e,r,{includePrerelease:!1});if(a)return a}return Cw(e,r,{includePrerelease:!0})??void 0}majorOf(e){return J_(e)}isExactVersion(e){return W_(e)!==null}isRange(e){return K_(e)!==null}},In=new Ma});function H_(t){return Math.min(9e5*Math.pow(2,Math.max(0,t-1)),864e5)}var $n,Ow=k(()=>{Na();$n=class{constructor(e){this.store=e}async isNegative(e){let n=await _e(()=>this.store.get(e));return!!n&&n.until>Date.now()}async recordNegative(e){let r=((await _e(()=>this.store.get(e)))?.attempts||0)+1;await _e(()=>this.store.set(e,{until:Date.now()+H_(r),attempts:r}))}async clearNegative(e){await _e(()=>this.store.delete(e))}}});function Pw(t,e){let n=new si(t,e),r=new oi(n),s=new ai(t,n,In);return{packageService:new Cr(s,n,r),versionResolver:s,cdnClient:n,peerResolver:r}}var kt=k(()=>{cf();La();uf();df();ff();ri();ff();ni();cf();La();uf();df();Ow()});import*as pf from"fs/promises";import*as _w from"crypto";function nt(t){return _w.createHash("sha1").update(t).digest("hex")}async function xt(t){try{return JSON.parse(await pf.readFile(t,"utf8"))}catch{return}}async function Da(t){try{return await pf.readFile(t,"utf8")}catch{return}}var Or=k(()=>{"use strict"});import*as Vt from"fs/promises";import*as Et from"path";import*as Iw from"os";function se(){return hf||(hf=Y_().catch(()=>yt())),hf}function ja(t,e){return Et.join(z_,nt(t),e)}async function Y_(){await Vt.mkdir(Yt,{recursive:!0});let t=Et.join(Yt,"version.json");if((await xt(t))?.version===Rw)return;let n=await Vt.readdir(Yt).catch(()=>[]);await Promise.all(n.map(r=>Vt.rm(Et.join(Yt,r),{recursive:!0,force:!0}))),await Vt.writeFile(t,JSON.stringify({version:Rw})+`
545
- `,"utf8")}var Rw,Yt,ci,li,Ba,z_,hf,Pr=k(()=>{"use strict";Or();Ue();Rw=1,Yt=Et.join(Iw.homedir(),".typebulb","cache"),ci=Et.join(Yt,"packages"),li=Et.join(Yt,"proxy"),Ba=Et.join(Yt,"dts"),z_=Et.join(Yt,"emit")});import*as Gt from"fs/promises";import*as $w from"path";async function qe(t,e){let n=`${t}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await Gt.mkdir($w.dirname(t),{recursive:!0}),await Gt.writeFile(n,e,"utf8")}catch{yt();return}await Gt.rename(n,t).catch(async()=>{await Gt.rm(n,{force:!0}).catch(()=>{})})}var ui=k(()=>{"use strict";Ue()});var _r,mf=k(()=>{"use strict";ui();Or();_r=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=xt(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,n){let r=await this.load();r.set(e,n),await this.persist(r)}async delete(e){let n=await this.load();n.delete(e)&&await this.persist(n)}async persist(e){await qe(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as Mw from"fs/promises";import*as rt from"path";function Lw(t,e){return rt.join(V_,Fa(t),encodeURIComponent(e)+".json")}function Fa(t){return t.replace(/\//g,"__")}var gf,Nw,V_,G_,Ua,Dw=k(()=>{"use strict";kt();Pr();ui();mf();Or();gf=rt.join(ci,"indexes"),Nw=rt.join(ci,"pinned"),V_=rt.join(ci,"meta"),G_=rt.join(ci,"negative.json"),Ua=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new $n(new _r(G_));async getPinnedExact(e,n){let r=`${e}@${n}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await se();let s=await Da(rt.join(Nw,nt(r)+".txt"));return this.pinnedMem.set(r,s),s}async setPinnedExact(e,n,r){let s=`${e}@${n}`;this.pinnedMem.set(s,r),await se(),await qe(rt.join(Nw,nt(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await se();let n=await xt(rt.join(gf,Fa(e)+".json"));return this.indexMem.set(e,n),n}async setIndex(e,n,r){let s={versions:n,distTags:r,updatedAt:Date.now()};this.indexMem.set(e,s),await se(),await qe(rt.join(gf,Fa(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Mw.rm(rt.join(gf,Fa(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await se(),this.negativeCache.isNegative(e)}async recordNegative(e){await se(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,n){let r=`${e}@${n}`;if(this.metaMem.has(r))return this.metaMem.get(r);await se();let s=await xt(Lw(e,n));return this.metaMem.set(r,s),s}async setMeta(e,n,r,s,i){let o={dependencies:r,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${n}`,o),await se(),await qe(Lw(e,n),JSON.stringify(o))}}});var Bw,jw=k(()=>{"use strict";Bw={async getJson(t){try{let e=await fetch(t,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(t){try{let e=await fetch(t,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}}});var X_,qa,Fw,Uw,IU,yf=k(()=>{"use strict";kt();Dw();jw();X_=new Ua,{packageService:qa,versionResolver:Fw,cdnClient:Uw,peerResolver:IU}=Pw(X_,Bw)});function Ja(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function qw(){return` <script>
545
+ `,"utf8")}var Rw,Yt,ci,li,Ba,z_,hf,Pr=k(()=>{"use strict";Or();Ue();Rw=1,Yt=Et.join(Iw.homedir(),".typebulb","cache"),ci=Et.join(Yt,"packages"),li=Et.join(Yt,"proxy"),Ba=Et.join(Yt,"dts"),z_=Et.join(Yt,"emit")});import*as Gt from"fs/promises";import*as $w from"path";async function qe(t,e){let n=`${t}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await Gt.mkdir($w.dirname(t),{recursive:!0}),await Gt.writeFile(n,e,"utf8")}catch{yt();return}await Gt.rename(n,t).catch(async()=>{await Gt.rm(n,{force:!0}).catch(()=>{})})}var ui=k(()=>{"use strict";Ue()});var _r,mf=k(()=>{"use strict";ui();Or();_r=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=xt(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,n){let r=await this.load();r.set(e,n),await this.persist(r)}async delete(e){let n=await this.load();n.delete(e)&&await this.persist(n)}async persist(e){await qe(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as Mw from"fs/promises";import*as rt from"path";function Lw(t,e){return rt.join(V_,Fa(t),encodeURIComponent(e)+".json")}function Fa(t){return t.replace(/\//g,"__")}var gf,Nw,V_,G_,Ua,Dw=k(()=>{"use strict";kt();Pr();ui();mf();Or();gf=rt.join(ci,"indexes"),Nw=rt.join(ci,"pinned"),V_=rt.join(ci,"meta"),G_=rt.join(ci,"negative.json"),Ua=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new $n(new _r(G_));async getPinnedExact(e,n){let r=`${e}@${n}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await se();let s=await Da(rt.join(Nw,nt(r)+".txt"));return this.pinnedMem.set(r,s),s}async setPinnedExact(e,n,r){let s=`${e}@${n}`;this.pinnedMem.set(s,r),await se(),await qe(rt.join(Nw,nt(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await se();let n=await xt(rt.join(gf,Fa(e)+".json"));return this.indexMem.set(e,n),n}async setIndex(e,n,r){let s={versions:n,distTags:r,updatedAt:Date.now()};this.indexMem.set(e,s),await se(),await qe(rt.join(gf,Fa(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Mw.rm(rt.join(gf,Fa(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await se(),this.negativeCache.isNegative(e)}async recordNegative(e){await se(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,n){let r=`${e}@${n}`;if(this.metaMem.has(r))return this.metaMem.get(r);await se();let s=await xt(Lw(e,n));return this.metaMem.set(r,s),s}async setMeta(e,n,r,s,i){let o={dependencies:r,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${n}`,o),await se(),await qe(Lw(e,n),JSON.stringify(o))}}});var Bw,jw=k(()=>{"use strict";Bw={async getJson(t){try{let e=await fetch(t,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(t){try{let e=await fetch(t,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}}});var X_,qa,Fw,Uw,$U,yf=k(()=>{"use strict";kt();Dw();jw();X_=new Ua,{packageService:qa,versionResolver:Fw,cdnClient:Uw,peerResolver:$U}=Pw(X_,Bw)});function Ja(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function qw(){return` <script>
546
546
  ${_y}
547
547
  (function () {
548
548
  try {
@@ -2052,34 +2052,34 @@ Reply with the summary alone.
2052
2052
  [snipped for brevity]
2053
2053
 
2054
2054
  `+t.slice(t.length-n)},vI={ok:!1,error:"Summary needs OPENROUTER_API_KEY or OPENAI_API_KEY in this project\u2019s .env.",setup:!0},SI={ok:!1,error:"the model call failed or timed out"}});import{readFileSync as kI,statSync as xI}from"fs";function Fr(t,e,n,r){let s=t.apply(e,r),i=Date.parse(t.timestampOf(e)??""),o=s.events.map(a=>{let c=n==="child"&&a.type==="user"?{...a,authored:!0}:a;return!isNaN(i)&&(c.type==="user"||c.type==="assistant"||c.type==="tool_result"||c.type==="task_done"||c.type==="turn_end")&&(c.at=i),c});return{...s,events:o}}function mc(t){let e=new Map,n=t.linker();return{entries:e,add(r,s){let i;for(let o of r){if(!o.trim())continue;let a=t.parseEntry(o);if(!a)continue;n.link(a);let c=t.idOf(a);c&&(e.set(c,a),!t.isSidechain(a,s)&&t.isLeafType(a)&&(i=c))}return i}}}function Nv(t,e,n){let r=t.forRead(),s;try{s=kI(e,"utf8")}catch{return[]}let{entries:i,add:o}=mc(r),a=o(s.split(`
2055
- `),n),c=[],l=new Set;for(let d=a;d&&!l.has(d);){let p=i.get(d);if(!p)break;l.add(d),c.push(p),d=r.parentOf(p)}let f=[],u=Date.now();for(let d of c.reverse())if(!r.isSidechain(d,n))try{f.push(...Fr(r,d,n,u).events)}catch{}return f}function gc(t,e,n,r){let s=t.sessionAlive(e,n);if(s!==void 0)return s;if(!r)return!1;try{return Date.now()-xI(r).mtimeMs<1e4}catch{return!1}}function Ur(t,e){return t.stopped?"stopped":t.running&&e?"running":"done"}var yc=k(()=>{"use strict"});function EI(t,...e){return t.slice().sort((n,r)=>{for(let{key:s,desc:i}of e){let o=s(n),a=s(r);if(o!==a)return o==null?i?-1:1:a==null||o<a?i?1:-1:i?-1:1}return 0})}function Lv(t){let e=new Set(t.map(o=>o.id)),n=new Map;for(let o of t){let a=o.parentId&&e.has(o.parentId)?o.parentId:"",c=n.get(a);c?c.push(o):n.set(a,[o])}let r=[],s=new Set,i=o=>{for(let a of n.get(o)??[])s.has(a.id)||(s.add(a.id),r.push(a),i(a.id))};i("");for(let o of t)s.has(o.id)||r.push(o);return r}var gi,Bf=k(()=>{"use strict";gi=(t,e)=>EI(t,{key:e,desc:!0})});function jf(t){let e=[],n="",r,s=()=>{if(!r)return;let i=r.lines.join(`
2056
- `).trim(),o={kind:r.kind,id:r.id,text:i};if(r.kind==="Ask"){let[a,c]=i.split(CI);o.question=a.trim(),c?.trim()&&(o.recommend=c.trim())}e.push(o),r=void 0};for(let i of t.split(`
2057
- `)){let o=OI.exec(i)?.[1];if(n){o&&o[0]===n[0]&&o.length>=n.length&&(n="");continue}if(o){s(),n=o;continue}let a=TI.exec(i.trimStart());if(a){s(),r={kind:a[1],id:a[2],lines:[i.trimStart().slice(a[0].length)]};continue}if(r){if(!i.trim()||PI.test(i)){s();continue}r.lines.push(i.trim())}}return s(),e}function Mv(t,e){let n=[],r=0;for(let s of t)s.type==="cleared"?(n.length=0,r=0):s.type==="user"?r++:s.type==="assistant"&&!s.error&&s.text&&n.push(...jf(s.text).map(i=>({...i,turn:r,at:s.at,from:e})));return n}function Dv(t,e={}){let n=new Map;for(let r of t){let s=n.get(r.id)??{id:r.id,state:"open",latest:r,version:0,first:r.at};r.kind==="Ask"&&s.ask?.text!==r.text&&s.version++,r.kind==="Ask"&&(s.ask=r),s.latest=r,n.set(r.id,s)}for(let r of n.values()){let s=e[r.id];r.latest.kind==="Ask"?(r.answer=s&&s.version===r.version?s:void 0,r.state=r.answer?"answered":"open"):r.state=r.latest.kind.toLowerCase()}return[...n.values()]}function _I(t){return[t.choice==="accept"?`accept: ${t.recommend??""}`:t.choice==="todo"?"leave as todo":t.choice==="discuss"?"discuss":"",t.note?`note: "${t.note}"`:""].filter(Boolean).join(" \xB7 ")}function Bv(t,e){let n=t.filter(i=>i.state==="open"),r=t.filter(i=>i.state==="answered");if(!n.length&&!r.length)return[];let s=Math.min(...n.map(i=>i.ask?.at??e));return[n.length?`Asks: ${n.length} waiting on the owner, the oldest for ${ne(e-s)}.`:"Asks: none waiting on the owner.",...r.map(i=>` ${yi(i.id,i.answer)} (answered, not acknowledged)`)]}function Ff(t){let e=t.split(`
2058
- `).find(r=>r.trim())?.trim()??"",n=RI.exec(t)?.[1];return{line:e.length>200?e.slice(0,200)+"\u2026":e,boxMs:n?II(n):void 0}}function II(t){let e=/^(\d+(?:\.\d+)?)([smh]?)$/.exec(t),n=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,"":6e4}[e[2]]:0;return n>0?n:void 0}var AI,TI,CI,OI,PI,yi,RI,Dn=k(()=>{"use strict";or();AI=["Ask","Decided","Todo","Done","Finding"],TI=new RegExp(`^(?:[-*+]\\s+|\\d+[.)]\\s+)?\\*\\*(${AI.join("|")}) \\[([a-z0-9][a-z0-9-]*)\\]:?\\*\\*:?[ \\t]*`),CI=/\*{1,2}Recommend:\*{1,2}\s*/,OI=/^\s*(`{3,}|~{3,})/,PI=/^\s*(?:[-*+]|\d+[.)])\s+/;yi=(t,e)=>`[answer ${t} v${e.version}] ${_I(e)}`;RI=/^\s*\*\*Time box:\*\*\s*(\S+)\s*$/m});function Wv(t){let e=[],n=new Map,r=new Map,s=[],i=[],o=[],a=[],c,l={},f,u=!1,d=0;for(let h of t){if(h.type==="cleared"){e=[],n=new Map,r=new Map,s=[],i=[],o=[],a=[],c=void 0,l={},f=void 0,u=!1;continue}let m="at"in h?h.at:void 0;if(m!==void 0&&(d=Math.max(d,m)),h.type==="user"){if(f===void 0&&!h.agent)f=m,c??=Ff(h.text),l={start:m,boxMs:c.boxMs};else{m!==void 0&&s.push(m);let g=h.agent?void 0:Ff(h.text).boxMs;(g!==void 0||u&&!h.agent)&&(l={start:m,boxMs:g})}u=!1}else if(h.type==="assistant"){m!==void 0&&i.push(m);let g=h.error?void 0:h.text.split(`
2059
- `).find(b=>b.trim());g&&a.push({text:Bn(g,200),calls:e.length});for(let b of h.tools){let C={id:b.id,name:b.name,input:b.input,at:m,isError:!1};e.push(C),n.set(b.id,C)}}else if(h.type==="tool_result"){let g=n.get(h.id);if(!g)continue;Object.assign(g,{result:h.content,isError:h.isError,exit:h.exit,background:h.background,refused:h.refused,doneAt:m}),h.output&&(g.output=h.output),h.task&&r.set(h.task,g),m!==void 0&&i.push(m)}else if(h.type==="task_done"){let g=h.id?n.get(h.id):h.task?r.get(h.task):void 0;if(!g?.background||g.endAt!==void 0)continue;Object.assign(g,{endAt:m??d,outcome:h.outcome,output:h.output??g.output}),h.exit!==void 0&&(g.exit=h.exit),u&&m!==void 0&&(s.push(m),u=!1)}else h.type==="turn_end"&&(!u&&m!==void 0&&o.push(m),u=!0)}let p=l.start??f;return{calls:e,turnEnds:o,narration:a,lastAt:d,brief:c,boxMs:l.boxMs,runMs:Uv(e,s.filter(h=>h>(p??-1/0)),i,p,d).span,...Uv(e,s,i,f,d)}}function Uv(t,e,n,r,s){let i=r??t[0]?.at??s,o=[];for(let f of e){let u=-1/0;for(let p of n)p<=f&&p>u&&(u=p);let d=t.some(p=>p.at!==void 0&&p.at<f&&(p.doneAt??1/0)>f);u>-1/0&&!d&&f-u>=$I&&o.push([u,f])}let a=o.reduce((f,[u,d])=>f+Math.max(0,Math.min(s,d)-u),0),c=0,l=-1/0;for(let f of t.filter(u=>u.at!==void 0).sort((u,d)=>u.at-d.at)){let u=f.doneAt??s;u>l&&(c+=u-Math.max(f.at,l),l=u)}return{span:Math.max(0,s-i-a),idle:a,toolMs:c}}function Jf(t,e){if(qf(t))return;let n=Kv(t),r=t.background?t.endAt:t.doneAt,s=vi(t),i=!n&&(t.exit!==void 0?t.exit!==0&&!(t.exit===1&&s&&Qy(sa(s).rest)):t.background?t.outcome==="failed":t.isError),o=t.background?t.output?e?.(t.output)??"":"":t.result??"";return{id:t.id,at:t.at,open:n,failed:i,hidden:!n&&!i&&!!s&&Zy(s)||void 0,exit:t.exit,outcome:t.background?t.outcome:void 0,ms:t.at!==void 0&&r!==void 0?r-t.at:void 0,...NI(o)}}function NI(t){let e=Ls(t).split(`
2060
- `).map(n=>n.trim()).filter(n=>/[\p{L}\p{N}]/u.test(n));return/^exit(?: code)?:? \d+$/i.test(e[0]??"")&&e.shift(),{first:Bn(e[0]??"",120),last:e.length>1?Bn(e.at(-1),120):""}}function DI(t,e,n=wi){let r=new Map,s=0;for(let o of t.calls){let a=vi(o),c=a&&Jf(o,e);if(!c)continue;let l=Jv(a).trim();if(Xy(l)){s++;continue}r.set(l,[...r.get(l)??[],c])}let i=[...r].map(([o,a])=>{let c=0;for(let u of a.filter(d=>!d.open&&!d.hidden).reverse()){if(!u.failed)break;c++}let l=Fs(o),f=[LI.test(l)?"stops a process":"",MI.test(l)?"git write":""].filter(Boolean);return{cmd:Bn(ld(o),100),runs:a.length,open:a.filter(u=>u.open).length,failed:a.filter(u=>u.failed).length,hidden:a.filter(u=>u.hidden).length,streak:c,long:a.some(u=>(u.ms??0)>n)?`over ${n%6e4?`${Math.round(n/1e3)}s`:ne(n)}`:"",ms:a.reduce((u,d)=>u+(d.ms??0),0),tags:f,latest:a.at(-1)}}).sort((o,a)=>(a.latest.at??0)-(o.latest.at??0));return{runs:i.reduce((o,a)=>o+a.runs,0),failed:i.reduce((o,a)=>o+a.failed,0),lookups:s,groups:i}}function qI(t){let e=t.filter(Boolean),n=e.slice(Math.max(0,e.map(UI).lastIndexOf(!0)));if(n.some(s=>s.includes("$")||/^~|^-$/.test(s)))return;let r=[];for(let s of n.join("/").split("/"))s===".."&&r.length&&!/^(\.\.|[a-zA-Z]:)?$/.test(r.at(-1))?r.pop():s!=="."&&(s||!r.length)&&r.push(s);return r.join("/")}function Hv(t,e){let n=new Map,r=[],s=[],i=[],o=l=>l.trim().replace(/^["']|["']$/g,"").replace(/\\/g,"/").replace(/^\/([a-zA-Z])\//,"$1:/"),a=l=>{let f=My(o(l),e).replace(/^\.\//,"");return!f||/^([a-zA-Z]:)?\//.test(f)?void 0:f},c=l=>a(l)??(o(l)||void 0);for(let l of t.calls){if(l.isError||l.result===void 0)continue;let f=l.doneAt??l.at??0,u=(O,_={},x=!1)=>{let M=a(O);if(!M)return;let F=n.get(M)??{path:M};F.deleted=_.deleted,_.from&&(F.from=_.from),n.set(M,F),r.push({path:M,at:f,whole:x})},d=(O,_)=>{let x=a(O),M=x?n.get(x):void 0;x&&(n.delete(x),r.push({path:x,at:f})),u(_,{from:M?.from??x})},p=l.input??{},h=!1;for(let[O,_]of Object.entries(p)){if(O==="command"||O==="cmd"||typeof _!="string"||!/^(---|\+\+\+) /m.test(_))continue;let x;for(let M of _.split(`
2061
- `)){let F=/^(---|\+\+\+) (?:[ab]\/)?(.+?)\s*$/.exec(M);if(F?.[1]==="---"){x=F[2];continue}if(F?.[1]==="+++"){h=!0,F[2]==="/dev/null"?x&&x!=="/dev/null"&&u(x,{deleted:!0}):u(F[2]);continue}let ee=/^\*\*\* Move to: (.+?)\s*$/.exec(M);ee&&x&&d(x,ee[1])}}let m=te(p.file_path)??te(p.filePath)??te(p.path),g=FI.some(O=>O in p);!h&&m&&g&&u(m,{},typeof p.content=="string");let b=te(p.file_path)??te(p.filePath);if(b&&!g&&!h){let O=c(b);O&&s.push({path:O,at:f})}let C=O=>Object.entries(p).filter(([_,x])=>typeof x=="string"&&(_===O||_.startsWith(`${O} (`))).map(([,_])=>_);if(l.name==="read")for(let O of C("path")){let _=c(O);_&&s.push({path:_,at:f})}let T=te(p.workdir),E=O=>{let{dirs:_,rest:x}=sa(O);return{rest:x,at:M=>qI([e,T??"",..._,M].map(o))}};for(let O of[...C("command"),...C("cmd")]){let _=E(O);for(let x of nb(_.rest)){let M=_.at(x),F=M&&c(M);F&&i.push({path:F,at:f})}}let R=vi(l);if(R){let O=E(R);for(let _ of eb(O.rest)){let x=O.at(_.from),M=_.to&&O.at(_.to);x&&M?d(x,M):x&&!_.to&&u(x,{deleted:!0})}}}return{edited:[...n.values()],writes:r,reads:s,shellReads:i}}function zv(t){let e=new Map;for(let s of t)for(let i of s.writes)e.set(i.path,[...e.get(i.path)??[],{id:s.id,at:i.at,whole:i.whole}]);let n=new Map,r=new Map;for(let[s,i]of e){i.sort((a,c)=>a.at-c.at);let o=new Map;for(let a of i)o.set(a.id,a.at);n.set(s,[...o].map(([a,c])=>({id:a,at:c})).sort((a,c)=>a.at-c.at)),i.forEach((a,c)=>{if(!a.whole)return;let l=i.slice(0,c).reverse().find(d=>d.id!==a.id);if(!l)return;let f=t.find(d=>d.id===a.id);[...f.reads,...f.writes].some(d=>d.path===s&&d.at>l.at&&d.at<a.at)||r.set(`${s}
2055
+ `),n),c=[],l=new Set;for(let d=a;d&&!l.has(d);){let p=i.get(d);if(!p)break;l.add(d),c.push(p),d=r.parentOf(p)}let f=[],u=Date.now();for(let d of c.reverse())if(!r.isSidechain(d,n))try{f.push(...Fr(r,d,n,u).events)}catch{}return f}function gc(t,e,n,r){let s=t.sessionAlive(e,n);if(s!==void 0)return s;if(!r)return!1;try{return Date.now()-xI(r).mtimeMs<1e4}catch{return!1}}function Ur(t,e){return t.stopped?"stopped":t.running&&e?"running":"done"}var yc=k(()=>{"use strict"});function EI(t,...e){return t.slice().sort((n,r)=>{for(let{key:s,desc:i}of e){let o=s(n),a=s(r);if(o!==a)return o==null?i?-1:1:a==null||o<a?i?1:-1:i?-1:1}return 0})}function Lv(t){let e=new Set(t.map(o=>o.id)),n=new Map;for(let o of t){let a=o.parentId&&e.has(o.parentId)?o.parentId:"",c=n.get(a);c?c.push(o):n.set(a,[o])}let r=[],s=new Set,i=o=>{for(let a of n.get(o)??[])s.has(a.id)||(s.add(a.id),r.push(a),i(a.id))};i("");for(let o of t)s.has(o.id)||r.push(o);return r}var gi,Bf=k(()=>{"use strict";gi=(t,e)=>EI(t,{key:e,desc:!0})});function _I(t){let e=[],n="",r,s=o=>{if(!r)return;let a=r.lines.join(`
2056
+ `).trim(),c={kind:r.kind,id:r.id,text:a};if(r.kind==="Ask"){let[l,f]=a.split(CI);c.question=l.trim(),f?.trim()&&(c.recommend=f.trim())}e.push({tag:c,end:o}),r=void 0},i=t.split(`
2057
+ `);for(let o=0;o<i.length;o++){let a=i[o],c=OI.exec(a)?.[1];if(n){c&&c[0]===n[0]&&c.length>=n.length&&(n="");continue}if(c){s(o),n=c;continue}let l=TI.exec(a.trimStart());if(l){s(o),r={kind:l[1],id:l[2],lines:[a.trimStart().slice(l[0].length)]};continue}if(r){if(!a.trim()||PI.test(a)){s(o);continue}r.lines.push(a.trim())}}return s(i.length),e}function Mv(t,e){let n=[],r=0;for(let s of t)s.type==="cleared"?(n.length=0,r=0):s.type==="user"?r++:s.type==="assistant"&&!s.error&&s.text&&n.push(...jf(s.text).map(i=>({...i,turn:r,at:s.at,from:e})));return n}function Dv(t,e={}){let n=new Map;for(let r of t){let s=n.get(r.id)??{id:r.id,state:"open",latest:r,version:0,first:r.at};r.kind==="Ask"&&s.ask?.text!==r.text&&s.version++,r.kind==="Ask"&&(s.ask=r),s.latest=r,n.set(r.id,s)}for(let r of n.values()){let s=e[r.id];r.answer=r.ask&&s&&s.version===r.version?s:void 0,r.latest.kind==="Ask"?r.state=r.answer?"answered":"open":r.state=r.latest.kind.toLowerCase()}return[...n.values()]}function RI(t){return[t.choice==="accept"?`accept: ${t.recommend??""}`:t.choice==="todo"?"leave as todo":t.choice==="discuss"?"discuss":"",t.note?`note: "${t.note}"`:""].filter(Boolean).join(" \xB7 ")}function Bv(t,e){let n=t.filter(i=>i.state==="open"),r=t.filter(i=>i.state==="answered");if(!n.length&&!r.length)return[];let s=Math.min(...n.map(i=>i.ask?.at??e));return[n.length?`Asks: ${n.length} waiting on the owner, the oldest for ${ne(e-s)}.`:"Asks: none waiting on the owner.",...r.map(i=>` ${yi(i.id,i.answer)} (answered, not acknowledged)`)]}function Ff(t){let e=t.split(`
2058
+ `).find(r=>r.trim())?.trim()??"",n=II.exec(t)?.[1];return{line:e.length>200?e.slice(0,200)+"\u2026":e,boxMs:n?$I(n):void 0}}function $I(t){let e=/^(\d+(?:\.\d+)?)([smh]?)$/.exec(t),n=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,"":6e4}[e[2]]:0;return n>0?n:void 0}var AI,TI,CI,OI,PI,jf,yi,II,Dn=k(()=>{"use strict";or();AI=["Ask","Decided","Todo","Done","Finding"],TI=new RegExp(`^(?:[-*+]\\s+|\\d+[.)]\\s+)?\\*\\*(${AI.join("|")}) \\[([a-z0-9][a-z0-9-]*)\\]:?\\*\\*:?[ \\t]*`),CI=/\*{1,2}Recommend:\*{1,2}\s*/,OI=/^\s*(`{3,}|~{3,})/,PI=/^\s*(?:[-*+]|\d+[.)])\s+/,jf=t=>_I(t).map(e=>e.tag);yi=(t,e)=>`[answer ${t} v${e.version}] ${RI(e)}`;II=/^\s*\*\*Time box:\*\*\s*(\S+)\s*$/m});function Wv(t){let e=[],n=new Map,r=new Map,s=[],i=[],o=[],a=[],c,l={},f,u=!1,d=0;for(let h of t){if(h.type==="cleared"){e=[],n=new Map,r=new Map,s=[],i=[],o=[],a=[],c=void 0,l={},f=void 0,u=!1;continue}let m="at"in h?h.at:void 0;if(m!==void 0&&(d=Math.max(d,m)),h.type==="user"){if(f===void 0&&!h.agent)f=m,c??=Ff(h.text),l={start:m,boxMs:c.boxMs};else{m!==void 0&&s.push(m);let g=h.agent?void 0:Ff(h.text).boxMs;(g!==void 0||u&&!h.agent)&&(l={start:m,boxMs:g})}u=!1}else if(h.type==="assistant"){m!==void 0&&i.push(m);let g=h.error?void 0:h.text.split(`
2059
+ `).find(b=>b.trim());g&&a.push({text:Bn(g,200),calls:e.length});for(let b of h.tools){let C={id:b.id,name:b.name,input:b.input,at:m,isError:!1};e.push(C),n.set(b.id,C)}}else if(h.type==="tool_result"){let g=n.get(h.id);if(!g)continue;Object.assign(g,{result:h.content,isError:h.isError,exit:h.exit,background:h.background,refused:h.refused,doneAt:m}),h.output&&(g.output=h.output),h.task&&r.set(h.task,g),m!==void 0&&i.push(m)}else if(h.type==="task_done"){let g=h.id?n.get(h.id):h.task?r.get(h.task):void 0;if(!g?.background||g.endAt!==void 0)continue;Object.assign(g,{endAt:m??d,outcome:h.outcome,output:h.output??g.output}),h.exit!==void 0&&(g.exit=h.exit),u&&m!==void 0&&(s.push(m),u=!1)}else h.type==="turn_end"&&(!u&&m!==void 0&&o.push(m),u=!0)}let p=l.start??f;return{calls:e,turnEnds:o,narration:a,lastAt:d,brief:c,boxMs:l.boxMs,runMs:Uv(e,s.filter(h=>h>(p??-1/0)),i,p,d).span,...Uv(e,s,i,f,d)}}function Uv(t,e,n,r,s){let i=r??t[0]?.at??s,o=[];for(let f of e){let u=-1/0;for(let p of n)p<=f&&p>u&&(u=p);let d=t.some(p=>p.at!==void 0&&p.at<f&&(p.doneAt??1/0)>f);u>-1/0&&!d&&f-u>=NI&&o.push([u,f])}let a=o.reduce((f,[u,d])=>f+Math.max(0,Math.min(s,d)-u),0),c=0,l=-1/0;for(let f of t.filter(u=>u.at!==void 0).sort((u,d)=>u.at-d.at)){let u=f.doneAt??s;u>l&&(c+=u-Math.max(f.at,l),l=u)}return{span:Math.max(0,s-i-a),idle:a,toolMs:c}}function Jf(t,e){if(qf(t))return;let n=Kv(t),r=t.background?t.endAt:t.doneAt,s=vi(t),i=!n&&(t.exit!==void 0?t.exit!==0&&!(t.exit===1&&s&&Qy(sa(s).rest)):t.background?t.outcome==="failed":t.isError),o=t.background?t.output?e?.(t.output)??"":"":t.result??"";return{id:t.id,at:t.at,open:n,failed:i,hidden:!n&&!i&&!!s&&Zy(s)||void 0,exit:t.exit,outcome:t.background?t.outcome:void 0,ms:t.at!==void 0&&r!==void 0?r-t.at:void 0,...LI(o)}}function LI(t){let e=Ls(t).split(`
2060
+ `).map(n=>n.trim()).filter(n=>/[\p{L}\p{N}]/u.test(n));return/^exit(?: code)?:? \d+$/i.test(e[0]??"")&&e.shift(),{first:Bn(e[0]??"",120),last:e.length>1?Bn(e.at(-1),120):""}}function BI(t,e,n=wi){let r=new Map,s=0;for(let o of t.calls){let a=vi(o),c=a&&Jf(o,e);if(!c)continue;let l=Jv(a).trim();if(Xy(l)){s++;continue}r.set(l,[...r.get(l)??[],c])}let i=[...r].map(([o,a])=>{let c=0;for(let u of a.filter(d=>!d.open&&!d.hidden).reverse()){if(!u.failed)break;c++}let l=Fs(o),f=[MI.test(l)?"stops a process":"",DI.test(l)?"git write":""].filter(Boolean);return{cmd:Bn(ld(o),100),runs:a.length,open:a.filter(u=>u.open).length,failed:a.filter(u=>u.failed).length,hidden:a.filter(u=>u.hidden).length,streak:c,long:a.some(u=>(u.ms??0)>n)?`over ${n%6e4?`${Math.round(n/1e3)}s`:ne(n)}`:"",ms:a.reduce((u,d)=>u+(d.ms??0),0),tags:f,latest:a.at(-1)}}).sort((o,a)=>(a.latest.at??0)-(o.latest.at??0));return{runs:i.reduce((o,a)=>o+a.runs,0),failed:i.reduce((o,a)=>o+a.failed,0),lookups:s,groups:i}}function JI(t){let e=t.filter(Boolean),n=e.slice(Math.max(0,e.map(qI).lastIndexOf(!0)));if(n.some(s=>s.includes("$")||/^~|^-$/.test(s)))return;let r=[];for(let s of n.join("/").split("/"))s===".."&&r.length&&!/^(\.\.|[a-zA-Z]:)?$/.test(r.at(-1))?r.pop():s!=="."&&(s||!r.length)&&r.push(s);return r.join("/")}function Hv(t,e){let n=new Map,r=[],s=[],i=[],o=l=>l.trim().replace(/^["']|["']$/g,"").replace(/\\/g,"/").replace(/^\/([a-zA-Z])\//,"$1:/"),a=l=>{let f=My(o(l),e).replace(/^\.\//,"");return!f||/^([a-zA-Z]:)?\//.test(f)?void 0:f},c=l=>a(l)??(o(l)||void 0);for(let l of t.calls){if(l.isError||l.result===void 0)continue;let f=l.doneAt??l.at??0,u=(O,_={},x=!1)=>{let M=a(O);if(!M)return;let F=n.get(M)??{path:M};F.deleted=_.deleted,_.from&&(F.from=_.from),n.set(M,F),r.push({path:M,at:f,whole:x})},d=(O,_)=>{let x=a(O),M=x?n.get(x):void 0;x&&(n.delete(x),r.push({path:x,at:f})),u(_,{from:M?.from??x})},p=l.input??{},h=!1;for(let[O,_]of Object.entries(p)){if(O==="command"||O==="cmd"||typeof _!="string"||!/^(---|\+\+\+) /m.test(_))continue;let x;for(let M of _.split(`
2061
+ `)){let F=/^(---|\+\+\+) (?:[ab]\/)?(.+?)\s*$/.exec(M);if(F?.[1]==="---"){x=F[2];continue}if(F?.[1]==="+++"){h=!0,F[2]==="/dev/null"?x&&x!=="/dev/null"&&u(x,{deleted:!0}):u(F[2]);continue}let ee=/^\*\*\* Move to: (.+?)\s*$/.exec(M);ee&&x&&d(x,ee[1])}}let m=te(p.file_path)??te(p.filePath)??te(p.path),g=UI.some(O=>O in p);!h&&m&&g&&u(m,{},typeof p.content=="string");let b=te(p.file_path)??te(p.filePath);if(b&&!g&&!h){let O=c(b);O&&s.push({path:O,at:f})}let C=O=>Object.entries(p).filter(([_,x])=>typeof x=="string"&&(_===O||_.startsWith(`${O} (`))).map(([,_])=>_);if(l.name==="read")for(let O of C("path")){let _=c(O);_&&s.push({path:_,at:f})}let T=te(p.workdir),E=O=>{let{dirs:_,rest:x}=sa(O);return{rest:x,at:M=>JI([e,T??"",..._,M].map(o))}};for(let O of[...C("command"),...C("cmd")]){let _=E(O);for(let x of nb(_.rest)){let M=_.at(x),F=M&&c(M);F&&i.push({path:F,at:f})}}let R=vi(l);if(R){let O=E(R);for(let _ of eb(O.rest)){let x=O.at(_.from),M=_.to&&O.at(_.to);x&&M?d(x,M):x&&!_.to&&u(x,{deleted:!0})}}}return{edited:[...n.values()],writes:r,reads:s,shellReads:i}}function zv(t){let e=new Map;for(let s of t)for(let i of s.writes)e.set(i.path,[...e.get(i.path)??[],{id:s.id,at:i.at,whole:i.whole}]);let n=new Map,r=new Map;for(let[s,i]of e){i.sort((a,c)=>a.at-c.at);let o=new Map;for(let a of i)o.set(a.id,a.at);n.set(s,[...o].map(([a,c])=>({id:a,at:c})).sort((a,c)=>a.at-c.at)),i.forEach((a,c)=>{if(!a.whole)return;let l=i.slice(0,c).reverse().find(d=>d.id!==a.id);if(!l)return;let f=t.find(d=>d.id===a.id);[...f.reads,...f.writes].some(d=>d.path===s&&d.at>l.at&&d.at<a.at)||r.set(`${s}
2062
2062
  ${a.id}
2063
- ${l.id}`,{path:s,by:a.id,over:l.id,at:a.at,overAt:l.at})})}return{writers:n,blind:[...r.values()]}}function Yv(t,e,n,r,s,i,o,a=Wf,c=wi){let l=b=>`"${s.get(b)??b}"`,f=e.calls.filter(b=>!qf(b)&&Kv(b)).map(b=>({id:b.id,label:Uf(b),short:Bn(te(b.input?.description)??"",80)||Uf(b),at:b.at,background:!!b.background,interrupted:!i||t.liveSince!==void 0&&(b.at??0)<t.liveSince,said:r$(Jf(b,o))})),u=new Map;for(let b of[...n.reads,...n.shellReads].sort((C,T)=>C.at-T.at)){let C=u.get(b.path)??{path:b.path,times:0,at:0};u.delete(b.path),u.set(b.path,{...C,times:C.times+1,at:Math.max(C.at,b.at)})}let d=t.state==="running"&&!f.length?e.calls.filter(b=>!qf(b)).at(-1):void 0,p=d&&Jf(d),h=pc(t),m=h==="done"?"finished":h,g=m==="finished"&&e.narration.at(-1)?.calls===e.calls.length;return{id:t.id,name:ft(t),state:m,asOf:e.lastAt,activeMs:e.span,idleMs:e.idle,toolMs:e.toolMs,open:f,commands:JI(DI(e,o,c),f),files:n.edited.map(b=>{let C=a.since(b.path);return{...b,committed:!a.ignored(b.path)&&!a.uncommitted(b.path),ignored:a.ignored(b.path),also:(r.writers.get(b.path)??[]).filter(T=>T.id!==t.id&&T.at>C).map(T=>({name:s.get(T.id)??T.id,at:T.at})),blind:r.blind.filter(T=>T.path===b.path&&(T.by===t.id||T.over===t.id)&&T.overAt>C).map(T=>T.by===t.id?`\u26A0 written at ${qr(T.at)} over ${l(T.over)}'s ${qr(T.overAt)} write without reading it`:`\u26A0 ${l(T.by)} wrote over this agent's ${qr(T.overAt)} write at ${qr(T.at)} without reading it`)}}),read:[...u.values()].sort((b,C)=>b.at-C.at),narration:(g?e.narration.slice(0,-1):e.narration).map(b=>b.text),latest:d&&p?{id:d.id,label:Uf(d),run:p}:void 0,brief:e.brief?.line??"",boxMs:e.boxMs,runMs:e.runMs}}function JI(t,e){let n=new Set(e.filter(r=>r.interrupted).map(r=>r.id));return{...t,groups:t.groups.map(r=>n.has(r.latest.id)?{...r,latest:{...r.latest,interrupted:!0}}:r)}}function Gv(t,e){let n=t.state==="finished"?Jr(t).filter(r=>r.background):[];return n.length?`finished, background call running ${ne(e-(n[0].at??e))}${n.length>1?` (+${n.length-1} more)`:""}`:t.state}function zI(t,e){if(!t.open.length)return[`Now: ${HI(t,e)}`,...t.latest?[`Latest: ${t.latest.label} \xB7 ${tS(t.latest.run)}${t.latest.run.ms!==void 0?` after ${ne(t.latest.run.ms)}`:""}`]:[]];let n=(r,s)=>r.said?[`${s}"${r.said}"`]:[];return t.open.length===1?[`Now: ${qv(t.open[0],e)}`,...n(t.open[0]," ")]:["Now:",...t.open.flatMap(r=>[` ${qv(r,e)}`,...n(r," ")])]}function YI(t,e){let n=t.latest;return`latest: ${n.interrupted?"interrupted":n.open?`running ${ne(e-(n.at??e))}`:`${tS(n)}${n.ms!==void 0?` after ${ne(n.ms)}`:""}`}${t.streak>=2?`, failed ${t.streak} in a row`:""}`}function Qv(t,e){let n=[`Sub-agent "${t.name}" (${t.id}): ${KI(t,e)}${t.asOf?` \xB7 as of ${qr(t.asOf)}`:""}`,""];n.push(...zI(t,e));let r=t.commands;n.push(`Commands: ${BI(r)}`);let{shown:s,more:i}=ZI(r);for(let c of s){let l=n$(c);n.push(` ${c.cmd} \xD7${c.runs}${c.failed?`, ${c.failed} failed`:""}${l?` \xB7 ${l}`:""}`,` ${YI(c,e)}`);let f=[c.latest.first,c.latest.last].filter(Boolean).map(u=>`"${u}"`).join(" \u2026 ");f&&n.push(` ${f}`)}i&&n.push(` ${e$(i)}`),eS(r).runs&&n.push(` ${t$(r)}`),t.activeMs&&n.push(`Time: ${XI(t,e)}`),t.narration.length&&n.push("Narration:",...t.narration.map(c=>` ${c}`)),n.push(`Files written: ${VI(t)}`);for(let c of t.files){let l=c.also.length?` also ${QI(c)}`:"";n.push(` ${s$(c)}${c.ignored?" (ignored)":c.committed?" (committed)":""}${l}`,...c.blind.map(f=>` ${f}`))}let{shown:o,earlier:a}=o$(t);return n.push(`Files read: ${t.read.length||"none"}`,...a?[` +${a} earlier`]:[],...o.map(c=>` ${i$(c)}`)),n.join(`
2064
- `)}function GI(t,e){let n=t.toolMs+(Jr(t).some(r=>!r.background)?Kf(t,e):0);return{tools:n,model:Math.max(0,Hf(t,e)-n)}}function nS(t,e,n,r,s=[]){let i=e.filter(bi).length,o=Math.max(0,...e.map(p=>p.asOf)),a=[i?`Session ${t}: ${i} of ${e.length} agents running.`:`Session ${t}: No agent running for ${ne(r-o)} (${e.length} agents).`];if(s.length&&a.push("",...s),n.length){a.push("","Files to check before git add:");for(let p of n)a.push(` ${p.path} ${p.writers.map(h=>`"${h.name}"${h.running?" (running)":h.stopped?" (stopped)":""}`).join(", ")}${p.blind.length?" \u26A0":""}`)}a.push("","Agents:");let c=e.filter(p=>bi(p)||p.state==="failing"||n.some(h=>h.writers.some(m=>m.id===p.id))),l=new Set(c.map(p=>p.id));for(let p of c){let h=Jr(p)[0],m=p.state==="finished"?Jr(p).filter(R=>R.background):[],g=Gv(p,r).padEnd(8),b=m.length?m[0].short:h?`waiting ${ne(r-(h.at??r))} on ${h.short}`:"",C=WI(p),T=[b,zf(p,r)?Yf:"",C>=2?`failed ${C} in a row`:"",n.some(R=>R.blind.includes(p.id))?"\u26A0":""].filter(Boolean),E=p.parentId&&l.has(p.parentId)?" ".repeat(Math.max(0,p.depth-1)):"";a.push(` ${E}${p.id} ${g} ${`${ne(Hf(p,r))} active`.padStart(10)} ${p.name}${T.length?` \xB7 ${T.join(" \xB7 ")}`:""}`)}let f=e.filter(p=>!l.has(p.id)),u=f.filter(p=>p.state==="stopped").length,d=[f.length-u?`${f.length-u} finished`:"",u?`${u} stopped`:""].filter(Boolean).join(", ");return f.length&&a.push(` ${c.length?"+":""}${d}, nothing to check`),a.push("","Run `typebulb status <id>` for one agent's report, or `typebulb babysit` in the background to be woken when an agent or the user's answer needs you."),a.join(`
2065
- `)}function rS(t,e,n=!1,r=wi,s=[]){let i=new Map,o=c=>`"${t.find(l=>l.id===c)?.name??c}"`,a=Math.max(0,...t.map(c=>c.asOf));t.length&&!n&&!t.some(bi)&&!s.some(c=>c.state==="open")&&e-a>=a$&&i.set("idle",`No agent running for ${ne(e-a)} (${t.length} agents).`);for(let c of s)c.state==="answered"&&i.set(`answer:${c.id}:v${c.version}:${c.answer.at}`,yi(c.id,c.answer));for(let c of t){zf(c,e)&&i.set(`late:${c.id}`,`${o(c.id)}: ${Yf}, ${Xv(c,e).active}`);for(let l of Jr(c).filter(f=>e-(f.at??e)>=r)){let f=c.state==="finished"&&l.background;i.set(`${f?"background":"slow"}:${l.id}`,`${o(c.id)}: ${f?"finished, background call":"call"} running ${ne(e-(l.at??e))}: ${l.short}`)}for(let l of c.commands.groups.filter(f=>f.streak>=2))i.set(`streak:${c.id}:${l.cmd}`,`${o(c.id)}: failed ${l.streak} in a row: ${l.cmd}`)}return i}var $I,jv,Fv,wi,Bn,Jv,vi,qr,Uf,Kv,qf,LI,MI,BI,jI,FI,UI,Wf,Jr,bi,WI,Kf,Hf,Vv,zf,Yf,Xv,KI,qv,HI,VI,XI,QI,Zv,ZI,e$,eS,t$,n$,r$,tS,s$,i$,o$,a$,bc=k(()=>{"use strict";jr();or();ud();Dn();$I=6e4,jv=8,Fv=30,wi=3*6e4,Bn=(t,e)=>(t=Ls(t).replace(/\s+/g," ").trim(),t.length>e?t.slice(0,e)+"\u2026":t),Jv=t=>sa(t).rest,vi=t=>te(t.input?.command)??te(t.input?.cmd),qr=t=>new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),Uf=t=>{let e=vi(t);if(e)return Bn(ld(Jv(e).trim()),100);let n=Bn(By(t.input),80);return n?`${nd(t.name)}: ${n}`:nd(t.name)};Kv=t=>t.result===void 0||!!t.background&&t.endAt===void 0,qf=t=>!!t.refused&&vi(t)!==void 0;LI=/(^|[\s;|&(])(kill|pkill|killall|taskkill|stop-process)\b/i,MI=/\bgit\s+(-C\s+\S+\s+)?(commit|stash|checkout|reset|push|clean|restore|rebase|merge|cherry-pick|revert)(?![\w-])/;BI=t=>[t.runs?`${t.runs} run, ${t.failed} failed`:"",jI(t)].filter(Boolean).join(", ")||"none",jI=t=>t.lookups?`${t.lookups} ${t.lookups===1?"lookup":"lookups"}`:"",FI=["content","diff","new_string","new_source","edits"],UI=t=>/^([a-zA-Z]:)?\//.test(t);Wf={uncommitted:()=>!0,ignored:()=>!1,since:()=>0};Jr=t=>t.open.filter(e=>!e.interrupted),bi=t=>t.state==="running"||Jr(t).length>0,WI=t=>Math.max(0,...t.commands.groups.map(e=>e.streak)),Kf=(t,e)=>t.state==="running"?Math.max(0,e-t.asOf):0,Hf=(t,e)=>t.activeMs+Kf(t,e),Vv=(t,e)=>t.runMs+Kf(t,e),zf=(t,e)=>t.state==="running"&&t.boxMs!==void 0&&Vv(t,e)>t.boxMs,Yf="past its time box";Xv=(t,e)=>({state:Gv(t,e),active:`${ne(Hf(t,e))} active${t.boxMs?t.runMs<t.activeMs?`, ${ne(Vv(t,e))} of a ${ne(t.boxMs)} box this run`:` of a ${ne(t.boxMs)} box`:""}`,late:zf(t,e)?Yf:"",idle:t.idleMs?`${ne(t.idleMs)} idle`:""}),KI=(t,e)=>{let n=Xv(t,e);return[n.state,n.active,n.late,n.idle].filter(Boolean).join(" \xB7 ")},qv=(t,e)=>t.interrupted?`${t.label}: interrupted, its process has ended`:`${t.label}, ${ne(e-(t.at??e))}${t.background?" (background)":""}`,HI=(t,e)=>`nothing open, last entry ${ne(e-t.asOf)} ago`;VI=t=>{let e=t.files.filter(n=>!n.committed&&!n.ignored).length;return t.files.length?`${t.files.length} (${e} uncommitted)`:"none"};XI=(t,e)=>{let n=GI(t,e);return`${ne(n.tools)} in tools, ${ne(n.model)} in the model`},QI=t=>t.also.map(e=>`"${e.name}" ${qr(e.at)}`).join(", "),Zv=t=>t.failed>0||!!t.long||t.runs>=3||t.tags.length>0,ZI=t=>{let e=t.groups.filter(Zv);return{shown:e.slice(0,jv),more:Math.max(0,e.length-jv)}},e$=t=>`+${t} more like these`,eS=t=>{let e=t.groups.filter(n=>!Zv(n));return{runs:e.reduce((n,r)=>n+r.runs-r.open,0),hidden:e.reduce((n,r)=>n+r.hidden,0),ms:e.reduce((n,r)=>n+r.ms,0)}},t$=(t,e=!0)=>{let n=eS(t),r=n.runs-n.hidden,s=e?" other":"",i=c=>c===1?"run":"runs",o=`with ${n.hidden===1?"its":"their"} exit hidden by a pipe`;return`${r?`${r}${s} ${i(r)} passed${n.hidden?`, ${n.hidden} ${o}`:""}`:`${n.hidden}${s} ${i(n.hidden)} ${o}`}, ${ne(n.ms)} in all`},n$=t=>[...t.tags,t.long].filter(Boolean).join(", "),r$=t=>t?t.last||t.first:"",tS=t=>t.hidden?"exit hidden":t.outcome&&t.outcome!=="completed"&&t.outcome!=="failed"&&t.exit===void 0?t.outcome:t.exit!==void 0?`exit ${t.exit}`:t.failed?"error":"ok",s$=t=>t.deleted?`${t.path} (deleted)`:t.from?`${t.path} (moved from ${t.from})`:t.path,i$=t=>t.times>1?`${t.path} \xD7${t.times}`:t.path,o$=t=>({shown:t.read.slice(-Fv),earlier:Math.max(0,t.read.length-Fv)});a$=5*6e4});import{openSync as c$,readSync as l$,closeSync as u$,fstatSync as d$,statSync as f$,readFileSync as p$,writeFileSync as h$,mkdirSync as m$}from"fs";import{join as sS}from"path";function*Sc(t,e){if(!t.listChildren)return;let n=t.callerSessionId?.(e),r=gi(t.listSessionFiles(e),s=>s.mtime).sort((s,i)=>+(i.sessionId===n)-+(s.sessionId===n));for(let s of r){let i=t.listChildren(e,s.sessionId);i.length&&(yield iS(t,e,s.sessionId,s.file,i))}}function iS(t,e,n,r,s){let i=gc(t,n,e,r);return{sessionId:n,live:i,file:r,children:s.map(o=>({...o,state:Ur(o,i)}))}}function Si(t,e){let n=t.callerSessionId?.(e);return{sessionId:n,cwd:n&&t.sessionCwd?.(n)||e}}function oS(t,e){let n=Si(t,e);return n.sessionId?n:{sessionId:Sc(t,e).next().value?.sessionId,cwd:e}}function kc(t,e,n){let r=t.listSessionFiles(e).find(s=>s.sessionId===n)?.file;return iS(t,e,n,r,t.listChildren?.(e,n)??[])}function aS(t,e){let n=e.trim().toLowerCase(),r=t.children.filter(s=>s.id.toLowerCase()===n);return r.length?r:t.children.filter(s=>s.id.toLowerCase().startsWith(n)||ft(s).toLowerCase().includes(n))}function en(t,e){let n=sS(Ee(),"slow",t);if(e)try{m$(sS(n,".."),{recursive:!0}),h$(n,String(e))}catch{}let r=0;try{r=Number(p$(n,"utf8"))}catch{}return e||r||wi}function cS(t,e,n,r){let s={size:-1,mtimeMs:-1};try{s=f$(e)}catch{}let i=vc.get(e);if(i&&i.size===s.size&&i.mtime===s.mtimeMs&&i.cwd===n)return i;let o=Nv(t,e,"child"),a=Wv(o),c={size:s.size,mtime:s.mtimeMs,cwd:n,d:a,touches:Hv(a,n),tags:Mv(o,r)};return vc.set(e,c),c}function lS(t,e,n){let r=n.map(s=>({c:s,x:cS(t,s.file,e,s.id)}));return{tags:r.flatMap(s=>s.x.tags),briefs:new Map(r.map(s=>[s.c.id,s.x.d.brief?.line??""]))}}function g$(t){let e;try{e=c$(t,"r")}catch{return}try{let n=d$(e).size,r=(s,i)=>{let o=Buffer.alloc(i);return o.subarray(0,l$(e,o,0,i,s)).toString("utf8")};return n<=2*wc?r(0,n):`${r(0,wc)}
2066
- ${r(n-wc,wc)}`}catch{return}finally{u$(e)}}async function tn(t,e,n,r){let s=Lv([...n.children].sort((p,h)=>(p.started??p.mtime)-(h.started??h.mtime))),i=en(n.sessionId),o=s.map(p=>cS(t,p.file,e,p.id)),a=new Set(s.map(p=>p.file));for(let p of vc.keys())a.has(p)||vc.delete(p);let c=zv(s.map((p,h)=>({id:p.id,writes:o[h].touches.writes,reads:o[h].touches.reads}))),l=await b$(e,Math.min(1/0,...[...c.writers.values()].flat().map(p=>p.at)),[...c.writers.keys()]),f=new Map(s.map(p=>[p.id,ft(p)])),u=p=>r!==void 0&&(typeof r=="string"?p!==r:!r.has(p)),d=s.flatMap((p,h)=>u(p.id)?[]:[{...Yv(p,o[h].d,o[h].touches,c,f,n.live,g$,l,i),depth:p.depth,parentId:p.parentId}]);return{reports:d,files:r!==void 0?[]:y$(d,c,l)}}function y$(t,e,n){let r=new Set(t.filter(bi).map(a=>a.id)),s=new Set(t.filter(a=>a.state==="stopped").map(a=>a.id)),i=new Map(t.map(a=>[a.id,a.name]));return[...e.writers].filter(([a])=>n.uncommitted(a)).map(([a,c])=>{let l=n.since(a),f=c.filter(d=>d.at>l);if(f.length<2&&!f.some(d=>r.has(d.id)||s.has(d.id)))return;let u=e.blind.filter(d=>d.path===a&&d.overAt>l).flatMap(d=>[d.by,d.over]);return{path:a,writers:f.map(d=>({id:d.id,name:i.get(d.id)??d.id,running:r.has(d.id),stopped:s.has(d.id)})),blind:[...new Set(u)]}}).filter(a=>!!a).sort((a,c)=>a.path.localeCompare(c.path))}async function b$(t,e,n){let r=s=>process.platform==="win32"?s.toLowerCase():s;try{let s=(await Se(["rev-parse","--show-prefix"],t)).trim(),i=u=>u.startsWith(s)?r(u.slice(s.length)):void 0,o=await Se(["status","--porcelain","-z","--untracked-files=all"],t),a=new Set,c=o.split("\0");for(let u=0;u<c.length;u++){let d=c[u];if(d.length<4)continue;(d[0]==="R"||d[0]==="C")&&u++;let p=i(d.slice(3));p&&a.add(p)}let l=new Map;if(Number.isFinite(e)){let u=0;for(let d of(await Se(["log",`--since=${new Date(e).toISOString()}`,"--format=@%ct","--name-only","--","."],t)).split(`
2063
+ ${l.id}`,{path:s,by:a.id,over:l.id,at:a.at,overAt:l.at})})}return{writers:n,blind:[...r.values()]}}function Yv(t,e,n,r,s,i,o,a=Wf,c=wi){let l=b=>`"${s.get(b)??b}"`,f=e.calls.filter(b=>!qf(b)&&Kv(b)).map(b=>({id:b.id,label:Uf(b),short:Bn(te(b.input?.description)??"",80)||Uf(b),at:b.at,background:!!b.background,interrupted:!i||t.liveSince!==void 0&&(b.at??0)<t.liveSince,said:s$(Jf(b,o))})),u=new Map;for(let b of[...n.reads,...n.shellReads].sort((C,T)=>C.at-T.at)){let C=u.get(b.path)??{path:b.path,times:0,at:0};u.delete(b.path),u.set(b.path,{...C,times:C.times+1,at:Math.max(C.at,b.at)})}let d=t.state==="running"&&!f.length?e.calls.filter(b=>!qf(b)).at(-1):void 0,p=d&&Jf(d),h=pc(t),m=h==="done"?"finished":h,g=m==="finished"&&e.narration.at(-1)?.calls===e.calls.length;return{id:t.id,name:ft(t),state:m,asOf:e.lastAt,activeMs:e.span,idleMs:e.idle,toolMs:e.toolMs,open:f,commands:WI(BI(e,o,c),f),files:n.edited.map(b=>{let C=a.since(b.path);return{...b,committed:!a.ignored(b.path)&&!a.uncommitted(b.path),ignored:a.ignored(b.path),also:(r.writers.get(b.path)??[]).filter(T=>T.id!==t.id&&T.at>C).map(T=>({name:s.get(T.id)??T.id,at:T.at})),blind:r.blind.filter(T=>T.path===b.path&&(T.by===t.id||T.over===t.id)&&T.overAt>C).map(T=>T.by===t.id?`\u26A0 written at ${qr(T.at)} over ${l(T.over)}'s ${qr(T.overAt)} write without reading it`:`\u26A0 ${l(T.by)} wrote over this agent's ${qr(T.overAt)} write at ${qr(T.at)} without reading it`)}}),read:[...u.values()].sort((b,C)=>b.at-C.at),narration:(g?e.narration.slice(0,-1):e.narration).map(b=>b.text),latest:d&&p?{id:d.id,label:Uf(d),run:p}:void 0,brief:e.brief?.line??"",boxMs:e.boxMs,runMs:e.runMs}}function WI(t,e){let n=new Set(e.filter(r=>r.interrupted).map(r=>r.id));return{...t,groups:t.groups.map(r=>n.has(r.latest.id)?{...r,latest:{...r.latest,interrupted:!0}}:r)}}function Gv(t,e){let n=t.state==="finished"?Jr(t).filter(r=>r.background):[];return n.length?`finished, background call running ${ne(e-(n[0].at??e))}${n.length>1?` (+${n.length-1} more)`:""}`:t.state}function YI(t,e){if(!t.open.length)return[`Now: ${zI(t,e)}`,...t.latest?[`Latest: ${t.latest.label} \xB7 ${tS(t.latest.run)}${t.latest.run.ms!==void 0?` after ${ne(t.latest.run.ms)}`:""}`]:[]];let n=(r,s)=>r.said?[`${s}"${r.said}"`]:[];return t.open.length===1?[`Now: ${qv(t.open[0],e)}`,...n(t.open[0]," ")]:["Now:",...t.open.flatMap(r=>[` ${qv(r,e)}`,...n(r," ")])]}function VI(t,e){let n=t.latest;return`latest: ${n.interrupted?"interrupted":n.open?`running ${ne(e-(n.at??e))}`:`${tS(n)}${n.ms!==void 0?` after ${ne(n.ms)}`:""}`}${t.streak>=2?`, failed ${t.streak} in a row`:""}`}function Qv(t,e){let n=[`Sub-agent "${t.name}" (${t.id}): ${HI(t,e)}${t.asOf?` \xB7 as of ${qr(t.asOf)}`:""}`,""];n.push(...YI(t,e));let r=t.commands;n.push(`Commands: ${jI(r)}`);let{shown:s,more:i}=e$(r);for(let c of s){let l=r$(c);n.push(` ${c.cmd} \xD7${c.runs}${c.failed?`, ${c.failed} failed`:""}${l?` \xB7 ${l}`:""}`,` ${VI(c,e)}`);let f=[c.latest.first,c.latest.last].filter(Boolean).map(u=>`"${u}"`).join(" \u2026 ");f&&n.push(` ${f}`)}i&&n.push(` ${t$(i)}`),eS(r).runs&&n.push(` ${n$(r)}`),t.activeMs&&n.push(`Time: ${QI(t,e)}`),t.narration.length&&n.push("Narration:",...t.narration.map(c=>` ${c}`)),n.push(`Files written: ${GI(t)}`);for(let c of t.files){let l=c.also.length?` also ${ZI(c)}`:"";n.push(` ${i$(c)}${c.ignored?" (ignored)":c.committed?" (committed)":""}${l}`,...c.blind.map(f=>` ${f}`))}let{shown:o,earlier:a}=a$(t);return n.push(`Files read: ${t.read.length||"none"}`,...a?[` +${a} earlier`]:[],...o.map(c=>` ${o$(c)}`)),n.join(`
2064
+ `)}function XI(t,e){let n=t.toolMs+(Jr(t).some(r=>!r.background)?Kf(t,e):0);return{tools:n,model:Math.max(0,Hf(t,e)-n)}}function nS(t,e,n,r,s=[]){let i=e.filter(bi).length,o=Math.max(0,...e.map(p=>p.asOf)),a=[i?`Session ${t}: ${i} of ${e.length} agents running.`:`Session ${t}: No agent running for ${ne(r-o)} (${e.length} agents).`];if(s.length&&a.push("",...s),n.length){a.push("","Files to check before git add:");for(let p of n)a.push(` ${p.path} ${p.writers.map(h=>`"${h.name}"${h.running?" (running)":h.stopped?" (stopped)":""}`).join(", ")}${p.blind.length?" \u26A0":""}`)}a.push("","Agents:");let c=e.filter(p=>bi(p)||p.state==="failing"||n.some(h=>h.writers.some(m=>m.id===p.id))),l=new Set(c.map(p=>p.id));for(let p of c){let h=Jr(p)[0],m=p.state==="finished"?Jr(p).filter(R=>R.background):[],g=Gv(p,r).padEnd(8),b=m.length?m[0].short:h?`waiting ${ne(r-(h.at??r))} on ${h.short}`:"",C=KI(p),T=[b,zf(p,r)?Yf:"",C>=2?`failed ${C} in a row`:"",n.some(R=>R.blind.includes(p.id))?"\u26A0":""].filter(Boolean),E=p.parentId&&l.has(p.parentId)?" ".repeat(Math.max(0,p.depth-1)):"";a.push(` ${E}${p.id} ${g} ${`${ne(Hf(p,r))} active`.padStart(10)} ${p.name}${T.length?` \xB7 ${T.join(" \xB7 ")}`:""}`)}let f=e.filter(p=>!l.has(p.id)),u=f.filter(p=>p.state==="stopped").length,d=[f.length-u?`${f.length-u} finished`:"",u?`${u} stopped`:""].filter(Boolean).join(", ");return f.length&&a.push(` ${c.length?"+":""}${d}, nothing to check`),a.push("","Run `typebulb status <id>` for one agent's report, or `typebulb babysit` in the background to be woken when an agent or the user's answer needs you."),a.join(`
2065
+ `)}function rS(t,e,n=!1,r=wi,s=[]){let i=new Map,o=c=>`"${t.find(l=>l.id===c)?.name??c}"`,a=Math.max(0,...t.map(c=>c.asOf));t.length&&!n&&!t.some(bi)&&!s.some(c=>c.state==="open")&&e-a>=c$&&i.set("idle",`No agent running for ${ne(e-a)} (${t.length} agents).`);for(let c of s)c.state==="answered"&&i.set(`answer:${c.id}:v${c.version}:${c.answer.at}`,yi(c.id,c.answer));for(let c of t){zf(c,e)&&i.set(`late:${c.id}`,`${o(c.id)}: ${Yf}, ${Xv(c,e).active}`);for(let l of Jr(c).filter(f=>e-(f.at??e)>=r)){let f=c.state==="finished"&&l.background;i.set(`${f?"background":"slow"}:${l.id}`,`${o(c.id)}: ${f?"finished, background call":"call"} running ${ne(e-(l.at??e))}: ${l.short}`)}for(let l of c.commands.groups.filter(f=>f.streak>=2))i.set(`streak:${c.id}:${l.cmd}`,`${o(c.id)}: failed ${l.streak} in a row: ${l.cmd}`)}return i}var NI,jv,Fv,wi,Bn,Jv,vi,qr,Uf,Kv,qf,MI,DI,jI,FI,UI,qI,Wf,Jr,bi,KI,Kf,Hf,Vv,zf,Yf,Xv,HI,qv,zI,GI,QI,ZI,Zv,e$,t$,eS,n$,r$,s$,tS,i$,o$,a$,c$,bc=k(()=>{"use strict";jr();or();ud();Dn();NI=6e4,jv=8,Fv=30,wi=3*6e4,Bn=(t,e)=>(t=Ls(t).replace(/\s+/g," ").trim(),t.length>e?t.slice(0,e)+"\u2026":t),Jv=t=>sa(t).rest,vi=t=>te(t.input?.command)??te(t.input?.cmd),qr=t=>new Date(t).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),Uf=t=>{let e=vi(t);if(e)return Bn(ld(Jv(e).trim()),100);let n=Bn(By(t.input),80);return n?`${nd(t.name)}: ${n}`:nd(t.name)};Kv=t=>t.result===void 0||!!t.background&&t.endAt===void 0,qf=t=>!!t.refused&&vi(t)!==void 0;MI=/(^|[\s;|&(])(kill|pkill|killall|taskkill|stop-process)\b/i,DI=/\bgit\s+(-C\s+\S+\s+)?(commit|stash|checkout|reset|push|clean|restore|rebase|merge|cherry-pick|revert)(?![\w-])/;jI=t=>[t.runs?`${t.runs} run, ${t.failed} failed`:"",FI(t)].filter(Boolean).join(", ")||"none",FI=t=>t.lookups?`${t.lookups} ${t.lookups===1?"lookup":"lookups"}`:"",UI=["content","diff","new_string","new_source","edits"],qI=t=>/^([a-zA-Z]:)?\//.test(t);Wf={uncommitted:()=>!0,ignored:()=>!1,since:()=>0};Jr=t=>t.open.filter(e=>!e.interrupted),bi=t=>t.state==="running"||Jr(t).length>0,KI=t=>Math.max(0,...t.commands.groups.map(e=>e.streak)),Kf=(t,e)=>t.state==="running"?Math.max(0,e-t.asOf):0,Hf=(t,e)=>t.activeMs+Kf(t,e),Vv=(t,e)=>t.runMs+Kf(t,e),zf=(t,e)=>t.state==="running"&&t.boxMs!==void 0&&Vv(t,e)>t.boxMs,Yf="past its time box";Xv=(t,e)=>({state:Gv(t,e),active:`${ne(Hf(t,e))} active${t.boxMs?t.runMs<t.activeMs?`, ${ne(Vv(t,e))} of a ${ne(t.boxMs)} box this run`:` of a ${ne(t.boxMs)} box`:""}`,late:zf(t,e)?Yf:"",idle:t.idleMs?`${ne(t.idleMs)} idle`:""}),HI=(t,e)=>{let n=Xv(t,e);return[n.state,n.active,n.late,n.idle].filter(Boolean).join(" \xB7 ")},qv=(t,e)=>t.interrupted?`${t.label}: interrupted, its process has ended`:`${t.label}, ${ne(e-(t.at??e))}${t.background?" (background)":""}`,zI=(t,e)=>`nothing open, last entry ${ne(e-t.asOf)} ago`;GI=t=>{let e=t.files.filter(n=>!n.committed&&!n.ignored).length;return t.files.length?`${t.files.length} (${e} uncommitted)`:"none"};QI=(t,e)=>{let n=XI(t,e);return`${ne(n.tools)} in tools, ${ne(n.model)} in the model`},ZI=t=>t.also.map(e=>`"${e.name}" ${qr(e.at)}`).join(", "),Zv=t=>t.failed>0||!!t.long||t.runs>=3||t.tags.length>0,e$=t=>{let e=t.groups.filter(Zv);return{shown:e.slice(0,jv),more:Math.max(0,e.length-jv)}},t$=t=>`+${t} more like these`,eS=t=>{let e=t.groups.filter(n=>!Zv(n));return{runs:e.reduce((n,r)=>n+r.runs-r.open,0),hidden:e.reduce((n,r)=>n+r.hidden,0),ms:e.reduce((n,r)=>n+r.ms,0)}},n$=(t,e=!0)=>{let n=eS(t),r=n.runs-n.hidden,s=e?" other":"",i=c=>c===1?"run":"runs",o=`with ${n.hidden===1?"its":"their"} exit hidden by a pipe`;return`${r?`${r}${s} ${i(r)} passed${n.hidden?`, ${n.hidden} ${o}`:""}`:`${n.hidden}${s} ${i(n.hidden)} ${o}`}, ${ne(n.ms)} in all`},r$=t=>[...t.tags,t.long].filter(Boolean).join(", "),s$=t=>t?t.last||t.first:"",tS=t=>t.hidden?"exit hidden":t.outcome&&t.outcome!=="completed"&&t.outcome!=="failed"&&t.exit===void 0?t.outcome:t.exit!==void 0?`exit ${t.exit}`:t.failed?"error":"ok",i$=t=>t.deleted?`${t.path} (deleted)`:t.from?`${t.path} (moved from ${t.from})`:t.path,o$=t=>t.times>1?`${t.path} \xD7${t.times}`:t.path,a$=t=>({shown:t.read.slice(-Fv),earlier:Math.max(0,t.read.length-Fv)});c$=5*6e4});import{openSync as l$,readSync as u$,closeSync as d$,fstatSync as f$,statSync as p$,readFileSync as h$,writeFileSync as m$,mkdirSync as g$}from"fs";import{join as sS}from"path";function*Sc(t,e){if(!t.listChildren)return;let n=t.callerSessionId?.(e),r=gi(t.listSessionFiles(e),s=>s.mtime).sort((s,i)=>+(i.sessionId===n)-+(s.sessionId===n));for(let s of r){let i=t.listChildren(e,s.sessionId);i.length&&(yield iS(t,e,s.sessionId,s.file,i))}}function iS(t,e,n,r,s){let i=gc(t,n,e,r);return{sessionId:n,live:i,file:r,children:s.map(o=>({...o,state:Ur(o,i)}))}}function Si(t,e){let n=t.callerSessionId?.(e);return{sessionId:n,cwd:n&&t.sessionCwd?.(n)||e}}function oS(t,e){let n=Si(t,e);return n.sessionId?n:{sessionId:Sc(t,e).next().value?.sessionId,cwd:e}}function kc(t,e,n){let r=t.listSessionFiles(e).find(s=>s.sessionId===n)?.file;return iS(t,e,n,r,t.listChildren?.(e,n)??[])}function aS(t,e){let n=e.trim().toLowerCase(),r=t.children.filter(s=>s.id.toLowerCase()===n);return r.length?r:t.children.filter(s=>s.id.toLowerCase().startsWith(n)||ft(s).toLowerCase().includes(n))}function en(t,e){let n=sS(Ee(),"slow",t);if(e)try{g$(sS(n,".."),{recursive:!0}),m$(n,String(e))}catch{}let r=0;try{r=Number(h$(n,"utf8"))}catch{}return e||r||wi}function cS(t,e,n,r){let s={size:-1,mtimeMs:-1};try{s=p$(e)}catch{}let i=vc.get(e);if(i&&i.size===s.size&&i.mtime===s.mtimeMs&&i.cwd===n)return i;let o=Nv(t,e,"child"),a=Wv(o),c={size:s.size,mtime:s.mtimeMs,cwd:n,d:a,touches:Hv(a,n),tags:Mv(o,r)};return vc.set(e,c),c}function lS(t,e,n){let r=n.map(s=>({c:s,x:cS(t,s.file,e,s.id)}));return{tags:r.flatMap(s=>s.x.tags),briefs:new Map(r.map(s=>[s.c.id,s.x.d.brief?.line??""]))}}function y$(t){let e;try{e=l$(t,"r")}catch{return}try{let n=f$(e).size,r=(s,i)=>{let o=Buffer.alloc(i);return o.subarray(0,u$(e,o,0,i,s)).toString("utf8")};return n<=2*wc?r(0,n):`${r(0,wc)}
2066
+ ${r(n-wc,wc)}`}catch{return}finally{d$(e)}}async function tn(t,e,n,r){let s=Lv([...n.children].sort((p,h)=>(p.started??p.mtime)-(h.started??h.mtime))),i=en(n.sessionId),o=s.map(p=>cS(t,p.file,e,p.id)),a=new Set(s.map(p=>p.file));for(let p of vc.keys())a.has(p)||vc.delete(p);let c=zv(s.map((p,h)=>({id:p.id,writes:o[h].touches.writes,reads:o[h].touches.reads}))),l=await w$(e,Math.min(1/0,...[...c.writers.values()].flat().map(p=>p.at)),[...c.writers.keys()]),f=new Map(s.map(p=>[p.id,ft(p)])),u=p=>r!==void 0&&(typeof r=="string"?p!==r:!r.has(p)),d=s.flatMap((p,h)=>u(p.id)?[]:[{...Yv(p,o[h].d,o[h].touches,c,f,n.live,y$,l,i),depth:p.depth,parentId:p.parentId}]);return{reports:d,files:r!==void 0?[]:b$(d,c,l)}}function b$(t,e,n){let r=new Set(t.filter(bi).map(a=>a.id)),s=new Set(t.filter(a=>a.state==="stopped").map(a=>a.id)),i=new Map(t.map(a=>[a.id,a.name]));return[...e.writers].filter(([a])=>n.uncommitted(a)).map(([a,c])=>{let l=n.since(a),f=c.filter(d=>d.at>l);if(f.length<2&&!f.some(d=>r.has(d.id)||s.has(d.id)))return;let u=e.blind.filter(d=>d.path===a&&d.overAt>l).flatMap(d=>[d.by,d.over]);return{path:a,writers:f.map(d=>({id:d.id,name:i.get(d.id)??d.id,running:r.has(d.id),stopped:s.has(d.id)})),blind:[...new Set(u)]}}).filter(a=>!!a).sort((a,c)=>a.path.localeCompare(c.path))}async function w$(t,e,n){let r=s=>process.platform==="win32"?s.toLowerCase():s;try{let s=(await Se(["rev-parse","--show-prefix"],t)).trim(),i=u=>u.startsWith(s)?r(u.slice(s.length)):void 0,o=await Se(["status","--porcelain","-z","--untracked-files=all"],t),a=new Set,c=o.split("\0");for(let u=0;u<c.length;u++){let d=c[u];if(d.length<4)continue;(d[0]==="R"||d[0]==="C")&&u++;let p=i(d.slice(3));p&&a.add(p)}let l=new Map;if(Number.isFinite(e)){let u=0;for(let d of(await Se(["log",`--since=${new Date(e).toISOString()}`,"--format=@%ct","--name-only","--","."],t)).split(`
2067
2067
  `)){if(d.startsWith("@")){u=Number(d.slice(1))*1e3;continue}let p=d.trim()&&i(d.trim());p&&!l.has(p)&&l.set(p,u)}}let f=new Set(n.length?(await Se(["check-ignore","--",...n],t).catch(()=>"")).split(`
2068
- `).map(u=>r(u.trim())).filter(Boolean):[]);return{uncommitted:u=>a.has(r(u)),ignored:u=>f.has(r(u)),since:u=>l.get(r(u))??0}}catch{return Wf}}var vc,wc,ki=k(()=>{"use strict";Br();yc();jr();Bf();bc();Dn();Qt();vc=new Map;wc=4096});import{closeSync as w$,openSync as v$,readSync as S$,statSync as k$}from"fs";function uS(t,e){if(!e)return[];let n=Wr.get(e);Wr.delete(e),n??=new Vf(t,e),Wr.set(e,n);for(let r of[...Wr.keys()].slice(0,Math.max(0,Wr.size-E$)))Wr.delete(r);return n.tags()}var x$,Vf,E$,Wr,dS=k(()=>{"use strict";yc();Dn();x$=8<<20,Vf=class{constructor(e,n){this.file=n;this.#t=e.forRead(),this.#s=this.#t.linker()}#t;#s;#e=0;#r=Buffer.alloc(0);#c=new Map;#n;#o;tags(){let e=this.#l();if(this.#o&&!e)return this.#o;let n=[],r=new Set;for(let o=this.#n;o&&!r.has(o);){let a=this.#c.get(o);if(!a)break;r.add(o),n.push(a),o=a.parent??a.logical}let s=[],i=0;for(let o of n.reverse()){o.user&&i++;for(let a of o.tags)s.push({...a,turn:i})}return this.#o=s}#l(){let e=0;try{e=k$(this.file).size}catch{return!1}if(e<this.#e&&(this.#e=0,this.#r=Buffer.alloc(0),this.#c.clear(),this.#n=void 0,this.#s=this.#t.linker()),e===this.#e)return!1;let n;try{n=v$(this.file,"r")}catch{return!1}try{let r=Buffer.alloc(Math.min(x$,e-this.#e));for(;this.#e<e;){let s=S$(n,r,0,Math.min(r.length,e-this.#e),this.#e);if(!s)break;this.#e+=s;let i=Buffer.concat([this.#r,r.subarray(0,s)]),o=i.lastIndexOf(10);this.#r=Buffer.from(i.subarray(o+1)),o>=0&&this.#u(i.subarray(0,o).toString("utf8"))}}finally{w$(n)}return!0}#u(e){let n=this.#t,r=Date.now();for(let s of e.split(`
2069
- `)){if(!s.trim())continue;let i=n.parseEntry(s);if(!i)continue;this.#s.link(i);let o=n.idOf(i);if(!o)continue;let a=[];try{a=Fr(n,i,"main",r).events}catch{}let c=a.flatMap(l=>l.type==="assistant"&&!l.error&&l.text?jf(l.text).map(f=>({...f,at:l.at})):[]);this.#c.set(o,{parent:n.parentOf(i),logical:n.logicalParentOf?.(i),user:a.some(l=>l.type==="user"),tags:c}),!n.isSidechain(i,"main")&&n.isLeafType(i)&&(this.#n=o)}}},E$=4,Wr=new Map});import{mkdirSync as A$,readFileSync as T$,writeFileSync as C$}from"fs";import{join as fS}from"path";function hS(t){try{return JSON.parse(T$(pS(t),"utf8"))}catch{return{}}}function mS(t,e,n){let r=pS(t),s={...hS(t),[e]:n};A$(fS(r,".."),{recursive:!0}),C$(r,JSON.stringify(s,null,2)+`
2070
- `)}function jn(t,e,n,r,s){let{tags:i,briefs:o}=lS(t,e,s),a=[...uS(t,r),...i].sort((c,l)=>(c.at??0)-(l.at??0));return{threads:Dv(a,hS(n)),briefs:o}}var pS,xc=k(()=>{"use strict";dS();ki();Dn();Qt();pS=t=>fS(Ee(),"answers",`${t}.json`)});import{existsSync as gS,openSync as O$,readSync as P$,closeSync as _$,statSync as xi,readdirSync as yS,watchFile as R$,unwatchFile as bS,mkdirSync as I$,writeFileSync as $$,readFileSync as Gf,unlinkSync as N$,rmSync as L$}from"fs";import{stat as M$}from"fs/promises";import{dirname as D$,join as Fn,resolve as wS}from"path";function U$(t){if(!Number.isInteger(t))return!0;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Kr(t){let e={cwd:Z,sessionId:"",sessionStartMs:Date.now(),buffer:[],base:0,partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,index:mc(t),thread:"main"},n;function r(y,S){let v={offset:S,text:""},P;try{P=xi(y).size}catch{return v}if(P<=S)return v;let N;try{N=O$(y,"r")}catch{return v}try{let j=P-S,D=Buffer.alloc(j),J=0;for(;J<j;){let V=P$(N,D,J,j-J,S+J);if(!V)break;J+=V}return{offset:S+J,text:D.subarray(0,J).toString("utf8")}}finally{_$(N)}}let s=new Set,i,o=0;function a(){if(e.file){for(let y of s)if(y.file===e.file)return y;return}return i}function c(y){let S={d:t.createDriver(e.cwd,y),file:y,id:`new:${++o}`,startedAt:Date.now()};return s.add(S),e.file||(i=S),S}function l(){let y=[...s].filter(v=>v.file);if(!y.length)return[];let S=new Map(t.listSessionFiles(e.cwd).map(v=>[v.file,v.sessionId]));return y.map(v=>{let P=S.get(v.file);return{rec:v,sessionId:P??v.id,pending:P===void 0}})}let f=()=>l().filter(y=>y.pending&&y.rec.prompt!==void 0);async function u(y){s.delete(y),i===y&&(i=void 0);try{await y.d.dispose()}catch(S){console.error("[composer] dispose:",X(S))}}function d(){let y=a(),S=new Set(f().map(v=>v.rec));for(let v of[...s])v!==y&&(S.has(v)||v.d.streaming||v.d.queue||v.d.error||u(v))}function p(){for(let y of s)y.d.sessionFile&&y.file!==y.d.sessionFile&&(y.file=y.d.sessionFile);if(i&&!e.file&&i.file){let y=t.listSessionFiles(e.cwd).find(S=>S.file===i.file);y&&ee(y)}i&&!e.file&&i.prompt!==void 0&&e.sessionId!==i.id&&(M(void 0,i.id),e.everAttached=!0)}let h=y=>Fn(y,j$),m=(y,S)=>Fn(h(y),`${S}.lock`);function g(y,S){try{let v=m(y,S);if(Date.now()-xi(v).mtimeMs>=vS)return!1;try{let P=parseInt(Gf(v,"utf8").trim(),10);if(P===process.pid||!U$(P))return!1}catch{}return!0}catch{return!1}}function b(y,S){if(S)try{I$(h(y),{recursive:!0}),$$(m(y,S),String(process.pid))}catch(v){console.error("[lock] claim failed:",X(v))}}function C(y){try{L$(Fn(y,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function T(y){let S=h(y);if(!gS(S))return;let v;try{v=yS(S)}catch{return}let P=Date.now();for(let N of v){if(!N.endsWith(".lock"))continue;let j=Fn(S,N);try{let D=xi(j);P-D.mtimeMs>F$&&N$(j)}catch{}}}function E(y){try{return xi(y),!1}catch(S){return S.code==="ENOENT"}}function R(){let y=e;if(y.file&&!E(y.file)){b(y.cwd,y.sessionId);return}let S=O(y);S&&ee(S)}function O(y){if(!y.everAttached)return _(y.cwd)??x(y.cwd,()=>!0)}function _(y){let S=h(y);if(!gS(S))return;let v;try{v=yS(S)}catch{return}let P;for(let j of v)if(j.endsWith(".lock"))try{let D=xi(Fn(S,j));if(Date.now()-D.mtimeMs>=vS||parseInt(Gf(Fn(S,j),"utf8").trim(),10)!==process.pid)continue;(!P||D.mtimeMs>P.mtime)&&(P={sessionId:j.slice(0,-5),mtime:D.mtimeMs})}catch{}if(!P)return;let N=t.listSessionFiles(y).find(j=>j.sessionId===P.sessionId);if(!(!N||E(N.file)))return N}function x(y,S){return t.listSessionFiles(y).sort((v,P)=>P.mtime-v.mtime).find(v=>!g(y,v.sessionId)&&S(v))}function M(y,S){let v=e;if(v.file)try{bS(v.file)}catch{}v.file=y,v.sessionId=S,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.index=mc(t),v.chainLastId=void 0,F(S)}function F(y){e.base+=e.buffer.length,e.buffer=[{type:"cleared"},{type:"session",sessionId:y}]}function ee(y){let S=e;i=void 0,Fi(),n=y.file,M(y.file,y.sessionId),S.everAttached=!0,b(S.cwd,y.sessionId),q(y.file)}function q(y){if(ie(),!!y){try{bS(y)}catch{}R$(y,{interval:200},()=>ie())}}function ue(){Fi(),n=void 0,M(void 0,"")}function ie(){let y=e;if(!y.file)return;let S=r(y.file,y.offset);if(!S.text)return;y.offset=S.offset,y.partial+=S.text;let v=y.partial.lastIndexOf(`
2068
+ `).map(u=>r(u.trim())).filter(Boolean):[]);return{uncommitted:u=>a.has(r(u)),ignored:u=>f.has(r(u)),since:u=>l.get(r(u))??0}}catch{return Wf}}var vc,wc,ki=k(()=>{"use strict";Br();yc();jr();Bf();bc();Dn();Qt();vc=new Map;wc=4096});import{closeSync as v$,openSync as S$,readSync as k$,statSync as x$}from"fs";function uS(t,e){if(!e)return[];let n=Wr.get(e);Wr.delete(e),n??=new Vf(t,e),Wr.set(e,n);for(let r of[...Wr.keys()].slice(0,Math.max(0,Wr.size-A$)))Wr.delete(r);return n.tags()}var E$,Vf,A$,Wr,dS=k(()=>{"use strict";yc();Dn();E$=8<<20,Vf=class{constructor(e,n){this.file=n;this.#t=e.forRead(),this.#s=this.#t.linker()}#t;#s;#e=0;#r=Buffer.alloc(0);#c=new Map;#n;#o;tags(){let e=this.#l();if(this.#o&&!e)return this.#o;let n=[],r=new Set;for(let o=this.#n;o&&!r.has(o);){let a=this.#c.get(o);if(!a)break;r.add(o),n.push(a),o=a.parent??a.logical}let s=[],i=0;for(let o of n.reverse()){o.user&&i++;for(let a of o.tags)s.push({...a,turn:i})}return this.#o=s}#l(){let e=0;try{e=x$(this.file).size}catch{return!1}if(e<this.#e&&(this.#e=0,this.#r=Buffer.alloc(0),this.#c.clear(),this.#n=void 0,this.#s=this.#t.linker()),e===this.#e)return!1;let n;try{n=S$(this.file,"r")}catch{return!1}try{let r=Buffer.alloc(Math.min(E$,e-this.#e));for(;this.#e<e;){let s=k$(n,r,0,Math.min(r.length,e-this.#e),this.#e);if(!s)break;this.#e+=s;let i=Buffer.concat([this.#r,r.subarray(0,s)]),o=i.lastIndexOf(10);this.#r=Buffer.from(i.subarray(o+1)),o>=0&&this.#u(i.subarray(0,o).toString("utf8"))}}finally{v$(n)}return!0}#u(e){let n=this.#t,r=Date.now();for(let s of e.split(`
2069
+ `)){if(!s.trim())continue;let i=n.parseEntry(s);if(!i)continue;this.#s.link(i);let o=n.idOf(i);if(!o)continue;let a=[];try{a=Fr(n,i,"main",r).events}catch{}let c=a.flatMap(l=>l.type==="assistant"&&!l.error&&l.text?jf(l.text).map(f=>({...f,at:l.at})):[]);this.#c.set(o,{parent:n.parentOf(i),logical:n.logicalParentOf?.(i),user:a.some(l=>l.type==="user"),tags:c}),!n.isSidechain(i,"main")&&n.isLeafType(i)&&(this.#n=o)}}},A$=4,Wr=new Map});import{mkdirSync as T$,readFileSync as C$,writeFileSync as O$}from"fs";import{join as fS}from"path";function hS(t){try{return JSON.parse(C$(pS(t),"utf8"))}catch{return{}}}function mS(t,e,n){let r=pS(t),s={...hS(t),[e]:n};T$(fS(r,".."),{recursive:!0}),O$(r,JSON.stringify(s,null,2)+`
2070
+ `)}function jn(t,e,n,r,s){let{tags:i,briefs:o}=lS(t,e,s),a=[...uS(t,r),...i].sort((c,l)=>(c.at??0)-(l.at??0));return{threads:Dv(a,hS(n)),briefs:o}}var pS,xc=k(()=>{"use strict";dS();ki();Dn();Qt();pS=t=>fS(Ee(),"answers",`${t}.json`)});import{existsSync as gS,openSync as P$,readSync as _$,closeSync as R$,statSync as xi,readdirSync as yS,watchFile as I$,unwatchFile as bS,mkdirSync as $$,writeFileSync as N$,readFileSync as Gf,unlinkSync as L$,rmSync as M$}from"fs";import{stat as D$}from"fs/promises";import{dirname as B$,join as Fn,resolve as wS}from"path";function q$(t){if(!Number.isInteger(t))return!0;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}function Kr(t){let e={cwd:Z,sessionId:"",sessionStartMs:Date.now(),buffer:[],base:0,partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,index:mc(t),thread:"main"},n;function r(y,S){let v={offset:S,text:""},P;try{P=xi(y).size}catch{return v}if(P<=S)return v;let N;try{N=P$(y,"r")}catch{return v}try{let j=P-S,D=Buffer.alloc(j),J=0;for(;J<j;){let V=_$(N,D,J,j-J,S+J);if(!V)break;J+=V}return{offset:S+J,text:D.subarray(0,J).toString("utf8")}}finally{R$(N)}}let s=new Set,i,o=0;function a(){if(e.file){for(let y of s)if(y.file===e.file)return y;return}return i}function c(y){let S={d:t.createDriver(e.cwd,y),file:y,id:`new:${++o}`,startedAt:Date.now()};return s.add(S),e.file||(i=S),S}function l(){let y=[...s].filter(v=>v.file);if(!y.length)return[];let S=new Map(t.listSessionFiles(e.cwd).map(v=>[v.file,v.sessionId]));return y.map(v=>{let P=S.get(v.file);return{rec:v,sessionId:P??v.id,pending:P===void 0}})}let f=()=>l().filter(y=>y.pending&&y.rec.prompt!==void 0);async function u(y){s.delete(y),i===y&&(i=void 0);try{await y.d.dispose()}catch(S){console.error("[composer] dispose:",X(S))}}function d(){let y=a(),S=new Set(f().map(v=>v.rec));for(let v of[...s])v!==y&&(S.has(v)||v.d.streaming||v.d.queue||v.d.error||u(v))}function p(){for(let y of s)y.d.sessionFile&&y.file!==y.d.sessionFile&&(y.file=y.d.sessionFile);if(i&&!e.file&&i.file){let y=t.listSessionFiles(e.cwd).find(S=>S.file===i.file);y&&ee(y)}i&&!e.file&&i.prompt!==void 0&&e.sessionId!==i.id&&(M(void 0,i.id),e.everAttached=!0)}let h=y=>Fn(y,F$),m=(y,S)=>Fn(h(y),`${S}.lock`);function g(y,S){try{let v=m(y,S);if(Date.now()-xi(v).mtimeMs>=vS)return!1;try{let P=parseInt(Gf(v,"utf8").trim(),10);if(P===process.pid||!q$(P))return!1}catch{}return!0}catch{return!1}}function b(y,S){if(S)try{$$(h(y),{recursive:!0}),N$(m(y,S),String(process.pid))}catch(v){console.error("[lock] claim failed:",X(v))}}function C(y){try{M$(Fn(y,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function T(y){let S=h(y);if(!gS(S))return;let v;try{v=yS(S)}catch{return}let P=Date.now();for(let N of v){if(!N.endsWith(".lock"))continue;let j=Fn(S,N);try{let D=xi(j);P-D.mtimeMs>U$&&L$(j)}catch{}}}function E(y){try{return xi(y),!1}catch(S){return S.code==="ENOENT"}}function R(){let y=e;if(y.file&&!E(y.file)){b(y.cwd,y.sessionId);return}let S=O(y);S&&ee(S)}function O(y){if(!y.everAttached)return _(y.cwd)??x(y.cwd,()=>!0)}function _(y){let S=h(y);if(!gS(S))return;let v;try{v=yS(S)}catch{return}let P;for(let j of v)if(j.endsWith(".lock"))try{let D=xi(Fn(S,j));if(Date.now()-D.mtimeMs>=vS||parseInt(Gf(Fn(S,j),"utf8").trim(),10)!==process.pid)continue;(!P||D.mtimeMs>P.mtime)&&(P={sessionId:j.slice(0,-5),mtime:D.mtimeMs})}catch{}if(!P)return;let N=t.listSessionFiles(y).find(j=>j.sessionId===P.sessionId);if(!(!N||E(N.file)))return N}function x(y,S){return t.listSessionFiles(y).sort((v,P)=>P.mtime-v.mtime).find(v=>!g(y,v.sessionId)&&S(v))}function M(y,S){let v=e;if(v.file)try{bS(v.file)}catch{}v.file=y,v.sessionId=S,v.partial="",v.offset=0,v.latest={in:0,out:0,cached:0,cacheCreate:0},v.latestModel=null,v.index=mc(t),v.chainLastId=void 0,F(S)}function F(y){e.base+=e.buffer.length,e.buffer=[{type:"cleared"},{type:"session",sessionId:y}]}function ee(y){let S=e;i=void 0,Fi(),n=y.file,M(y.file,y.sessionId),S.everAttached=!0,b(S.cwd,y.sessionId),q(y.file)}function q(y){if(ie(),!!y){try{bS(y)}catch{}I$(y,{interval:200},()=>ie())}}function ue(){Fi(),n=void 0,M(void 0,"")}function ie(){let y=e;if(!y.file)return;let S=r(y.file,y.offset);if(!S.text)return;y.offset=S.offset,y.partial+=S.text;let v=y.partial.lastIndexOf(`
2071
2071
  `);if(v<0)return;let P=y.index.add(y.partial.slice(0,v).split(`
2072
- `),y.thread);if(y.partial=y.partial.slice(v+1),!P)return;let N=[],{entries:j}=y.index,D=j.get(P),J=!1;for(;D;){if(N.push(D),t.idOf(D)===y.chainLastId){J=!0;break}let V=t.parentOf(D);D=V?j.get(V):void 0}if(J)for(let V=N.length-2;V>=0;V--)be(N[V]);else{y.chainLastId!==void 0&&(F(y.sessionId),y.latest={in:0,out:0,cached:0,cacheCreate:0});let V=new Set(N.map(ze=>t.idOf(ze))),G=ye(j);for(let ze=N.length-1;ze>=0;ze--)be(N[ze]),xe(t.idOf(N[ze]),G,V)}y.chainLastId=P}function ye(y){let S=new Map;for(let v of y.values()){let P=t.parentOf(v);if(!P)continue;let N=S.get(P);N?N.push(v):S.set(P,[v])}return S}function xe(y,S,v){if(!y)return;let P=S.get(y);if(!P)return;let N=P.filter(V=>!t.isSidechain(V,e.thread));if(N.length<2)return;let j=N.filter(V=>!v.has(t.idOf(V)));if(!j.length)return;let D=[],J=0;for(let V of j){let G=de(V,S);D.push(...G.events),J+=G.count}J>0&&e.buffer.push({type:"fork",atId:y,count:J,events:D})}function de(y,S){let v=[],P=[y];for(;P.length;){let D=P.pop();if(t.isSidechain(D,e.thread))continue;v.push(D);let J=S.get(t.idOf(D)??"");if(J)for(let V of J)P.push(V)}v.sort((D,J)=>(Date.parse(t.timestampOf(D)??"")||0)-(Date.parse(t.timestampOf(J)??"")||0));let N=[];for(let D of v)t.isRecoveryNoise(D)||N.push(...Fr(t,D,e.thread,e.sessionStartMs).events);return{count:N.reduce((D,J)=>D+(J.type==="user"||J.type==="assistant"?1:0),0),events:N}}function be(y){if(!t.isSidechain(y,e.thread))try{let{events:S,usage:v,model:P,cost:N}=Fr(t,y,e.thread,e.sessionStartMs);for(let j of S)e.buffer.push(j);S.some(j=>j.type==="assistant")&&a()?.d.clearCompletedDraft(),S.some(j=>j.type==="user")&&a()?.d.clearEcho(),P&&(e.latestModel=P),v&&(e.latest=v),(v||N)&&e.buffer.push({type:"usage",...e.latest,cost:N})}catch(S){console.error("[mirror] skipped malformed entry:",X(S))}}async function ln(){return{cwd:e.cwd,pid:process.pid,composer:!!t.createDriver,children:!!t.listChildren,elsewhere:await w()}}async function w(){if(t.listSessionFiles(e.cwd).length)return;let y=await Mn();if(!y)return;let S=wS(y).toLowerCase();for(let v=wS(e.cwd);v.toLowerCase()!==S;){let P=D$(v);if(P===v)return;v=P;let N=t.listSessionFiles(v).length;if(N)return{dir:v,count:N}}}w().then(y=>{y&&console.log(`No sessions for ${e.cwd} \u2014 ${y.count} exist for ${y.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let A=new cc;async function I(y,S){e.thread!=="child"&&A.accept(y,S)&&console.log(S)}function L(){return gc(t,e.sessionId,e.cwd,e.file)}function B(){return t.chainWorking([...e.index.entries.values()])&&L()}function K(){!t.createDriver||a()||e.latestModel||B()||c(e.file)}async function H(y){let S=e;R(),p(),K(),d();let v=a();for(let D of s)D!==v&&D.d.dialog;let P=l().filter(D=>D.rec.d.streaming).map(D=>D.sessionId),N=B(),j=t.createDriver?{streaming:!!v?.d.streaming,foreign:!v&&N,draft:v?.d.draft??null,echo:v?.d.echo??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:S.buffer.slice(Math.max(0,y-S.base)),cursor:S.base+S.buffer.length,working:!!v?.d.streaming||N,latestModel:S.latestModel,child:S.child?.id??null,composer:j,busy:P}}async function Be(){R(),p();let y=a();if(y?.d.error&&!y.d.streaming&&(await u(y),y=void 0),!y){if(B())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};y=c(e.file)}let S=y;return{ok:!0,d:S.d,markSent:v=>{S.prompt===void 0&&(S.prompt=v)}}}async function Y(y,S){if(!t.createDriver)return{ok:!1,error:"not supported"};let v=String(y??"").trim();if(!v)return{ok:!1,error:"empty message"};let P=await Be();if(!P.ok)return P;let N=await P.d.send(v,S);return N.ok&&P.markSent(v),N}async function fe(y,S){let v=a();return v?v.d.respondUi(String(y??""),S??{}):{ok:!1,error:"no dialog pending"}}async function Re(y,S){if(!t.createDriver)return{ok:!1,error:"not supported"};if(!y||typeof y.type!="string")return{ok:!1,error:"bad command"};if(S?.spawn){let P=await Be();return P.ok?P.d.rpc(y):P}let v=a();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(y)}async function Qr(){let y=a();if(y)try{await y.d.stop()}catch(S){console.error("[composer] stop:",X(S))}return{ok:!0}}async function un(){return t.createDriver?(p(),!e.file&&i&&i.prompt===void 0&&!i.d.streaming&&!i.d.error?{ok:!0}:(i?.d.error&&await u(i),i=void 0,ue(),c(void 0),d(),{ok:!0})):{ok:!1,error:"not supported"}}async function _t(){if(!t.createDriver)return[];let y=await Se(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),S=y!==null?y.split(`
2073
- `).filter(Boolean):await t.walkFiles?.(e.cwd)??[];return(await Promise.all(S.map(async P=>{try{return{f:P,m:(await M$(Fn(e.cwd,P))).mtimeMs}}catch{return{f:P,m:0}}}))).sort((P,N)=>N.m-P.m).map(P=>P.f)}function el(){for(let y of[...s])u(y)}async function tl(y){return t.createDriver?Cv(e.cwd,y):{ok:!1,error:"not supported"}}async function Cx(y){return Ov(e.cwd,String(y??""))}async function Ox(y,S){return Iv(String(y??""),String(S??""))}async function Px(y){let S=t.listChildren?.(e.cwd,e.sessionId)??[],v=L(),{reports:[P]}=await tn(t,e.cwd,{sessionId:e.sessionId,live:v,children:S.map(N=>({...N,state:Ur(N,v)}))},y);return P?{ok:!0,report:P}:{ok:!1,error:"child not found"}}async function _x(y=!1){if(!e.sessionId||!n)return{threads:[],agents:[],others:[]};let S=t.listChildren?.(e.cwd,e.sessionId)??[],{threads:v,briefs:P}=jn(t,e.cwd,e.sessionId,n,S);if(!y)return{threads:v,agents:[],others:[]};let N=L(),j=S.map(G=>({...G,state:Ur(G,N)})),D=new Set(j.filter(G=>G.state==="running"||G.failing&&G.state!=="stopped").map(G=>G.id)),{reports:J}=D.size?await tn(t,e.cwd,{sessionId:e.sessionId,live:N,children:j},D):{reports:[]},V=j.filter(G=>!D.has(G.id)).map(G=>({id:G.id,name:ft(G),state:G.state,at:G.mtime,brief:P.get(G.id)??""}));return{threads:v,agents:J,others:V}}async function Rx(y,S,v,P){if(!e.sessionId||!n)return{ok:!1,error:"no session attached"};let N=t.listChildren?.(e.cwd,e.sessionId)??[],j=jn(t,e.cwd,e.sessionId,n,N).threads.find(V=>V.id===y);if(!j?.ask)return{ok:!1,error:"no such ask"};if(j.latest.kind!=="Ask")return{ok:!1,error:`already ${j.state}`};if(j.version!==S)return{ok:!1,error:"this ask has been asked again since; read it again"};let D=String(P??"").replace(/\s+/g," ").trim();if(!["accept","todo","discuss","note"].includes(v))return{ok:!1,error:"bad choice"};if(v==="accept"&&!j.ask.recommend)return{ok:!1,error:"this ask has no recommendation"};if(v==="note"&&!D)return{ok:!1,error:"empty note"};let J={version:S,choice:v,at:Date.now(),...v==="accept"?{recommend:j.ask.recommend}:{},...D?{note:D}:{}};return mS(e.sessionId,y,J),console.log(yi(y,J)),{ok:!0,answer:J}}async function Ix(){let y=t.sessionsWorking?.(e.cwd),S=t.sessionNames?.(),v=t.listSessionFiles(e.cwd).map(({sessionId:N,file:j,mtime:D})=>({sessionId:N,mtime:D,preview:t.readPreview(j),working:y?.has(N),name:S?.get(N)})),P=f().map(N=>({sessionId:N.sessionId,mtime:N.rec.startedAt,preview:N.rec.prompt??"",pending:!0}));return gi([...v,...P],N=>N.mtime)}let Hp=new Map;function zp(y,S){let v=Hp.get(y);if(v&&v.mtime===S)return v.turns;let P=[],N="";try{N=Gf(y,"utf8")}catch{return[]}for(let j of N.split(`
2074
- `)){if(!j.trim())continue;let D=t.parseEntry(j);if(!D)continue;let J=t.searchText(D);J&&P.push({text:J,lower:J.toLowerCase()})}return Hp.set(y,{mtime:S,turns:P}),P}async function $x(y){let S=y.toLowerCase(),v=[],P=0,N=t.sessionsWorking?.(e.cwd),j=t.sessionNames?.();for(let{sessionId:D,file:J,mtime:V}of t.listSessionFiles(e.cwd).sort((G,ze)=>ze.mtime-G.mtime)){let G=mi(zp(J,V),S),ze=(t.listChildren?.(e.cwd,D)??[]).map(Ye=>({c:Ye,hit:mi(zp(Ye.file,Ye.mtime),S)})).filter(Ye=>Ye.hit.hitCount);if(!(!G.hitCount&&!ze.length)){for(let{c:Ye,hit:Bx}of gi(ze,jx=>jx.c.mtime))v.push({sessionId:D,mtime:Ye.mtime,preview:ft(Ye),...Bx,child:{id:Ye.id,kind:Ye.kind,depth:Ye.depth}});if(v.push({sessionId:D,mtime:V,preview:t.readPreview(J),working:N?.has(D),name:j?.get(D),...G}),++P>=q$)break}}return v}async function Nx(y){let S=e,v=t.listSessionFiles(S.cwd).find(P=>P.sessionId===y);if(!v){let P=f().find(N=>N.sessionId===y)?.rec;return P?((i!==P||S.sessionId!==P.id)&&(i=P,Fi(),n=void 0,M(void 0,P.id),S.everAttached=!0,d()),{ok:!0}):{ok:!1,error:"session not found"}}return v.file===S.file?{ok:!0}:(ee(v),p(),d(),{ok:!0})}async function Lx(){if(!t.listChildren||!e.sessionId)return[];let y=L();return t.listChildren(e.cwd,e.sessionId).map(S=>({...S,state:Ur(S,y)}))}async function Mx(y){let S=e;if(!t.listChildren)return{ok:!1,error:"this harness has no child transcripts"};let v=t.listChildren(S.cwd,S.sessionId).find(P=>P.id===y);return v?(S.thread="child",S.child=v,M(v.file,S.sessionId),q(v.file),{ok:!0}):{ok:!1,error:"child not found"}}async function Dx(){let y=n;return!Fi()||!y?{ok:!0}:(M(y,e.sessionId),q(y),{ok:!0})}function Fi(){let y=e;return y.thread==="main"?!1:(y.thread="main",y.child=void 0,!0)}return C(e.cwd),T(e.cwd),R(),{info:ln,poll:H,logInlineStatus:I,listSessions:Ix,searchSessions:$x,attach:Nx,listChildren:Lx,openChild:Mx,closeChild:Dx,composerSend:Y,composerStop:Qr,composerNew:un,composerFiles:_t,composerUiRespond:fe,composerRpc:Re,composerPaste:tl,composerPasteRead:Cx,summarizeTurn:Ox,childStatus:Px,board:_x,answerAsk:Rx,shutdownComposer:el}}var B$,j$,vS,F$,q$,Ec=k(()=>{"use strict";Zt();Sv();Br();Mf();Pv();$v();yc();ki();xc();Dn();Bf();jr();B$=".typebulb",j$=`${B$}/locks`,vS=5e3,F$=6e4;q$=50});import{existsSync as ep,mkdirSync as J$,readFileSync as SS,writeFileSync as W$}from"fs";import{join as Un,isAbsolute as K$}from"path";async function np(t,e){let n=K$(t)?t:Un(Z,t);return ep(n)?(Md(n,e),{ok:!0}):{ok:!1,error:"file not found"}}async function rp(t){let e=Z,n=Ld(t),r=Un(e,"typebulbs");J$(r,{recursive:!0});let s=Rd(n),i=`${s}.bulb.md`;for(let l=2;ep(Un(r,i))&&SS(Un(r,i),"utf8")!==n;l++)i=`${s}-${l}.bulb.md`;let o=Un(r,i);ep(o)||W$(o,n);let a=Un("typebulbs",i),c=await xn(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function sp(){return Q(Z)}async function ip(t){let e=(await Q()).find(n=>n.pid===t);return e?{ok:!0,outcome:await wt(e)}:(await fr(t),{ok:!0})}async function op(){let t=await wn(Z);return Sa(Z).filter(e=>!e.serverOnly).map(e=>({...e,trusted:Tn(e.path),lastRunAt:t(e.path)}))}async function ap(t){let e=t.toLowerCase(),n=[];for(let r of Sa(Z).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=SS(r.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
2075
- `)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=mi(i,e);o&&n.push({path:r.path,hitCount:o,snippet:a})}return n}async function cp(t,e){let n=Z;e!=null&&br(t,e);let r=await xn(t,{cwd:n,open:!1,trust:e});return{ok:!0,file:r.file,pid:r.pid,url:r.url,trust:!!r.trust}}async function lp(t){return{cap:await $d(t)}}async function up(t,e){return br(t,e),{ok:!0}}async function dp(t,e){return Ze(t,e)}async function fp(){return Ei&&Date.now()-Ei.fetchedAt<=z$?Ei.samples:(Xf??=Y$().finally(()=>{Xf=null}),Xf)}async function Y$(){try{let t=await fetch(`${H$}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(xS)});if(!t.ok)throw new Error(`HTTP ${t.status}`);let e=await t.json(),n=i=>i.order??Number.MAX_SAFE_INTEGER,r=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>n(i)-n(o)||r(o)-r(i)).map(i=>({slug:i.slug,name:i.name,description:ul(i.config)}));return Ei={samples:s,fetchedAt:Date.now()},s}catch{return Ei?.samples??[]}}async function pp(t){return tp.test(t)?AS(kS,"samples",t,!0):{ok:!1,error:"bad slug"}}async function mp(){let t=hp();if(!t)return{bulbs:[]};let e=`${Ac()}
2076
- ${t}`;return nn?.key===e&&Date.now()-nn.fetchedAt<=V$?{user:nn.user,bulbs:nn.bulbs}:(Qf??=G$(e,t).finally(()=>{Qf=null}),Qf)}async function Zf(t,e,n){let r=await fetch(`${t}${e}`,{headers:n,signal:AbortSignal.timeout(xS)});if(!r.ok)throw new Error(`HTTP ${r.status}`);if(!r.headers.get("content-type")?.includes("json"))throw new Error("not json");return r.json()}async function G$(t,e){let n={Authorization:`Bearer ${e}`};try{let r=Ac(),s;try{s=await Zf(r,"/api/me",n)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await Zf(r,"/api/me",n)}let o=(await Zf(r,"/api/scripts/list",n)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:ul(a.config)}));return nn={key:t,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return nn?.key===t?{user:nn.user,bulbs:nn.bulbs}:{bulbs:[]}}}async function gp(t,e,n=!1){return!tp.test(e)||!tp.test(t)?{ok:!1,error:"bad slug"}:AS(Ac(),t,e,n)}async function AS(t,e,n,r){let s=Za(e,n);try{let i=await nc({origin:t,userSlug:e,slug:n,dest:Un(Z,s)},{force:r,token:hp(),timeoutMs:ES});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="asset-conflict"?{ok:!1,conflict:!0,error:`local assets differ from the site copies (${i.paths.join(", ")})`}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function yp(t,e=!1){let n=hp();if(!n)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=tc(t,Z,Ac()),s=await sc(r,{token:n,force:e,timeoutMs:ES});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="asset-error"?{ok:!1,error:`assets sync failed: ${s.message}`}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(r){return{ok:!1,error:r?.message??String(r)}}}var H$,kS,z$,xS,ES,Ei,Xf,tp,V$,nn,Qf,Ac,hp,Tc=k(()=>{"use strict";Qt();Zt();Mf();re();H$="https://api.typebulb.com",kS="https://typebulb.com",z$=3600*1e3,xS=5e3,ES=15e3,Ei=null,Xf=null;tp=/^[a-z0-9][a-z0-9-]*$/,V$=300*1e3,nn=null,Qf=null,Ac=()=>Ia("TYPEBULB_ORIGIN",Z)||kS,hp=()=>Ia("TYPEBULB_TOKEN",Z)});import{readFileSync as vp,writeFileSync as CS,mkdirSync as X$,appendFileSync as OS,rmSync as TS}from"fs";import{join as Pc,dirname as Q$}from"path";import{createServer as Z$}from"http";function rn(t){try{return JSON.parse(vp(t,"utf8"))}catch{return null}}function Oc(t,e){X$(Q$(t),{recursive:!0}),CS(t,JSON.stringify(e,null,2)+`
2072
+ `),y.thread);if(y.partial=y.partial.slice(v+1),!P)return;let N=[],{entries:j}=y.index,D=j.get(P),J=!1;for(;D;){if(N.push(D),t.idOf(D)===y.chainLastId){J=!0;break}let V=t.parentOf(D);D=V?j.get(V):void 0}if(J)for(let V=N.length-2;V>=0;V--)be(N[V]);else{y.chainLastId!==void 0&&(F(y.sessionId),y.latest={in:0,out:0,cached:0,cacheCreate:0});let V=new Set(N.map(ze=>t.idOf(ze))),G=ye(j);for(let ze=N.length-1;ze>=0;ze--)be(N[ze]),xe(t.idOf(N[ze]),G,V)}y.chainLastId=P}function ye(y){let S=new Map;for(let v of y.values()){let P=t.parentOf(v);if(!P)continue;let N=S.get(P);N?N.push(v):S.set(P,[v])}return S}function xe(y,S,v){if(!y)return;let P=S.get(y);if(!P)return;let N=P.filter(V=>!t.isSidechain(V,e.thread));if(N.length<2)return;let j=N.filter(V=>!v.has(t.idOf(V)));if(!j.length)return;let D=[],J=0;for(let V of j){let G=de(V,S);D.push(...G.events),J+=G.count}J>0&&e.buffer.push({type:"fork",atId:y,count:J,events:D})}function de(y,S){let v=[],P=[y];for(;P.length;){let D=P.pop();if(t.isSidechain(D,e.thread))continue;v.push(D);let J=S.get(t.idOf(D)??"");if(J)for(let V of J)P.push(V)}v.sort((D,J)=>(Date.parse(t.timestampOf(D)??"")||0)-(Date.parse(t.timestampOf(J)??"")||0));let N=[];for(let D of v)t.isRecoveryNoise(D)||N.push(...Fr(t,D,e.thread,e.sessionStartMs).events);return{count:N.reduce((D,J)=>D+(J.type==="user"||J.type==="assistant"?1:0),0),events:N}}function be(y){if(!t.isSidechain(y,e.thread))try{let{events:S,usage:v,model:P,cost:N}=Fr(t,y,e.thread,e.sessionStartMs);for(let j of S)e.buffer.push(j);S.some(j=>j.type==="assistant")&&a()?.d.clearCompletedDraft(),S.some(j=>j.type==="user")&&a()?.d.clearEcho(),P&&(e.latestModel=P),v&&(e.latest=v),(v||N)&&e.buffer.push({type:"usage",...e.latest,cost:N})}catch(S){console.error("[mirror] skipped malformed entry:",X(S))}}async function ln(){return{cwd:e.cwd,pid:process.pid,composer:!!t.createDriver,children:!!t.listChildren,elsewhere:await w()}}async function w(){if(t.listSessionFiles(e.cwd).length)return;let y=await Mn();if(!y)return;let S=wS(y).toLowerCase();for(let v=wS(e.cwd);v.toLowerCase()!==S;){let P=B$(v);if(P===v)return;v=P;let N=t.listSessionFiles(v).length;if(N)return{dir:v,count:N}}}w().then(y=>{y&&console.log(`No sessions for ${e.cwd} \u2014 ${y.count} exist for ${y.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let A=new cc;async function I(y,S){e.thread!=="child"&&A.accept(y,S)&&console.log(S)}function L(){return gc(t,e.sessionId,e.cwd,e.file)}function B(){return t.chainWorking([...e.index.entries.values()])&&L()}function K(){!t.createDriver||a()||e.latestModel||B()||c(e.file)}async function H(y){let S=e;R(),p(),K(),d();let v=a();for(let D of s)D!==v&&D.d.dialog;let P=l().filter(D=>D.rec.d.streaming).map(D=>D.sessionId),N=B(),j=t.createDriver?{streaming:!!v?.d.streaming,foreign:!v&&N,draft:v?.d.draft??null,echo:v?.d.echo??null,status:v?.d.status??null,dialog:v?.d.dialog??null,queue:v?.d.queue??null,stats:v?.d.stats??null,model:v?.d.model??null,error:v?.d.error}:void 0;return{events:S.buffer.slice(Math.max(0,y-S.base)),cursor:S.base+S.buffer.length,working:!!v?.d.streaming||N,latestModel:S.latestModel,child:S.child?.id??null,composer:j,busy:P}}async function Be(){R(),p();let y=a();if(y?.d.error&&!y.d.streaming&&(await u(y),y=void 0),!y){if(B())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};y=c(e.file)}let S=y;return{ok:!0,d:S.d,markSent:v=>{S.prompt===void 0&&(S.prompt=v)}}}async function Y(y,S){if(!t.createDriver)return{ok:!1,error:"not supported"};let v=String(y??"").trim();if(!v)return{ok:!1,error:"empty message"};let P=await Be();if(!P.ok)return P;let N=await P.d.send(v,S);return N.ok&&P.markSent(v),N}async function fe(y,S){let v=a();return v?v.d.respondUi(String(y??""),S??{}):{ok:!1,error:"no dialog pending"}}async function Re(y,S){if(!t.createDriver)return{ok:!1,error:"not supported"};if(!y||typeof y.type!="string")return{ok:!1,error:"bad command"};if(S?.spawn){let P=await Be();return P.ok?P.d.rpc(y):P}let v=a();return!v||v.d.error?{ok:!1,error:"not running"}:v.d.rpc(y)}async function Qr(){let y=a();if(y)try{await y.d.stop()}catch(S){console.error("[composer] stop:",X(S))}return{ok:!0}}async function un(){return t.createDriver?(p(),!e.file&&i&&i.prompt===void 0&&!i.d.streaming&&!i.d.error?{ok:!0}:(i?.d.error&&await u(i),i=void 0,ue(),c(void 0),d(),{ok:!0})):{ok:!1,error:"not supported"}}async function _t(){if(!t.createDriver)return[];let y=await Se(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),S=y!==null?y.split(`
2073
+ `).filter(Boolean):await t.walkFiles?.(e.cwd)??[];return(await Promise.all(S.map(async P=>{try{return{f:P,m:(await D$(Fn(e.cwd,P))).mtimeMs}}catch{return{f:P,m:0}}}))).sort((P,N)=>N.m-P.m).map(P=>P.f)}function el(){for(let y of[...s])u(y)}async function tl(y){return t.createDriver?Cv(e.cwd,y):{ok:!1,error:"not supported"}}async function Cx(y){return Ov(e.cwd,String(y??""))}async function Ox(y,S){return Iv(String(y??""),String(S??""))}async function Px(y){let S=t.listChildren?.(e.cwd,e.sessionId)??[],v=L(),{reports:[P]}=await tn(t,e.cwd,{sessionId:e.sessionId,live:v,children:S.map(N=>({...N,state:Ur(N,v)}))},y);return P?{ok:!0,report:P}:{ok:!1,error:"child not found"}}async function _x(y=!1){if(!e.sessionId||!n)return{threads:[],agents:[],others:[]};let S=t.listChildren?.(e.cwd,e.sessionId)??[],{threads:v,briefs:P}=jn(t,e.cwd,e.sessionId,n,S);if(!y)return{threads:v,agents:[],others:[]};let N=L(),j=S.map(G=>({...G,state:Ur(G,N)})),D=new Set(j.filter(G=>G.state==="running"||G.failing&&G.state!=="stopped").map(G=>G.id)),{reports:J}=D.size?await tn(t,e.cwd,{sessionId:e.sessionId,live:N,children:j},D):{reports:[]},V=j.filter(G=>!D.has(G.id)).map(G=>({id:G.id,name:ft(G),state:G.state,at:G.mtime,brief:P.get(G.id)??""}));return{threads:v,agents:J,others:V}}async function Rx(y,S,v,P){if(!e.sessionId||!n)return{ok:!1,error:"no session attached"};let N=t.listChildren?.(e.cwd,e.sessionId)??[],j=jn(t,e.cwd,e.sessionId,n,N).threads.find(V=>V.id===y);if(!j?.ask)return{ok:!1,error:"no such ask"};if(j.latest.kind!=="Ask")return{ok:!1,error:`already ${j.state}`};if(j.version!==S)return{ok:!1,error:"this ask has been asked again since; read it again"};let D=String(P??"").replace(/\s+/g," ").trim();if(!["accept","todo","discuss","note"].includes(v))return{ok:!1,error:"bad choice"};if(v==="accept"&&!j.ask.recommend)return{ok:!1,error:"this ask has no recommendation"};if(v==="note"&&!D)return{ok:!1,error:"empty note"};let J={version:S,choice:v,at:Date.now(),...v==="accept"?{recommend:j.ask.recommend}:{},...D?{note:D}:{}};return mS(e.sessionId,y,J),console.log(yi(y,J)),{ok:!0,answer:J}}async function Ix(){let y=t.sessionsWorking?.(e.cwd),S=t.sessionNames?.(),v=t.listSessionFiles(e.cwd).map(({sessionId:N,file:j,mtime:D})=>({sessionId:N,mtime:D,preview:t.readPreview(j),working:y?.has(N),name:S?.get(N)})),P=f().map(N=>({sessionId:N.sessionId,mtime:N.rec.startedAt,preview:N.rec.prompt??"",pending:!0}));return gi([...v,...P],N=>N.mtime)}let Hp=new Map;function zp(y,S){let v=Hp.get(y);if(v&&v.mtime===S)return v.turns;let P=[],N="";try{N=Gf(y,"utf8")}catch{return[]}for(let j of N.split(`
2074
+ `)){if(!j.trim())continue;let D=t.parseEntry(j);if(!D)continue;let J=t.searchText(D);J&&P.push({text:J,lower:J.toLowerCase()})}return Hp.set(y,{mtime:S,turns:P}),P}async function $x(y){let S=y.toLowerCase(),v=[],P=0,N=t.sessionsWorking?.(e.cwd),j=t.sessionNames?.();for(let{sessionId:D,file:J,mtime:V}of t.listSessionFiles(e.cwd).sort((G,ze)=>ze.mtime-G.mtime)){let G=mi(zp(J,V),S),ze=(t.listChildren?.(e.cwd,D)??[]).map(Ye=>({c:Ye,hit:mi(zp(Ye.file,Ye.mtime),S)})).filter(Ye=>Ye.hit.hitCount);if(!(!G.hitCount&&!ze.length)){for(let{c:Ye,hit:Bx}of gi(ze,jx=>jx.c.mtime))v.push({sessionId:D,mtime:Ye.mtime,preview:ft(Ye),...Bx,child:{id:Ye.id,kind:Ye.kind,depth:Ye.depth}});if(v.push({sessionId:D,mtime:V,preview:t.readPreview(J),working:N?.has(D),name:j?.get(D),...G}),++P>=J$)break}}return v}async function Nx(y){let S=e,v=t.listSessionFiles(S.cwd).find(P=>P.sessionId===y);if(!v){let P=f().find(N=>N.sessionId===y)?.rec;return P?((i!==P||S.sessionId!==P.id)&&(i=P,Fi(),n=void 0,M(void 0,P.id),S.everAttached=!0,d()),{ok:!0}):{ok:!1,error:"session not found"}}return v.file===S.file?{ok:!0}:(ee(v),p(),d(),{ok:!0})}async function Lx(){if(!t.listChildren||!e.sessionId)return[];let y=L();return t.listChildren(e.cwd,e.sessionId).map(S=>({...S,state:Ur(S,y)}))}async function Mx(y){let S=e;if(!t.listChildren)return{ok:!1,error:"this harness has no child transcripts"};let v=t.listChildren(S.cwd,S.sessionId).find(P=>P.id===y);return v?(S.thread="child",S.child=v,M(v.file,S.sessionId),q(v.file),{ok:!0}):{ok:!1,error:"child not found"}}async function Dx(){let y=n;return!Fi()||!y?{ok:!0}:(M(y,e.sessionId),q(y),{ok:!0})}function Fi(){let y=e;return y.thread==="main"?!1:(y.thread="main",y.child=void 0,!0)}return C(e.cwd),T(e.cwd),R(),{info:ln,poll:H,logInlineStatus:I,listSessions:Ix,searchSessions:$x,attach:Nx,listChildren:Lx,openChild:Mx,closeChild:Dx,composerSend:Y,composerStop:Qr,composerNew:un,composerFiles:_t,composerUiRespond:fe,composerRpc:Re,composerPaste:tl,composerPasteRead:Cx,summarizeTurn:Ox,childStatus:Px,board:_x,answerAsk:Rx,shutdownComposer:el}}var j$,F$,vS,U$,J$,Ec=k(()=>{"use strict";Zt();Sv();Br();Mf();Pv();$v();yc();ki();xc();Dn();Bf();jr();j$=".typebulb",F$=`${j$}/locks`,vS=5e3,U$=6e4;J$=50});import{existsSync as ep,mkdirSync as W$,readFileSync as SS,writeFileSync as K$}from"fs";import{join as Un,isAbsolute as H$}from"path";async function np(t,e){let n=H$(t)?t:Un(Z,t);return ep(n)?(Md(n,e),{ok:!0}):{ok:!1,error:"file not found"}}async function rp(t){let e=Z,n=Ld(t),r=Un(e,"typebulbs");W$(r,{recursive:!0});let s=Rd(n),i=`${s}.bulb.md`;for(let l=2;ep(Un(r,i))&&SS(Un(r,i),"utf8")!==n;l++)i=`${s}-${l}.bulb.md`;let o=Un(r,i);ep(o)||K$(o,n);let a=Un("typebulbs",i),c=await xn(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function sp(){return Q(Z)}async function ip(t){let e=(await Q()).find(n=>n.pid===t);return e?{ok:!0,outcome:await wt(e)}:(await fr(t),{ok:!0})}async function op(){let t=await wn(Z);return Sa(Z).filter(e=>!e.serverOnly).map(e=>({...e,trusted:Tn(e.path),lastRunAt:t(e.path)}))}async function ap(t){let e=t.toLowerCase(),n=[];for(let r of Sa(Z).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=SS(r.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
2075
+ `)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=mi(i,e);o&&n.push({path:r.path,hitCount:o,snippet:a})}return n}async function cp(t,e){let n=Z;e!=null&&br(t,e);let r=await xn(t,{cwd:n,open:!1,trust:e});return{ok:!0,file:r.file,pid:r.pid,url:r.url,trust:!!r.trust}}async function lp(t){return{cap:await $d(t)}}async function up(t,e){return br(t,e),{ok:!0}}async function dp(t,e){return Ze(t,e)}async function fp(){return Ei&&Date.now()-Ei.fetchedAt<=Y$?Ei.samples:(Xf??=V$().finally(()=>{Xf=null}),Xf)}async function V$(){try{let t=await fetch(`${z$}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(xS)});if(!t.ok)throw new Error(`HTTP ${t.status}`);let e=await t.json(),n=i=>i.order??Number.MAX_SAFE_INTEGER,r=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>n(i)-n(o)||r(o)-r(i)).map(i=>({slug:i.slug,name:i.name,description:ul(i.config)}));return Ei={samples:s,fetchedAt:Date.now()},s}catch{return Ei?.samples??[]}}async function pp(t){return tp.test(t)?AS(kS,"samples",t,!0):{ok:!1,error:"bad slug"}}async function mp(){let t=hp();if(!t)return{bulbs:[]};let e=`${Ac()}
2076
+ ${t}`;return nn?.key===e&&Date.now()-nn.fetchedAt<=G$?{user:nn.user,bulbs:nn.bulbs}:(Qf??=X$(e,t).finally(()=>{Qf=null}),Qf)}async function Zf(t,e,n){let r=await fetch(`${t}${e}`,{headers:n,signal:AbortSignal.timeout(xS)});if(!r.ok)throw new Error(`HTTP ${r.status}`);if(!r.headers.get("content-type")?.includes("json"))throw new Error("not json");return r.json()}async function X$(t,e){let n={Authorization:`Bearer ${e}`};try{let r=Ac(),s;try{s=await Zf(r,"/api/me",n)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await Zf(r,"/api/me",n)}let o=(await Zf(r,"/api/scripts/list",n)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:ul(a.config)}));return nn={key:t,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return nn?.key===t?{user:nn.user,bulbs:nn.bulbs}:{bulbs:[]}}}async function gp(t,e,n=!1){return!tp.test(e)||!tp.test(t)?{ok:!1,error:"bad slug"}:AS(Ac(),t,e,n)}async function AS(t,e,n,r){let s=Za(e,n);try{let i=await nc({origin:t,userSlug:e,slug:n,dest:Un(Z,s)},{force:r,token:hp(),timeoutMs:ES});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="asset-conflict"?{ok:!1,conflict:!0,error:`local assets differ from the site copies (${i.paths.join(", ")})`}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function yp(t,e=!1){let n=hp();if(!n)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=tc(t,Z,Ac()),s=await sc(r,{token:n,force:e,timeoutMs:ES});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="asset-error"?{ok:!1,error:`assets sync failed: ${s.message}`}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(r){return{ok:!1,error:r?.message??String(r)}}}var z$,kS,Y$,xS,ES,Ei,Xf,tp,G$,nn,Qf,Ac,hp,Tc=k(()=>{"use strict";Qt();Zt();Mf();re();z$="https://api.typebulb.com",kS="https://typebulb.com",Y$=3600*1e3,xS=5e3,ES=15e3,Ei=null,Xf=null;tp=/^[a-z0-9][a-z0-9-]*$/,G$=300*1e3,nn=null,Qf=null,Ac=()=>Ia("TYPEBULB_ORIGIN",Z)||kS,hp=()=>Ia("TYPEBULB_TOKEN",Z)});import{readFileSync as vp,writeFileSync as CS,mkdirSync as Q$,appendFileSync as OS,rmSync as TS}from"fs";import{join as Pc,dirname as Z$}from"path";import{createServer as e1}from"http";function rn(t){try{return JSON.parse(vp(t,"utf8"))}catch{return null}}function Oc(t,e){Q$(Z$(t),{recursive:!0}),CS(t,JSON.stringify(e,null,2)+`
2077
2077
  `)}function _S(t,e,n){let r=Pc(t,".gitignore"),s="";try{s=vp(r,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
2078
2078
  `)?`
2079
2079
  `:"";try{OS(r,a+n+`
2080
2080
  `+o.join(`
2081
2081
  `)+`
2082
- `)}catch(c){console.error("[switcher] .gitignore update failed",X(c))}}function s1(t){let e=i=>{let o=i.exec(t);return o?Number(o[1]):0},n=e(/"cache_read_input_tokens":\s*(\d+)/),r=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);n>0||r>0?Ci="live":s>r1&&(Ci="uncached")}function IS(t,e){let n={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":t.headers["anthropic-version"]||"2023-06-01",...Jd},r=t.headers["anthropic-beta"];return typeof r=="string"&&(n["anthropic-beta"]=r),n}function i1(t){if(Array.isArray(t?.messages))for(let e of t.messages){if(!Array.isArray(e?.content))continue;let n=e.content.filter(r=>r?.type!=="thinking"&&r?.type!=="redacted_thinking");n.length&&n.length!==e.content.length&&(e.content=n)}}function $S(t){let e;try{e=JSON.parse(t)}catch{return t}Ti=typeof e?.model=="string"?e.model:null,pt&&(e.model=pt),Jn&&(e.provider=RS(Jn));let n=/haiku/i.test(Ti||"");return Oi!=null&&!n&&(e.reasoning={effort:bp[Oi]}),delete e.thinking,e.output_config&&delete e.output_config.effort,i1(e),JSON.stringify(e)}function o1(){let t="",e=0,n=new Map,r=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return n.clear(),e=0,i;case"content_block_start":{if(r.has(a.content_block?.type))return n.set(a.index,null),null;let c=e++;return n.set(a.index,c),a.index=c,`event: ${a.type}
2082
+ `)}catch(c){console.error("[switcher] .gitignore update failed",X(c))}}function i1(t){let e=i=>{let o=i.exec(t);return o?Number(o[1]):0},n=e(/"cache_read_input_tokens":\s*(\d+)/),r=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);n>0||r>0?Ci="live":s>s1&&(Ci="uncached")}function IS(t,e){let n={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":t.headers["anthropic-version"]||"2023-06-01",...Jd},r=t.headers["anthropic-beta"];return typeof r=="string"&&(n["anthropic-beta"]=r),n}function o1(t){if(Array.isArray(t?.messages))for(let e of t.messages){if(!Array.isArray(e?.content))continue;let n=e.content.filter(r=>r?.type!=="thinking"&&r?.type!=="redacted_thinking");n.length&&n.length!==e.content.length&&(e.content=n)}}function $S(t){let e;try{e=JSON.parse(t)}catch{return t}Ti=typeof e?.model=="string"?e.model:null,pt&&(e.model=pt),Jn&&(e.provider=RS(Jn));let n=/haiku/i.test(Ti||"");return Oi!=null&&!n&&(e.reasoning={effort:bp[Oi]}),delete e.thinking,e.output_config&&delete e.output_config.effort,o1(e),JSON.stringify(e)}function a1(){let t="",e=0,n=new Map,r=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return n.clear(),e=0,i;case"content_block_start":{if(r.has(a.content_block?.type))return n.set(a.index,null),null;let c=e++;return n.set(a.index,c),a.index=c,`event: ${a.type}
2083
2083
  data: ${JSON.stringify(a)}
2084
2084
 
2085
2085
  `}case"content_block_delta":case"content_block_stop":{let c=n.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
@@ -2087,11 +2087,11 @@ data: ${JSON.stringify(a)}
2087
2087
 
2088
2088
  `)}default:return i}};return i=>{t+=i;let o="",a;for(;(a=t.indexOf(`
2089
2089
 
2090
- `))!==-1;){let c=t.slice(0,a);if(t=t.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function a1(t){return new Promise(e=>{let n=[];t.on("data",r=>n.push(r)),t.on("end",()=>e(Buffer.concat(n).toString("utf8"))),t.on("error",()=>e(Buffer.concat(n).toString("utf8")))})}function Ai(t,e,n,r){t.writableEnded||(t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify({type:"error",error:{type:n,message:r}})))}async function c1(t,e,n){if(!pt){Ai(e,400,"invalid_request_error",n1);return}let r=process.env.OPENROUTER_API_KEY;if(!r){Ai(e,401,"authentication_error","OPENROUTER_API_KEY not set in the typebulb proxy");return}let s=new AbortController;e.on("close",()=>{e.writableEnded||s.abort()});let i;try{i=await fetch(Sp,{method:"POST",headers:IS(t,r),body:$S(n),signal:s.signal})}catch(u){Ai(e,502,"api_error",`proxy upstream failed: ${X(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?o1():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});s1(p);let h=f(p);h&&e.write(h)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function l1(t,e,n){let r=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(n.length/4))}))};if(!pt||!r)return s();try{let i=await fetch(`${Sp}/count_tokens`,{method:"POST",headers:IS(t,r),body:$S(n)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function u1(t,e){let n=t.url||"/";if(t.method==="HEAD"){e.writeHead(200),e.end();return}if(t.method!=="POST"){Ai(e,404,"not_found_error",n);return}a1(t).then(r=>{if(n.includes("count_tokens"))return l1(t,e,r);if(n.includes("/v1/messages"))return c1(t,e,r);Ai(e,404,"not_found_error",n)})}function d1(){return Hr&&qn?Promise.resolve(qn):new Promise((t,e)=>{let n=Z$(u1);n.on("error",e),n.listen(0,"127.0.0.1",()=>{Hr=n,qn=n.address().port,console.log(`[switcher] wire proxy listening on ${Cc(qn)}`),t(qn)})})}function f1(){try{Hr?.close()}catch{}Hr=null,qn=null}function p1(t,e){let n=_c(t),r=rn(n),s=r||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Cc(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Rc(t);if(!rn(i)){let a={};for(let c of PS)a[c]=c in s.env?s.env[c]:null;Oc(i,{managedBy:"agent-switcher",fileExisted:r!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Cc(e),s.env.ANTHROPIC_AUTH_TOKEN=t1,Oc(n,s),_S(t,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function h1(t,e,n){let r=Rc(t),s=rn(r)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:n},Oc(r,s)}function NS(t){let e=_c(t),n=Rc(t),r=rn(n),s=rn(e);if(s?.env){let i=r?.snapshot||{};for(let o of PS){let a=i[o];a==null?delete s.env[o]:s.env[o]=a}if(Object.keys(s.env).length===0&&delete s.env,r?.fileExisted===!1&&Object.keys(s).length===0)try{TS(e,{force:!0})}catch{}else Oc(e,s)}try{TS(n,{force:!0})}catch{}}async function m1(){let t=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await vt()).filter(r=>r.provider==="openrouter"&&!kp(r.name)).map(r=>({id:r.name,label:r.friendlyName||r.name}))}catch(r){console.error("[switcher] model list failed",X(r))}let n=e.length?void 0:Fd()??void 0;return{hasKey:t,models:e,error:n}}async function g1(){if(Hr&&pt)return{active:!0,managed:!0,model:pt,port:qn,provider:Jn,routedModel:Ti,caching:Ci,reasoning:Oi,externalBaseUrl:null};let t=rn(_c(Z))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Oi,externalBaseUrl:t.ANTHROPIC_BASE_URL||null}}async function LS(t,e){let n=await d1();return pt=t,Jn=e,p1(Z,n),n}async function y1({model:t}){if(!process.env.OPENROUTER_API_KEY)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!t)return{ok:!1,error:"no model given"};if(kp(t))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await LS(t,xp[t]??null),Ti=null,Ci="unknown",h1(Z,t,Jn)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${X(e)}`}}return{ok:!0}}async function b1({level:t}){return t!=null&&(!Number.isInteger(t)||t<0||t>=bp.length)?{ok:!1,error:`reasoning level must be 0\u2013${bp.length-1} or null`}:(Oi=t,{ok:!0,level:t})}async function w1(){return NS(Z),pt=null,Jn=null,Ti=null,Ci="unknown",{ok:!0}}async function v1({key:t}){let e=(t||"").trim();if(!e)return{ok:!1,error:"empty key"};let n=Z,r=Pc(n,".env"),s="";try{s=vp(r,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))CS(r,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
2090
+ `))!==-1;){let c=t.slice(0,a);if(t=t.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function c1(t){return new Promise(e=>{let n=[];t.on("data",r=>n.push(r)),t.on("end",()=>e(Buffer.concat(n).toString("utf8"))),t.on("error",()=>e(Buffer.concat(n).toString("utf8")))})}function Ai(t,e,n,r){t.writableEnded||(t.writeHead(e,{"content-type":"application/json"}),t.end(JSON.stringify({type:"error",error:{type:n,message:r}})))}async function l1(t,e,n){if(!pt){Ai(e,400,"invalid_request_error",r1);return}let r=process.env.OPENROUTER_API_KEY;if(!r){Ai(e,401,"authentication_error","OPENROUTER_API_KEY not set in the typebulb proxy");return}let s=new AbortController;e.on("close",()=>{e.writableEnded||s.abort()});let i;try{i=await fetch(Sp,{method:"POST",headers:IS(t,r),body:$S(n),signal:s.signal})}catch(u){Ai(e,502,"api_error",`proxy upstream failed: ${X(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),c=i.body.getReader(),l=new TextDecoder,f=a?a1():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});i1(p);let h=f(p);h&&e.write(h)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function u1(t,e,n){let r=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(n.length/4))}))};if(!pt||!r)return s();try{let i=await fetch(`${Sp}/count_tokens`,{method:"POST",headers:IS(t,r),body:$S(n)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function d1(t,e){let n=t.url||"/";if(t.method==="HEAD"){e.writeHead(200),e.end();return}if(t.method!=="POST"){Ai(e,404,"not_found_error",n);return}c1(t).then(r=>{if(n.includes("count_tokens"))return u1(t,e,r);if(n.includes("/v1/messages"))return l1(t,e,r);Ai(e,404,"not_found_error",n)})}function f1(){return Hr&&qn?Promise.resolve(qn):new Promise((t,e)=>{let n=e1(d1);n.on("error",e),n.listen(0,"127.0.0.1",()=>{Hr=n,qn=n.address().port,console.log(`[switcher] wire proxy listening on ${Cc(qn)}`),t(qn)})})}function p1(){try{Hr?.close()}catch{}Hr=null,qn=null}function h1(t,e){let n=_c(t),r=rn(n),s=r||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Cc(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=Rc(t);if(!rn(i)){let a={};for(let c of PS)a[c]=c in s.env?s.env[c]:null;Oc(i,{managedBy:"agent-switcher",fileExisted:r!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Cc(e),s.env.ANTHROPIC_AUTH_TOKEN=n1,Oc(n,s),_S(t,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function m1(t,e,n){let r=Rc(t),s=rn(r)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:n},Oc(r,s)}function NS(t){let e=_c(t),n=Rc(t),r=rn(n),s=rn(e);if(s?.env){let i=r?.snapshot||{};for(let o of PS){let a=i[o];a==null?delete s.env[o]:s.env[o]=a}if(Object.keys(s.env).length===0&&delete s.env,r?.fileExisted===!1&&Object.keys(s).length===0)try{TS(e,{force:!0})}catch{}else Oc(e,s)}try{TS(n,{force:!0})}catch{}}async function g1(){let t=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await vt()).filter(r=>r.provider==="openrouter"&&!kp(r.name)).map(r=>({id:r.name,label:r.friendlyName||r.name}))}catch(r){console.error("[switcher] model list failed",X(r))}let n=e.length?void 0:Fd()??void 0;return{hasKey:t,models:e,error:n}}async function y1(){if(Hr&&pt)return{active:!0,managed:!0,model:pt,port:qn,provider:Jn,routedModel:Ti,caching:Ci,reasoning:Oi,externalBaseUrl:null};let t=rn(_c(Z))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Oi,externalBaseUrl:t.ANTHROPIC_BASE_URL||null}}async function LS(t,e){let n=await f1();return pt=t,Jn=e,h1(Z,n),n}async function b1({model:t}){if(!process.env.OPENROUTER_API_KEY)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!t)return{ok:!1,error:"no model given"};if(kp(t))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await LS(t,xp[t]??null),Ti=null,Ci="unknown",m1(Z,t,Jn)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${X(e)}`}}return{ok:!0}}async function w1({level:t}){return t!=null&&(!Number.isInteger(t)||t<0||t>=bp.length)?{ok:!1,error:`reasoning level must be 0\u2013${bp.length-1} or null`}:(Oi=t,{ok:!0,level:t})}async function v1(){return NS(Z),pt=null,Jn=null,Ti=null,Ci="unknown",{ok:!0}}async function S1({key:t}){let e=(t||"").trim();if(!e)return{ok:!1,error:"empty key"};let n=Z,r=Pc(n,".env"),s="";try{s=vp(r,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))CS(r,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
2091
2091
  `)?`
2092
2092
  `:"";OS(r,i+`OPENROUTER_API_KEY=${e}
2093
- `)}}catch(i){return{ok:!1,error:X(i)}}return process.env.OPENROUTER_API_KEY=e,_S(n,[".env"],"# secrets"),{ok:!0}}function S1(){if(!(!Hr&&!pt)){try{NS(Z)}catch{}f1()}}function k1(t,e){return MS.test(e)?"blocked by your OpenRouter data policy":t===401||t===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":t===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":t===429||/rate limit/i.test(e)?"rate limited":t===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function x1(t){if(MS.test(t))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function E1(t,e,n){if(!t)return{works:null,read:0,note:n?`couldn't re-test on ${n} \u2014 caching unconfirmed`:"caching unconfirmed"};let r=wp(e?.cache_read_input_tokens)||wp(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return r>0?{works:!0,read:r,note:`${r} tokens read from cache on the 2nd call`}:s?{works:!1,read:r,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:r,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function A1({model:t}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!t)return{ok:!1,error:"no model given"};if(kp(t))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let n=Date.now(),r=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:t,max_tokens:64,system:[{type:"text",text:r,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:RS(a)}:i),u=await fetch(Sp,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let b=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-n,error:k1(a.status,b),restriction:x1(b)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(b=>b.type==="text")?.text??c?.content?.[0]?.text??"ok",u=wp(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:h,read:m,note:g}=E1(d.ok,p?.usage,l);return h===!0&&l&&(xp[t]=l,pt===t&&(Jn=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-n,provider:l,sample:String(f).trim().slice(0,60),cache:{works:h,created:u,read:m,note:g}}}catch(a){let c=X(a);return{ok:!0,callable:!1,ms:Date.now()-n,error:/abort/i.test(c)?"timed out (20s)":c}}}var e1,Sp,t1,n1,PS,r1,bp,_c,Rc,Cc,kp,Hr,qn,pt,Jn,Ti,Ci,Oi,xp,wp,RS,MS,DS=k(()=>{"use strict";Qt();Zt();Wt();e1="https://openrouter.ai/api",Sp=`${e1}/v1/messages`,t1="typebulb-proxy-managed",n1="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",PS=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],r1=5e3,bp=["low","medium","high"],_c=t=>Pc(t,".claude","settings.local.json"),Rc=t=>Pc(t,".claude",".cc-switcher.json"),Cc=t=>`http://127.0.0.1:${t}`;kp=t=>/^anthropic\//i.test(t)||/claude/i.test(t),Hr=null,qn=null,pt=null,Jn=null,Ti=null,Ci="unknown",Oi=1,xp={},wp=t=>typeof t=="number"?t:0,RS=t=>({order:[t],allow_fallbacks:!1});MS=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=rn(Rc(Z)),n=e?.active?.model;if(!n)return;let s=(rn(_c(Z))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await LS(n,e.active.provider??xp[n]??null);console.log(`[switcher] re-adopted override after restart: ${n} via ${Cc(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",X(e))}})()});var jS={};qi(jS,{agentMessage:()=>na,answerAsk:()=>F1,attach:()=>I1,blockToMarkdown:()=>ta,board:()=>j1,breakout:()=>rp,capText:()=>Ie,childStatus:()=>B1,cleanUserText:()=>qt,clearSwitchModel:()=>w1,closeChild:()=>L1,composerPasteRead:()=>M1,displayName:()=>T1,downloadSample:()=>pp,firstLineDigest:()=>Fe,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>C1,isHiddenTurn:()=>Bs,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>$1,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>_1,listSwitchModels:()=>m1,logInlineStatus:()=>P1,openChild:()=>N1,openFile:()=>np,poll:()=>O1,predictTrustOf:()=>lp,probeModel:()=>A1,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,saveOpenRouterKey:()=>v1,searchBulbs:()=>ap,searchSessions:()=>R1,setBulbTrust:()=>up,setReasoning:()=>b1,setSwitchModel:()=>y1,shutdownSwitcher:()=>S1,stopBreakout:()=>ip,summarizeTurn:()=>D1,switchState:()=>g1,toolResultDigest:()=>ad});var BS,T1,C1,O1,P1,_1,R1,I1,$1,N1,L1,M1,D1,B1,j1,F1,FS=k(()=>{"use strict";Ec();ra();Tc();Br();DS();ra();Ms();BS=new cr,T1=BS.displayName,{info:C1,poll:O1,logInlineStatus:P1,listSessions:_1,searchSessions:R1,attach:I1,listChildren:$1,openChild:N1,closeChild:L1,composerPasteRead:M1,summarizeTurn:D1,childStatus:B1,board:j1,answerAsk:F1}=Kr(BS)});var qS={};qi(qS,{answerAsk:()=>tN,attach:()=>z1,board:()=>eN,breakout:()=>rp,childStatus:()=>Z1,closeChild:()=>G1,composerPasteRead:()=>X1,displayName:()=>U1,downloadSample:()=>pp,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>q1,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>Y1,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>K1,logInlineStatus:()=>W1,openChild:()=>V1,openFile:()=>np,poll:()=>J1,predictTrustOf:()=>lp,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,searchBulbs:()=>ap,searchSessions:()=>H1,setBulbTrust:()=>up,stopBreakout:()=>ip,summarizeTurn:()=>Q1});var US,U1,q1,J1,W1,K1,H1,z1,Y1,V1,G1,X1,Q1,Z1,eN,tN,JS=k(()=>{"use strict";Ec();gd();Tc();Br();US=new ur,U1=US.displayName,{info:q1,poll:J1,logInlineStatus:W1,listSessions:K1,searchSessions:H1,attach:z1,listChildren:Y1,openChild:V1,closeChild:G1,composerPasteRead:X1,summarizeTurn:Q1,childStatus:Z1,board:eN,answerAsk:tN}=Kr(US)});import{readFileSync as nN,writeFileSync as rN,mkdirSync as sN}from"fs";import{homedir as iN}from"os";import*as Ic from"path";async function HS(){try{let t=await fetch(new URL("/api/tags",KS()).toString(),{signal:AbortSignal.timeout(oN)});return t.ok?((await t.json()).models??[]).map(n=>n.name).filter(n=>!!n):[]}catch{return[]}}function zS(t){let e;try{e=nN(t,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n;return{json:r,unreadable:"providers"in r&&!Ep(r)}}}catch{}return{json:void 0,unreadable:!0}}function Ep(t){let e=t?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function aN(t){let e=Ep(t);if(!e||!("ollama"in e))return null;let n=e.ollama?.models;return Array.isArray(n)?n.map(r=>r?.id).filter(r=>typeof r=="string"):[]}async function YS(){let{json:t,unreadable:e}=zS(WS());return e?{installed:[],configured:null}:{installed:await HS(),configured:aN(t)}}async function VS(){let t=await HS();return t.length?cN(WS(),t,KS()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function cN(t,e,n){let{json:r,unreadable:s}=zS(t);if(s)return{ok:!1,error:`could not parse ${t} \u2014 edit the ollama provider there yourself`};let i={...r??{},providers:{...Ep(r)??{},ollama:{baseUrl:`${n}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{sN(Ic.dirname(t),{recursive:!0}),rN(t,JSON.stringify(i,null,2)+`
2094
- `)}catch(o){return{ok:!1,error:`could not write ${t}: ${X(o)}`}}return{ok:!0,count:e.length}}var oN,WS,KS,GS=k(()=>{"use strict";Zt();Qt();oN=1500,WS=()=>Ic.join(iN(),".pi","agent","models.json"),KS=()=>vr(process.env.OLLAMA_HOST??"http://localhost:11434")});var QS={};qi(QS,{answerAsk:()=>PN,attach:()=>mN,board:()=>ON,breakout:()=>rp,closeChild:()=>bN,composerFiles:()=>kN,composerNew:()=>SN,composerPaste:()=>AN,composerPasteRead:()=>TN,composerRpc:()=>EN,composerSend:()=>wN,composerStop:()=>vN,composerUiRespond:()=>xN,displayName:()=>lN,downloadSample:()=>pp,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>uN,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>gN,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>pN,logInlineStatus:()=>fN,ollamaOffer:()=>YS,ollamaSync:()=>VS,openChild:()=>yN,openFile:()=>np,poll:()=>dN,predictTrustOf:()=>lp,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,searchBulbs:()=>ap,searchSessions:()=>hN,setBulbTrust:()=>up,shutdownComposer:()=>_N,stopBreakout:()=>ip,summarizeTurn:()=>CN});var XS,lN,uN,dN,fN,pN,hN,mN,gN,yN,bN,wN,vN,SN,kN,xN,EN,AN,TN,CN,ON,PN,_N,ZS=k(()=>{"use strict";Ec();If();Tc();Br();GS();XS=new Dr,lN=XS.displayName,{info:uN,poll:dN,logInlineStatus:fN,listSessions:pN,searchSessions:hN,attach:mN,listChildren:gN,openChild:yN,closeChild:bN,composerSend:wN,composerStop:vN,composerNew:SN,composerFiles:kN,composerUiRespond:xN,composerRpc:EN,composerPaste:AN,composerPasteRead:TN,summarizeTurn:CN,board:ON,answerAsk:PN,shutdownComposer:_N}=Kr(XS)});import*as Tx from"fs/promises";import*as Pt from"path";Ji();re();function td(t){if(!Ve.includes(t))throw new Error(`Unknown block kind '${t}' (one of: ${Ve.join(", ")})`);return t}function Ny(t){let e=[];for(let n of t){let r=n.indexOf("=");if(r<=0||r===n.length-1)throw new Error(`Expected <kind>=<source>, got '${n}' (e.g. data=results.json, or data=- for stdin)`);let s=td(n.slice(0,r));if(e.some(i=>i.kind===s))throw new Error(`Duplicate block kind '${s}' \u2014 each block can be written once per invocation`);e.push({kind:s,source:n.slice(r+1)})}if(e.filter(n=>n.source==="-").length>1)throw new Error("Only one <kind>=- can read stdin");return e}ra();gd();If();var $c={claude:{adapter:()=>new cr,server:()=>Promise.resolve().then(()=>(FS(),jS))},codex:{adapter:()=>new ur,server:()=>Promise.resolve().then(()=>(JS(),qS))},pi:{adapter:()=>new Dr,server:()=>Promise.resolve().then(()=>(ZS(),QS))}};function ek(t){return t in $c}function zr(){return Object.keys($c)}function Yr(){return Object.fromEntries(Object.entries($c).map(([t,e])=>[t,e.adapter]))}function tk(t){return $c[t].server()}var Pi=Yr();function nk(){for(let t of Object.values(Pi))try{t().ensureHarnessSupport()}catch{}}function it(){for(let t of Object.keys(Pi))try{if(Pi[t]().detectsSelf())return t}catch{}}function rk(t){let e=zr(),n=new Map(e.filter(i=>Pi[i]).map(i=>[i,Pi[i]()]));for(let[i,o]of n)if(o.detectsSelf())return{name:i};let r=[...n].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(r.length===0)return{name:e[0]};if(r.length===1)return{name:r[0]};let s=i=>n.get(i).listSessionFiles(t).length>0;return{ambiguous:[...r].sort((i,o)=>Number(s(o))-Number(s(i)))}}var Tp=5e3;function Ap(t){try{return t()}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}}function RN(t){let e=/^(\d+(?:\.\d+)?)([smh]?)$/.exec(t??""),n=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,"":6e4}[e[2]]:0;return n>0?n:void 0}function sk(t){let n={subcommand:"run",file:"",watch:!0,open:process.env.TERM_PROGRAM==="vscode"||it()!==void 0?"link":"window",server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},r=["call","check","predict","logs","wait","stop","restart","trust","untrust","models","slug","send","pull","push","get","put","status","babysit"],s=t[0];if(s==="agent"||s?.startsWith("agent:")){n.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(n.agentTarget=a)}t=t.slice(1)}else s&&r.includes(s)&&(n.subcommand=s,t=t.slice(1));let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(a==="--help"||a==="-h")n.help=!0;else if(a==="--version"||a==="-V")n.version=!0;else if(a==="--no-watch")n.watch=!1;else if(a==="--open")n.open="window";else if(a==="--no-open")n.open="none";else if(a==="--server")n.server=!0;else if(a==="--trust")n.trust=!0;else if(a==="--no-trust")n.noTrust=!0;else if(a==="--force")n.force=!0;else if(a==="--mode"){let c=t[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),n.mode=c}else if(a==="--follow"||a==="-f")n.follow=!0;else if(a==="--clear")n.clear=!0;else if(a==="--run"){let c=t[++o];if(c==="latest")n.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),n.run=l}}else if(a==="--bulbs")n.stopScope="bulbs";else if(a==="--agent")n.stopScope="agent";else if(a==="--global")n.stopScope="global";else if(a==="--wake")n.wake=!0;else if(a==="--match"){let c=t[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),n.match=c}else if(a==="--timeout"){let c=parseInt(t[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${t[o]} (seconds)`),process.exit(1)),n.timeoutSec=c}else if(a==="--slow"){let c=RN(t[++o]);c===void 0&&(console.error(`Invalid --slow value: ${t[o]} (a duration, e.g. 90s, 8m, 1h)`),process.exit(1)),n.slowMs=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),n.sendWaitMs=c}else n.sendWaitMs=Tp;else if(a==="--lines"||a==="-n"){let c=parseInt(t[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${t[o]}`),process.exit(1)),n.lines=c}else if(a==="--port"||a==="-p"){let c=t[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),n.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):t[++o]??"",l=Ap(()=>Zp(c));n.local&&(console.error(`--replace can only be used once (got '${n.local.name}' and '${l.name}')`),process.exit(1)),n.local=l}else if(a==="--args"||a.startsWith("--args=")){n.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):t[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),n.argsJson=c}else if(!a.startsWith("-")||a==="-"&&n.subcommand==="send")["call","send","get","put","slug","status"].includes(n.subcommand)?i.push(a):n.file=a;else{let c=n.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}return n.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),n.file=i[0],n.fn=i[1],n.callArgs=i.slice(2)),n.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),n.file=i[0],n.sendMessage=i[1]),n.subcommand==="slug"&&(i.length||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1)),n.slugName=i.join(" ")),n.subcommand==="status"&&i.length&&(n.statusQuery=i.join(" ")),n.subcommand==="get"&&(i.length!==2&&(console.error("Usage: typebulb get <file> <kind>"),process.exit(1)),n.file=i[0],n.blockKind=Ap(()=>td(i[1]))),n.subcommand==="put"&&(i.length<2&&(console.error("Usage: typebulb put <file> <kind>=<source> [<kind>=<source> \u2026]"),process.exit(1)),n.file=i[0],n.blockPairs=Ap(()=>Ny(i.slice(1)))),n}function ik(){console.log(`
2093
+ `)}}catch(i){return{ok:!1,error:X(i)}}return process.env.OPENROUTER_API_KEY=e,_S(n,[".env"],"# secrets"),{ok:!0}}function k1(){if(!(!Hr&&!pt)){try{NS(Z)}catch{}p1()}}function x1(t,e){return MS.test(e)?"blocked by your OpenRouter data policy":t===401||t===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":t===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":t===429||/rate limit/i.test(e)?"rate limited":t===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function E1(t){if(MS.test(t))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function A1(t,e,n){if(!t)return{works:null,read:0,note:n?`couldn't re-test on ${n} \u2014 caching unconfirmed`:"caching unconfirmed"};let r=wp(e?.cache_read_input_tokens)||wp(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return r>0?{works:!0,read:r,note:`${r} tokens read from cache on the 2nd call`}:s?{works:!1,read:r,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:r,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function T1({model:t}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!t)return{ok:!1,error:"no model given"};if(kp(t))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let n=Date.now(),r=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:t,max_tokens:64,system:[{type:"text",text:r,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:RS(a)}:i),u=await fetch(Sp,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let b=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-n,error:x1(a.status,b),restriction:E1(b)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(b=>b.type==="text")?.text??c?.content?.[0]?.text??"ok",u=wp(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:h,read:m,note:g}=A1(d.ok,p?.usage,l);return h===!0&&l&&(xp[t]=l,pt===t&&(Jn=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-n,provider:l,sample:String(f).trim().slice(0,60),cache:{works:h,created:u,read:m,note:g}}}catch(a){let c=X(a);return{ok:!0,callable:!1,ms:Date.now()-n,error:/abort/i.test(c)?"timed out (20s)":c}}}var t1,Sp,n1,r1,PS,s1,bp,_c,Rc,Cc,kp,Hr,qn,pt,Jn,Ti,Ci,Oi,xp,wp,RS,MS,DS=k(()=>{"use strict";Qt();Zt();Wt();t1="https://openrouter.ai/api",Sp=`${t1}/v1/messages`,n1="typebulb-proxy-managed",r1="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",PS=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],s1=5e3,bp=["low","medium","high"],_c=t=>Pc(t,".claude","settings.local.json"),Rc=t=>Pc(t,".claude",".cc-switcher.json"),Cc=t=>`http://127.0.0.1:${t}`;kp=t=>/^anthropic\//i.test(t)||/claude/i.test(t),Hr=null,qn=null,pt=null,Jn=null,Ti=null,Ci="unknown",Oi=1,xp={},wp=t=>typeof t=="number"?t:0,RS=t=>({order:[t],allow_fallbacks:!1});MS=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=rn(Rc(Z)),n=e?.active?.model;if(!n)return;let s=(rn(_c(Z))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await LS(n,e.active.provider??xp[n]??null);console.log(`[switcher] re-adopted override after restart: ${n} via ${Cc(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",X(e))}})()});var jS={};qi(jS,{agentMessage:()=>na,answerAsk:()=>U1,attach:()=>$1,blockToMarkdown:()=>ta,board:()=>F1,breakout:()=>rp,capText:()=>Ie,childStatus:()=>j1,cleanUserText:()=>qt,clearSwitchModel:()=>v1,closeChild:()=>M1,composerPasteRead:()=>D1,displayName:()=>C1,downloadSample:()=>pp,firstLineDigest:()=>Fe,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>O1,isHiddenTurn:()=>Bs,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>N1,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>R1,listSwitchModels:()=>g1,logInlineStatus:()=>_1,openChild:()=>L1,openFile:()=>np,poll:()=>P1,predictTrustOf:()=>lp,probeModel:()=>T1,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,saveOpenRouterKey:()=>S1,searchBulbs:()=>ap,searchSessions:()=>I1,setBulbTrust:()=>up,setReasoning:()=>w1,setSwitchModel:()=>b1,shutdownSwitcher:()=>k1,stopBreakout:()=>ip,summarizeTurn:()=>B1,switchState:()=>y1,toolResultDigest:()=>ad});var BS,C1,O1,P1,_1,R1,I1,$1,N1,L1,M1,D1,B1,j1,F1,U1,FS=k(()=>{"use strict";Ec();ra();Tc();Br();DS();ra();Ms();BS=new cr,C1=BS.displayName,{info:O1,poll:P1,logInlineStatus:_1,listSessions:R1,searchSessions:I1,attach:$1,listChildren:N1,openChild:L1,closeChild:M1,composerPasteRead:D1,summarizeTurn:B1,childStatus:j1,board:F1,answerAsk:U1}=Kr(BS)});var qS={};qi(qS,{answerAsk:()=>nN,attach:()=>Y1,board:()=>tN,breakout:()=>rp,childStatus:()=>eN,closeChild:()=>X1,composerPasteRead:()=>Q1,displayName:()=>q1,downloadSample:()=>pp,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>J1,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>V1,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>H1,logInlineStatus:()=>K1,openChild:()=>G1,openFile:()=>np,poll:()=>W1,predictTrustOf:()=>lp,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,searchBulbs:()=>ap,searchSessions:()=>z1,setBulbTrust:()=>up,stopBreakout:()=>ip,summarizeTurn:()=>Z1});var US,q1,J1,W1,K1,H1,z1,Y1,V1,G1,X1,Q1,Z1,eN,tN,nN,JS=k(()=>{"use strict";Ec();gd();Tc();Br();US=new ur,q1=US.displayName,{info:J1,poll:W1,logInlineStatus:K1,listSessions:H1,searchSessions:z1,attach:Y1,listChildren:V1,openChild:G1,closeChild:X1,composerPasteRead:Q1,summarizeTurn:Z1,childStatus:eN,board:tN,answerAsk:nN}=Kr(US)});import{readFileSync as rN,writeFileSync as sN,mkdirSync as iN}from"fs";import{homedir as oN}from"os";import*as Ic from"path";async function HS(){try{let t=await fetch(new URL("/api/tags",KS()).toString(),{signal:AbortSignal.timeout(aN)});return t.ok?((await t.json()).models??[]).map(n=>n.name).filter(n=>!!n):[]}catch{return[]}}function zS(t){let e;try{e=rN(t,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let n=JSON.parse(e);if(n&&typeof n=="object"&&!Array.isArray(n)){let r=n;return{json:r,unreadable:"providers"in r&&!Ep(r)}}}catch{}return{json:void 0,unreadable:!0}}function Ep(t){let e=t?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function cN(t){let e=Ep(t);if(!e||!("ollama"in e))return null;let n=e.ollama?.models;return Array.isArray(n)?n.map(r=>r?.id).filter(r=>typeof r=="string"):[]}async function YS(){let{json:t,unreadable:e}=zS(WS());return e?{installed:[],configured:null}:{installed:await HS(),configured:cN(t)}}async function VS(){let t=await HS();return t.length?lN(WS(),t,KS()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function lN(t,e,n){let{json:r,unreadable:s}=zS(t);if(s)return{ok:!1,error:`could not parse ${t} \u2014 edit the ollama provider there yourself`};let i={...r??{},providers:{...Ep(r)??{},ollama:{baseUrl:`${n}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{iN(Ic.dirname(t),{recursive:!0}),sN(t,JSON.stringify(i,null,2)+`
2094
+ `)}catch(o){return{ok:!1,error:`could not write ${t}: ${X(o)}`}}return{ok:!0,count:e.length}}var aN,WS,KS,GS=k(()=>{"use strict";Zt();Qt();aN=1500,WS=()=>Ic.join(oN(),".pi","agent","models.json"),KS=()=>vr(process.env.OLLAMA_HOST??"http://localhost:11434")});var QS={};qi(QS,{answerAsk:()=>_N,attach:()=>gN,board:()=>PN,breakout:()=>rp,closeChild:()=>wN,composerFiles:()=>xN,composerNew:()=>kN,composerPaste:()=>TN,composerPasteRead:()=>CN,composerRpc:()=>AN,composerSend:()=>vN,composerStop:()=>SN,composerUiRespond:()=>EN,displayName:()=>uN,downloadSample:()=>pp,git:()=>Se,gitChangedFiles:()=>Nf,gitDiff:()=>Lf,info:()=>dN,launchBulb:()=>cp,listBreakouts:()=>sp,listBulbFiles:()=>op,listChildren:()=>yN,listMyBulbs:()=>mp,listSamples:()=>fp,listSessions:()=>hN,logInlineStatus:()=>pN,ollamaOffer:()=>YS,ollamaSync:()=>VS,openChild:()=>bN,openFile:()=>np,poll:()=>fN,predictTrustOf:()=>lp,pullRemoteBulb:()=>gp,pushLocalBulb:()=>yp,readBulbLog:()=>dp,repoRoot:()=>Mn,searchBulbs:()=>ap,searchSessions:()=>mN,setBulbTrust:()=>up,shutdownComposer:()=>RN,stopBreakout:()=>ip,summarizeTurn:()=>ON});var XS,uN,dN,fN,pN,hN,mN,gN,yN,bN,wN,vN,SN,kN,xN,EN,AN,TN,CN,ON,PN,_N,RN,ZS=k(()=>{"use strict";Ec();If();Tc();Br();GS();XS=new Dr,uN=XS.displayName,{info:dN,poll:fN,logInlineStatus:pN,listSessions:hN,searchSessions:mN,attach:gN,listChildren:yN,openChild:bN,closeChild:wN,composerSend:vN,composerStop:SN,composerNew:kN,composerFiles:xN,composerUiRespond:EN,composerRpc:AN,composerPaste:TN,composerPasteRead:CN,summarizeTurn:ON,board:PN,answerAsk:_N,shutdownComposer:RN}=Kr(XS)});import*as Tx from"fs/promises";import*as Pt from"path";Ji();re();function td(t){if(!Ve.includes(t))throw new Error(`Unknown block kind '${t}' (one of: ${Ve.join(", ")})`);return t}function Ny(t){let e=[];for(let n of t){let r=n.indexOf("=");if(r<=0||r===n.length-1)throw new Error(`Expected <kind>=<source>, got '${n}' (e.g. data=results.json, or data=- for stdin)`);let s=td(n.slice(0,r));if(e.some(i=>i.kind===s))throw new Error(`Duplicate block kind '${s}' \u2014 each block can be written once per invocation`);e.push({kind:s,source:n.slice(r+1)})}if(e.filter(n=>n.source==="-").length>1)throw new Error("Only one <kind>=- can read stdin");return e}ra();gd();If();var $c={claude:{adapter:()=>new cr,server:()=>Promise.resolve().then(()=>(FS(),jS))},codex:{adapter:()=>new ur,server:()=>Promise.resolve().then(()=>(JS(),qS))},pi:{adapter:()=>new Dr,server:()=>Promise.resolve().then(()=>(ZS(),QS))}};function ek(t){return t in $c}function zr(){return Object.keys($c)}function Yr(){return Object.fromEntries(Object.entries($c).map(([t,e])=>[t,e.adapter]))}function tk(t){return $c[t].server()}var Pi=Yr();function nk(){for(let t of Object.values(Pi))try{t().ensureHarnessSupport()}catch{}}function it(){for(let t of Object.keys(Pi))try{if(Pi[t]().detectsSelf())return t}catch{}}function rk(t){let e=zr(),n=new Map(e.filter(i=>Pi[i]).map(i=>[i,Pi[i]()]));for(let[i,o]of n)if(o.detectsSelf())return{name:i};let r=[...n].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(r.length===0)return{name:e[0]};if(r.length===1)return{name:r[0]};let s=i=>n.get(i).listSessionFiles(t).length>0;return{ambiguous:[...r].sort((i,o)=>Number(s(o))-Number(s(i)))}}var Tp=5e3;function Ap(t){try{return t()}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}}function IN(t){let e=/^(\d+(?:\.\d+)?)([smh]?)$/.exec(t??""),n=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,"":6e4}[e[2]]:0;return n>0?n:void 0}function sk(t){let n={subcommand:"run",file:"",watch:!0,open:process.env.TERM_PROGRAM==="vscode"||it()!==void 0?"link":"window",server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},r=["call","check","predict","logs","wait","stop","restart","trust","untrust","models","slug","send","pull","push","get","put","status","babysit"],s=t[0];if(s==="agent"||s?.startsWith("agent:")){n.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(n.agentTarget=a)}t=t.slice(1)}else s&&r.includes(s)&&(n.subcommand=s,t=t.slice(1));let i=[];for(let o=0;o<t.length;o++){let a=t[o];if(a==="--help"||a==="-h")n.help=!0;else if(a==="--version"||a==="-V")n.version=!0;else if(a==="--no-watch")n.watch=!1;else if(a==="--open")n.open="window";else if(a==="--no-open")n.open="none";else if(a==="--server")n.server=!0;else if(a==="--trust")n.trust=!0;else if(a==="--no-trust")n.noTrust=!0;else if(a==="--force")n.force=!0;else if(a==="--mode"){let c=t[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),n.mode=c}else if(a==="--follow"||a==="-f")n.follow=!0;else if(a==="--clear")n.clear=!0;else if(a==="--run"){let c=t[++o];if(c==="latest")n.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),n.run=l}}else if(a==="--bulbs")n.stopScope="bulbs";else if(a==="--agent")n.stopScope="agent";else if(a==="--global")n.stopScope="global";else if(a==="--wake")n.wake=!0;else if(a==="--match"){let c=t[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),n.match=c}else if(a==="--timeout"){let c=parseInt(t[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${t[o]} (seconds)`),process.exit(1)),n.timeoutSec=c}else if(a==="--slow"){let c=IN(t[++o]);c===void 0&&(console.error(`Invalid --slow value: ${t[o]} (a duration, e.g. 90s, 8m, 1h)`),process.exit(1)),n.slowMs=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),n.sendWaitMs=c}else n.sendWaitMs=Tp;else if(a==="--lines"||a==="-n"){let c=parseInt(t[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${t[o]}`),process.exit(1)),n.lines=c}else if(a==="--port"||a==="-p"){let c=t[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),n.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):t[++o]??"",l=Ap(()=>Zp(c));n.local&&(console.error(`--replace can only be used once (got '${n.local.name}' and '${l.name}')`),process.exit(1)),n.local=l}else if(a==="--args"||a.startsWith("--args=")){n.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):t[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),n.argsJson=c}else if(!a.startsWith("-")||a==="-"&&n.subcommand==="send")["call","send","get","put","slug","status"].includes(n.subcommand)?i.push(a):n.file=a;else{let c=n.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),process.exit(1)}}return n.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),n.file=i[0],n.fn=i[1],n.callArgs=i.slice(2)),n.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),n.file=i[0],n.sendMessage=i[1]),n.subcommand==="slug"&&(i.length||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1)),n.slugName=i.join(" ")),n.subcommand==="status"&&i.length&&(n.statusQuery=i.join(" ")),n.subcommand==="get"&&(i.length!==2&&(console.error("Usage: typebulb get <file> <kind>"),process.exit(1)),n.file=i[0],n.blockKind=Ap(()=>td(i[1]))),n.subcommand==="put"&&(i.length<2&&(console.error("Usage: typebulb put <file> <kind>=<source> [<kind>=<source> \u2026]"),process.exit(1)),n.file=i[0],n.blockPairs=Ap(()=>Ny(i.slice(1)))),n}function ik(){console.log(`
2095
2095
  typebulb - Local bulb runner for Typebulb
2096
2096
 
2097
2097
  Usage:
@@ -2285,7 +2285,7 @@ Examples:
2285
2285
  typebulb my-editor.bulb.md
2286
2286
  typebulb --no-watch my-editor.bulb.md
2287
2287
  typebulb .
2288
- `)}Tt();zs();Ji();Gs();Tt();import*as He from"path";import{spawn as iL,execSync as oL}from"child_process";import{createRequire as aL}from"module";import{existsSync as cL}from"fs";import*as Ae from"fs/promises";import*as ke from"path";var Cp=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],Op=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Pp(t,e){if(!e)return t.filter(s=>!s.since);let n={"5.0":0,"5.5":1},r=n[e];return t.filter(s=>!s.since||n[s.since]<=r)}re();var IN=`
2288
+ `)}Tt();zs();Ji();Gs();Tt();import*as He from"path";import{spawn as oL,execSync as aL}from"child_process";import{createRequire as cL}from"module";import{existsSync as lL}from"fs";import*as Ae from"fs/promises";import*as ke from"path";var Cp=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],Op=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function Pp(t,e){if(!e)return t.filter(s=>!s.since);let n={"5.0":0,"5.5":1},r=n[e];return t.filter(s=>!s.since||n[s.since]<=r)}re();var $N=`
2289
2289
  /**
2290
2290
  * Get raw data chunk from the Data tab.
2291
2291
  * @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
@@ -2296,7 +2296,7 @@ Examples:
2296
2296
  * @param index - Chunk index (0-based)
2297
2297
  * @throws If chunk is not valid JSON/JSON-ish
2298
2298
  */
2299
- json<T = unknown>(index: number): T;`,$N=`
2299
+ json<T = unknown>(index: number): T;`,NN=`
2300
2300
  /**
2301
2301
  * Get the insight data produced by the inference layer.
2302
2302
  *
@@ -2305,7 +2305,7 @@ Examples:
2305
2305
  *
2306
2306
  * @returns The parsed insight JSON, or undefined if no insight is available
2307
2307
  */
2308
- insight<T = unknown>(): T | undefined;`,NN=`
2308
+ insight<T = unknown>(): T | undefined;`,LN=`
2309
2309
  /**
2310
2310
  * Replace the data this run is working on.
2311
2311
  *
@@ -2412,7 +2412,7 @@ type AiAccess = "own" | "courtesy" | "none";
2412
2412
  * \`tb.mode\` or the length of \`tb.models()\` \u2014 which hosts offer a courtesy
2413
2413
  * model is the host's business and changes without your bulb changing.
2414
2414
  */
2415
- aiAccess(): Promise<AiAccess>;`,LN="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",dk=`
2415
+ aiAccess(): Promise<AiAccess>;`,MN="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",dk=`
2416
2416
  /**
2417
2417
  * The mode this bulb is running in.
2418
2418
  *
@@ -2451,7 +2451,7 @@ type AiAccess = "own" | "courtesy" | "none";
2451
2451
  * \`tb.fs\` already resolves relative paths against it, so bulb code writing
2452
2452
  * its own files never needs it. CLI only \u2014 throws in ide/published/inline mode.
2453
2453
  */
2454
- readonly dir: string;`,MN=`
2454
+ readonly dir: string;`,DN=`
2455
2455
  /**
2456
2456
  * Async value inspector for tensor-like objects.
2457
2457
  *
@@ -2504,14 +2504,14 @@ type AiAccess = "own" | "courtesy" | "none";
2504
2504
  *
2505
2505
  * @returns The full canonical URL
2506
2506
  */
2507
- url(): Promise<string>;`,DN="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an inline bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",BN="\n /**\n * Print to the CLI's stdout \u2014 the bulb's log channel, read back with `typebulb logs <file>`.\n *\n * Ungated: needs no `server.ts` block and no `--trust`, so a Restricted client-only bulb can\n * instrument itself. Args cross to the CLI as JSON; where no CLI serves the page (web, inline,\n * or a transport failure) it falls back to the browser console. Works in `server.ts` too (same\n * as `console.log` there).\n */\n log(...args: any[]): void;",jN="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",_p=`${ak}${ck}
2507
+ url(): Promise<string>;`,BN="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an inline bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",jN="\n /**\n * Print to the CLI's stdout \u2014 the bulb's log channel, read back with `typebulb logs <file>`.\n *\n * Ungated: needs no `server.ts` block and no `--trust`, so a Restricted client-only bulb can\n * instrument itself. Args cross to the CLI as JSON; where no CLI serves the page (web, inline,\n * or a transport failure) it falls back to the browser console. Works in `server.ts` too (same\n * as `console.log` there).\n */\n log(...args: any[]): void;",FN="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",_p=`${ak}${ck}
2508
2508
  /**
2509
2509
  * Typebulb utilities namespace.
2510
2510
  * Type \`tb.\` to discover available helpers.
2511
2511
  */
2512
- declare const tb: {${IN}${MN}${$N}${NN}${BN}${jN}${DN}${lk}${fk}${pk}${uk}${LN}${dk}
2512
+ declare const tb: {${$N}${DN}${NN}${LN}${jN}${FN}${BN}${lk}${fk}${pk}${uk}${MN}${dk}
2513
2513
  };
2514
- `,FN=`
2514
+ `,UN=`
2515
2515
  /**
2516
2516
  * Print to the CLI's stdout \u2014 the same channel as \`console.log\` here (the server's console IS
2517
2517
  * the bulb's log). One log verb across blocks: page-side \`tb.log\` reaches this same stdout.
@@ -2521,33 +2521,33 @@ declare const tb: {${IN}${MN}${$N}${NN}${BN}${jN}${DN}${lk}${fk}${pk}${uk}${LN}$
2521
2521
  * Typebulb utilities namespace (server-side).
2522
2522
  * Type \`tb.\` to discover available helpers.
2523
2523
  */
2524
- declare const tb: {${FN}${lk}${fk}${pk}${uk}${dk}
2524
+ declare const tb: {${UN}${lk}${fk}${pk}${uk}${dk}
2525
2525
  };
2526
- `;kt();import WN from"p-limit";kt();import{resolve as mk}from"resolve.exports";var Ct={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},_i=["index.d.ts","index.d.mts"],Ip=/\.d\.(ts|mts|cts)$/i;function Nc(t){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(t)||/[?&]dts(?:[&#]|$)/i.test(t)}function hk(t){return[`${t}.d.ts`,`${t}.d.mts`]}function sn(t){if(!t||t==="./"||t==="/")return[..._i];let e=t.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=hk(e),r=e.endsWith("/")?e:`${e}/`;return n.push(...hk(`${r}index`)),n}async function Vr(t,{retries:e=2,timeoutMs:n=15e3,init:r}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),n);try{let a=await fetch(t,{...r,signal:i.signal});if(UN(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function UN(t){return t===408||t===429||t>=500&&t<600}var Lc=class{constructor(e,n){this.fetchDts=e,this.cdnClient=n}async tryUrls(e){for(let n of e){let r=await this.fetchDts(n);if(r&&(this.looksLikeDts(r.dts)||Nc(r.url)))return r}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,n){let r=this.cdnClient.packageJson(new U({name:e,version:n})),s=await Vr(r);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new U({name:e,version:n??i.version})),version:n}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(n=>typeof n=="string")}async tryUntilSuccess(e,n){for(let r of e){let s=await n(r);if(s)return s}}async resolveFromSelected(e,n,r){if(e.kind==="types"){let o=Rn(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([..._i],n);if(!Ip.test(o)){let a=await this.tryUntilSuccess(sn(o),n);if(a)return a}return n(o)}let s=sn(e.path),i=r?.subpath?[...s,..._i]:[..._i,...s];return this.tryUntilSuccess(i,n)}toResolutionResult(e){return{kind:Ip.test(e)?"types":"probe",path:e}}resolveExportsPath(e,n){let r=n||".",s=e;try{let i=this.extractPathFromResult(mk(s,r,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(mk(s,r,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let n=U.parse(e),{pkg:r,baseDir:s}=await this.loadPackageAtVersionedRoot(n.name,n.version)||{};if(!r||!s)return;let i={name:n.name,version:n.version},o=new U(i).format(),a=new U({...i,subpath:n.subpath}).format(),c=u=>this.fetchCandidateFrom(s,n.name,u);if(n.subpath){let u=af(n.subpath),d=this.resolveExportsPath(r,u);if(d){let h=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(h)return{...h,resolvedPkg:a}}let p=await this.tryUntilSuccess(sn(u),c);if(p)return{...p,resolvedPkg:a}}let l=r.types??r.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(r,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,n,r){let s=Rn(r),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:n}:void 0}};kt();import{gunzipSync as qN}from"fflate";var Mc=class{async fetchAndExtract(e,n){let r=this.getTarballUrl(e,n),s=await Vr(r,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,n){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${n}.tgz`}normalizeTarPath(e){let n=e.replace(/^package\//,""),r=n.indexOf("/");return r>0?n.substring(r+1):n}extractDtsFiles(e){let n=new Map;try{let r=qN(e),s=new TextDecoder("utf-8"),i=0;for(;i<r.length-512;){let o=r.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let h=r.slice(i,i+d);n.set(this.normalizeTarPath(l),s.decode(h))}i+=Math.ceil(d/512)*512}}catch{}return n}};var Dc=class{constructor(e,n,r=new Mc){this.cdnClient=e,this.cache=n,this.tarballFetcher=r}typesNameCandidates(e){let n=e.startsWith("@")?e.slice(1).replace("/","__"):e;return n.includes(".")?[n,n.split(".").join("-"),n.split(".").join("")]:[n]}selectTypesVersion(e,n,r){try{if(r){let i=In.majorOf(r),o=e.filter(a=>In.majorOf(a)===i);if(o.length)return o.sort((a,c)=>In.cmp(c,a))[0]}let s=n?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let n=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),r=sn(e);return n!==e&&r.push(`${e}.d.ts`,`${e}/index.d.ts`),r}async fetchFromVersionedRoot(e,n){let r=new U(e),s=r.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(r.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=n.subpath?this.subpathCandidates(n.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:n.subpath?new U(n).format():n.name}}}async resolve(e){let n=U.parse(e);if(n.name)for(let r of this.typesNameCandidates(n.name)){let s=`@types/${r}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,n.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,n);if(a)return a}}};var Bc=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(n=>n.startsWith("./")||n.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(n=>this.isBare(n))}collectRefs(e){let n=e.split(`
2526
+ `;kt();import KN from"p-limit";kt();import{resolve as mk}from"resolve.exports";var Ct={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},_i=["index.d.ts","index.d.mts"],Ip=/\.d\.(ts|mts|cts)$/i;function Nc(t){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(t)||/[?&]dts(?:[&#]|$)/i.test(t)}function hk(t){return[`${t}.d.ts`,`${t}.d.mts`]}function sn(t){if(!t||t==="./"||t==="/")return[..._i];let e=t.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),n=hk(e),r=e.endsWith("/")?e:`${e}/`;return n.push(...hk(`${r}index`)),n}async function Vr(t,{retries:e=2,timeoutMs:n=15e3,init:r}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),n);try{let a=await fetch(t,{...r,signal:i.signal});if(qN(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function qN(t){return t===408||t===429||t>=500&&t<600}var Lc=class{constructor(e,n){this.fetchDts=e,this.cdnClient=n}async tryUrls(e){for(let n of e){let r=await this.fetchDts(n);if(r&&(this.looksLikeDts(r.dts)||Nc(r.url)))return r}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,n){let r=this.cdnClient.packageJson(new U({name:e,version:n})),s=await Vr(r);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new U({name:e,version:n??i.version})),version:n}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(n=>typeof n=="string")}async tryUntilSuccess(e,n){for(let r of e){let s=await n(r);if(s)return s}}async resolveFromSelected(e,n,r){if(e.kind==="types"){let o=Rn(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([..._i],n);if(!Ip.test(o)){let a=await this.tryUntilSuccess(sn(o),n);if(a)return a}return n(o)}let s=sn(e.path),i=r?.subpath?[...s,..._i]:[..._i,...s];return this.tryUntilSuccess(i,n)}toResolutionResult(e){return{kind:Ip.test(e)?"types":"probe",path:e}}resolveExportsPath(e,n){let r=n||".",s=e;try{let i=this.extractPathFromResult(mk(s,r,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(mk(s,r,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let n=U.parse(e),{pkg:r,baseDir:s}=await this.loadPackageAtVersionedRoot(n.name,n.version)||{};if(!r||!s)return;let i={name:n.name,version:n.version},o=new U(i).format(),a=new U({...i,subpath:n.subpath}).format(),c=u=>this.fetchCandidateFrom(s,n.name,u);if(n.subpath){let u=af(n.subpath),d=this.resolveExportsPath(r,u);if(d){let h=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(h)return{...h,resolvedPkg:a}}let p=await this.tryUntilSuccess(sn(u),c);if(p)return{...p,resolvedPkg:a}}let l=r.types??r.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(r,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,n,r){let s=Rn(r),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:n}:void 0}};kt();import{gunzipSync as JN}from"fflate";var Mc=class{async fetchAndExtract(e,n){let r=this.getTarballUrl(e,n),s=await Vr(r,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,n){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${n}.tgz`}normalizeTarPath(e){let n=e.replace(/^package\//,""),r=n.indexOf("/");return r>0?n.substring(r+1):n}extractDtsFiles(e){let n=new Map;try{let r=JN(e),s=new TextDecoder("utf-8"),i=0;for(;i<r.length-512;){let o=r.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let h=r.slice(i,i+d);n.set(this.normalizeTarPath(l),s.decode(h))}i+=Math.ceil(d/512)*512}}catch{}return n}};var Dc=class{constructor(e,n,r=new Mc){this.cdnClient=e,this.cache=n,this.tarballFetcher=r}typesNameCandidates(e){let n=e.startsWith("@")?e.slice(1).replace("/","__"):e;return n.includes(".")?[n,n.split(".").join("-"),n.split(".").join("")]:[n]}selectTypesVersion(e,n,r){try{if(r){let i=In.majorOf(r),o=e.filter(a=>In.majorOf(a)===i);if(o.length)return o.sort((a,c)=>In.cmp(c,a))[0]}let s=n?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let n=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),r=sn(e);return n!==e&&r.push(`${e}.d.ts`,`${e}/index.d.ts`),r}async fetchFromVersionedRoot(e,n){let r=new U(e),s=r.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(r.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=n.subpath?this.subpathCandidates(n.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:n.subpath?new U(n).format():n.name}}}async resolve(e){let n=U.parse(e);if(n.name)for(let r of this.typesNameCandidates(n.name)){let s=`@types/${r}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,n.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,n);if(a)return a}}};var Bc=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(n=>n.startsWith("./")||n.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(n=>this.isBare(n))}collectRefs(e){let n=e.split(`
2527
2527
  `).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
2528
- `),r=new Set;for(let s of n.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))r.add(s[2]);for(let s of n.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))r.add(s[1]);return Array.from(r)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};kt();var gk="file:///node_modules",jc=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${gk}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,n){let r=Rn(n);return`${gk}/${this.epochDir()}/${e}/${r}`}};import{LRUCache as JN}from"lru-cache";function yk(t){let e=new JN({ttl:Ct.negativeTtlMs,max:500}),n=new Map;return async function(s){try{if(await t.isNegative(s)||e.has(s))return;let i=await t.getCachedFile(s);if(i)return{dts:i,url:s};let o=n.get(s);if(o)return o;let a=(async()=>{let c=await Vr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await t.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await t.clearNegative(s),await t.setCachedFile(f,l),{dts:l,url:f}})();return n.set(s,a),await a.finally(()=>n.delete(s))}catch{return}}}var Ri=class{constructor(e){this.inFlight=new Map,this.scanner=new Bc,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=yk(e.cache),this.typescriptProvider=new Lc(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Dc(e.cdnClient,e.cache),this.virtualFs=new jc}withInFlight(e,n){let r=this.inFlight.get(e);if(r)return r;let s=n().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,n,r){e.some(s=>s.path===n)||e.push({path:n,content:r})}createStubDef(e){let n=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:n,files:[{path:n,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:n}]}}async fetchViaProviders(e){for(let n of[this.typescriptProvider,this.definitelyTypedProvider])try{let r=await n.resolve(e);if(r?.dts)return r}catch{}}async fetchRootDts(e,n){let{effectivePackage:r,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,n),o=await this.cache.getCachedDts(r);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:r}}let a;try{a=await this.fetchViaProviders(r)}catch{return}if(!(!a?.dts||!a.url)&&new U(r).subpath===new U(a.resolvedPkg||r).subpath){try{await this.cache.setCachedDts(r,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let n=e.pathname.match(/^(.+@[^/]+\/)/);return n?new URL(n[1],e.origin):new URL("./",e)}toVirtualPath(e,n,r){let s=n.pathname.startsWith(e.pathname)?n.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(n.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(r,s)}computeEntryPath(e,n){if(!e)return{mainPath:this.virtualFs.pathForMain(n),packageRootUrl:void 0};let r=new URL(e),s=this.extractPackageRootUrl(r);return{mainPath:this.toVirtualPath(s,r,n),packageRootUrl:s}}async expandRelativeRefs(e,n,r,s,i=new Set,o){if(!i.has(n)&&(i.add(n),!(i.size>Ct.maxRelativeTypeRefs)))try{let a=new URL(n),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ct.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,r,s,i)}catch{}}async tryRelativeRef(e,n,r,s,i,o){try{let a=new URL(e,n),c=a.pathname+a.search,l=Nc(c)?[c]:sn(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let h=this.toVirtualPath(r,new URL(p.url),s);this.pushFileIfNew(i,h,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,r);return}}}catch{}}isDifferentPackage(e,n){return e===n?!1:new U(e).name!==new U(n).name}ambientlyDeclares(e,n){if(/^(?:import|export)\b/m.test(e))return!1;for(let r of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=r[1];if(s===n||s.endsWith("/*")&&n.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,n){let r=e.find(s=>s.path===n);r&&(r.ambient=!0)}async prefetchBareDeps(e,n,r,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Ct.maxBareDeps).filter(l=>this.isDifferentPackage(l,n));if(!o.length)return;let a=new Set([n]),c=WN(Ct.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,r,s,Ct.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,n,r,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(n,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(n,l):r.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,n);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ct.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,n,r,s-1,i,o)}async resolve(e,n,r){let s=await this.packageService.extractImports(e),i=r?[...s,...r]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,n)))).filter(a=>!!a)}async resolveOne(e,n){let{effectivePackage:r}=await this.versionResolver.effectivePackage(e,n);return this.withInFlight(r,async()=>{let s=new U(e),i=await this.fetchRootDts(e,n)??(s.subpath?await this.fetchRootDts(s.name,n):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,n):this.createStubDef(e)})}async buildDefFromContent(e,n,r,s){let{dts:i,url:o,resolvedPkg:a}=n,c=new U(a||r),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let h=d.map(C=>C.content).join(`
2529
- `);await this.prefetchBareDeps(h,l,d,p,s);let m=c.format(),g=e===m?[e]:[e,m],b=g.some(C=>this.ambientlyDeclares(i,C));return b?this.markFileAmbient(d,f):p.push(...g.map(C=>({module:C,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:b}}};yf();kt();Pr();ui();mf();Or();import*as Gr from"path";var KN=Gr.join(Ba,"pkg"),HN=Gr.join(Ba,"files"),zN=Gr.join(Ba,"negative.json"),Uc=class{pkgMem=new Map;fileMem=new Map;negativeCache=new $n(new _r(zN));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await se();let n=await xt(bk(e));return this.pkgMem.set(e,n),n}async setCachedDts(e,n,r){let s={content:n,url:r};this.pkgMem.set(e,s),await Fc(async()=>{await se(),await qe(bk(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await se();let n=await Da(wk(e));return this.fileMem.set(e,n),n}async setCachedFile(e,n){this.fileMem.set(e,n),await Fc(async()=>{await se(),await qe(wk(e),n)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Fc(async()=>{await se(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Fc(()=>this.negativeCache.clearNegative(e))}};async function Fc(t){try{await t()}catch{}}function bk(t){return Gr.join(KN,nt(t)+".json")}function wk(t){return Gr.join(HN,nt(t)+".txt")}Pr();var $p;function YN(){return $p||($p=new Ri({cache:new Uc,cdnClient:Uw,packageService:qa,versionResolver:Fw})),$p}var vk="file:///node_modules/";async function Sk(t){let e=ja(t.emitKey,"typecheck");await se(),await Ae.rm(e,{recursive:!0,force:!0}),await Ae.mkdir(e,{recursive:!0});let n=QN(t.jsxImportSource,t.dependencies),r=await YN().resolve(t.code,t.dependencies,n),s=t.local?.name,i=s?r.filter(f=>f.pkg!==s):r,o=new Set;for(let f of i)for(let u of f.files){let d=qc(u.path);if(!d||o.has(d))continue;o.add(d);let p=ke.join(e,"node_modules",d);await Ae.mkdir(ke.dirname(p),{recursive:!0}),await Ae.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=qc(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=qc(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=qc(u.path);d&&c.add(`node_modules/${d}`)}if(t.local){delete a[t.local.name];let f=await ZN(t.local,e);f?a[t.local.name]=[`./node_modules/${t.local.name}/${f}`]:console.warn(` local: '${t.local.name}' ships no type defs; check cannot type against it.`)}let l=VN(t.jsxImportSource,a,[...c]);return await Ae.writeFile(ke.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
2530
- `,"utf8"),await Ae.writeFile(ke.join(e,"code.tsx"),t.code,"utf8"),await Ae.writeFile(ke.join(e,"tb.d.ts"),_p,"utf8"),{dir:e}}var Np={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function VN(t,e,n=[]){return{compilerOptions:{...Np,lib:GN([...Cp,...Op]),jsx:"react-jsx",jsxImportSource:t??"react",paths:e},include:["code.tsx","tb.d.ts",...n]}}function GN(t){return Pp(t).map(e=>XN(e.name))}function XN(t){return t.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function QN(t,e){let n=t??("react"in e?"react":void 0);return n?[`${n}/jsx-runtime`,`${n}/jsx-dev-runtime`]:[]}function qc(t){if(!t.startsWith(vk))return;let e=t.slice(vk.length),n=e.indexOf("/");if(!(n<0))return e.slice(n+1)}async function ZN(t,e){if(!t.typesAbs)return;let n=ke.dirname(t.typesAbs),r=ke.join(e,"node_modules",t.name);for(let s of await eL(n)){let i=ke.join(r,ke.relative(n,s));await Ae.mkdir(ke.dirname(i),{recursive:!0}),await Ae.copyFile(s,i)}return ke.basename(t.typesAbs)}async function eL(t){let e=[];async function n(r){let s=await Ae.readdir(r,{withFileTypes:!0});for(let i of s){let o=ke.join(r,i.name);i.isDirectory()?await n(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await n(t),e}import*as Ke from"fs/promises";import*as Ot from"path";import{existsSync as tL}from"fs";Pr();wf();var nL="^22";async function kk(t){let e=ja(t.emitKey,"typecheck-server");await se(),await Ke.rm(e,{recursive:!0,force:!0}),await Ke.mkdir(e,{recursive:!0});let n=Ot.join(t.bulbDir,".typebulb"),r=Va(t.server).filter(o=>o!==t.local?.name);await Ya([`@types/node@${nL}`,...r],n,t.dependencies,{ignoreScripts:!0});let s=Ot.join(n,"node_modules"),i=Ot.join(e,"node_modules");return await sL(s,i),await Ke.writeFile(Ot.join(e,"server.ts"),t.server,"utf8"),await Ke.writeFile(Ot.join(e,"tb.d.ts"),Rp,"utf8"),await Ke.writeFile(Ot.join(e,"tsconfig.json"),JSON.stringify(rL(t.local),null,2)+`
2531
- `,"utf8"),{dir:e}}function rL(t){let e={...Np,lib:["ES2023"],types:["node"]};if(t?.typesAbs){let n=i=>i.replace(/\\/g,"/"),r=n(Ot.dirname(t.typesAbs)),s=n(t.typesAbs).replace(/\.d\.ts$/,"");e.paths={[t.name]:[s],[`${t.name}/*`]:[`${r}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function sL(t,e){if(!tL(t)){await Ke.mkdir(e,{recursive:!0});return}await Ke.rm(e,{recursive:!0,force:!0});let n=process.platform==="win32"?"junction":"dir";await Ke.symlink(t,e,n)}xa();re();async function Ek(t,e){let{bulb:n,config:r,warnings:s,starts:i}=await st(t),o=He.basename(t),a=m=>i.get(m)??1;!n.code&&!n.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let c=!1,l=!1;for(let m of s)console.log(`structure ${m}`);s.length&&(c=!0);let f=Nr(He.resolve(t)),u=f?sr(n.name):"";f&&u&&u!==f.slug&&(console.log(`naming filename '${f.slug}.bulb.md' doesn't match the title '${n.name}' \u2014 its slug derives to '${u}'. Rename the file to '${u}.bulb.md', or change name: to suit the filename.`),l=!0),n.code&&(c=xk(Ys(n.code,{target:"client",dependencies:r.dependencies??{},lineOffset:a("code.tsx")}),"client")||c),n.server&&(c=xk(Ys(n.server,{target:"server",lineOffset:a("server.ts")}),"server")||c);let d=fL([process.cwd(),He.dirname(t)]);if(!d){let m=He.relative(process.cwd(),t)||t;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${m}`),process.exit(2)}let p=[];if(n.code){let{dir:m}=await Sk({code:n.code,dependencies:r.dependencies??{},jsxImportSource:r.ts?.jsxImportSource,emitKey:t,local:e});p.push({role:"client",dir:m})}if(n.server){let{dir:m}=await kk({server:n.server,bulbDir:He.dirname(t),emitKey:t,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:r.dependencies});p.push({role:"server",dir:m})}for(let{role:m,dir:g}of p){let{stdout:b,exitCode:C}=await uL(d,g);for(let T of b.split(/\r?\n/))T.trim()&&console.log(`${m} ${lL(T,o,a)}`);C!==0&&(c=!0)}c&&process.exit(1);let h=[n.code&&"code.tsx",n.server&&"server.ts"].filter(Boolean).join(", ");console.error(l?`\u2713 type-checks (${h}) \u2014 see the naming warning above`:`\u2713 no issues (${h})`)}function xk(t,e){for(let n of t)for(let r of n.message.split(`
2532
- `))console.log(`${e} ${r}`);return t.length>0}function lL(t,e,n){return t.replace(/\b(code\.tsx|server\.ts)\((\d+),(\d+)\)/g,(r,s,i,o)=>`${e}(${Number(i)+n(s)-1},${o})`)}function uL(t,e){return new Promise(n=>{let r=iL(process.execPath,[t,"--noEmit"],{cwd:e}),s="";r.stdout?.on("data",i=>{s+=i.toString()}),r.stderr?.on("data",i=>{s+=i.toString()}),r.on("close",i=>n({stdout:s,exitCode:i??1}))})}var dL=aL(import.meta.url);function fL(t){let e=r=>{try{let s=dL.resolve("typescript/package.json",{paths:r}),i=He.join(He.dirname(s),"lib","tsc.js");return cL(i)?i:void 0}catch{return}},n=e(t);if(n)return n;try{let r=oL("npm root -g",{encoding:"utf8"}).trim();return e([r])}catch{return}}Tt();ka();Gs();async function Ak(t,e){let{bulb:n}=await st(t),r=yr(n);if(Tn(t)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),r&&console.log(` (it uses ${r})`);return}r?(console.log(`This bulb appears to use ${r}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}Gs();import*as Ii from"path";async function Tk(t,e){if(!t){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let r=jd();if(!r.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of r)console.log(` ${s}`);return}let n=Ii.resolve(t);n.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));try{br(n,e)}catch(r){console.error(r.message),process.exit(1)}console.log(e?`Trusted ${Ii.basename(n)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Ii.basename(n)} \u2014 runs Restricted.`),console.log(` ${n}`)}$e();import*as Pk from"readline";rf();function Lp(t){let e=n=>r=>t?`\x1B[${n}m${r}\x1B[0m`:r;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}var pL=5e3,Jc=()=>Math.round(performance.now()),Ck=t=>t>=1e3?`${(t/1e3).toFixed(1)}s`:`${t}ms`;async function _k(t){let e=rk(process.cwd()),n=Jc();if("ambiguous"in e){let r=await hL(t,e.ambiguous);return r?Ok(t,r,{boot:n,from:Jc()}):mL(t,e.ambiguous)}return Ok(t,e.name,{boot:n,from:Jc()})}async function Ok(t,e,n){let r,s;try{r=await Hs(e)}catch(p){s=p instanceof Error?p.message:String(p)}let i=Jc()-n.from,{lit:o,litLink:a,brand:c}=Lp(process.stdout.isTTY===!0),l=[" Read the authoring skill before writing a bulb:",` \u2022 ${o(ei())}`],f=r?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${o("\u25CF")} ${a(r.url)}`," Inline bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${o(".bulb.md")}`," Show something inline \u2192 emit an inline bulb"," emit it with no .bulb.md draft first",...e==="codex"?[" verify it this turn \u2014 foreground-wait, bounded:",` \u2022 ${o('typebulb wait agent --match "[inline <name>" --timeout 120')}`," via exec_command; while it still runs,"," poll it with write_stdin until it exits"]:[e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${o('typebulb wait agent --match "[inline <name>"')}`],...l," End this reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${s})`,` \u25CF Start it manually: ${o(`npx typebulb agent:${e}`)}`," Agents:",...l],u=n.boot+i>pL?[` slow launch: boot ${Ck(n.boot)} \xB7 mirror ${Ck(i)}`]:[],d=[` ${c(`typebulb v${t}`)}`,...u,...f,""];process.stdout.write(d.join(`
2528
+ `),r=new Set;for(let s of n.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))r.add(s[2]);for(let s of n.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))r.add(s[1]);return Array.from(r)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};kt();var gk="file:///node_modules",jc=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${gk}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,n){let r=Rn(n);return`${gk}/${this.epochDir()}/${e}/${r}`}};import{LRUCache as WN}from"lru-cache";function yk(t){let e=new WN({ttl:Ct.negativeTtlMs,max:500}),n=new Map;return async function(s){try{if(await t.isNegative(s)||e.has(s))return;let i=await t.getCachedFile(s);if(i)return{dts:i,url:s};let o=n.get(s);if(o)return o;let a=(async()=>{let c=await Vr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await t.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await t.clearNegative(s),await t.setCachedFile(f,l),{dts:l,url:f}})();return n.set(s,a),await a.finally(()=>n.delete(s))}catch{return}}}var Ri=class{constructor(e){this.inFlight=new Map,this.scanner=new Bc,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=yk(e.cache),this.typescriptProvider=new Lc(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new Dc(e.cdnClient,e.cache),this.virtualFs=new jc}withInFlight(e,n){let r=this.inFlight.get(e);if(r)return r;let s=n().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,n,r){e.some(s=>s.path===n)||e.push({path:n,content:r})}createStubDef(e){let n=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:n,files:[{path:n,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:n}]}}async fetchViaProviders(e){for(let n of[this.typescriptProvider,this.definitelyTypedProvider])try{let r=await n.resolve(e);if(r?.dts)return r}catch{}}async fetchRootDts(e,n){let{effectivePackage:r,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,n),o=await this.cache.getCachedDts(r);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:r}}let a;try{a=await this.fetchViaProviders(r)}catch{return}if(!(!a?.dts||!a.url)&&new U(r).subpath===new U(a.resolvedPkg||r).subpath){try{await this.cache.setCachedDts(r,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let n=e.pathname.match(/^(.+@[^/]+\/)/);return n?new URL(n[1],e.origin):new URL("./",e)}toVirtualPath(e,n,r){let s=n.pathname.startsWith(e.pathname)?n.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(n.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(r,s)}computeEntryPath(e,n){if(!e)return{mainPath:this.virtualFs.pathForMain(n),packageRootUrl:void 0};let r=new URL(e),s=this.extractPackageRootUrl(r);return{mainPath:this.toVirtualPath(s,r,n),packageRootUrl:s}}async expandRelativeRefs(e,n,r,s,i=new Set,o){if(!i.has(n)&&(i.add(n),!(i.size>Ct.maxRelativeTypeRefs)))try{let a=new URL(n),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,Ct.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,r,s,i)}catch{}}async tryRelativeRef(e,n,r,s,i,o){try{let a=new URL(e,n),c=a.pathname+a.search,l=Nc(c)?[c]:sn(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let h=this.toVirtualPath(r,new URL(p.url),s);this.pushFileIfNew(i,h,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,r);return}}}catch{}}isDifferentPackage(e,n){return e===n?!1:new U(e).name!==new U(n).name}ambientlyDeclares(e,n){if(/^(?:import|export)\b/m.test(e))return!1;for(let r of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=r[1];if(s===n||s.endsWith("/*")&&n.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,n){let r=e.find(s=>s.path===n);r&&(r.ambient=!0)}async prefetchBareDeps(e,n,r,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,Ct.maxBareDeps).filter(l=>this.isDifferentPackage(l,n));if(!o.length)return;let a=new Set([n]),c=KN(Ct.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,r,s,Ct.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,n,r,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(n,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(n,l):r.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,n);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,Ct.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,n,r,s-1,i,o)}async resolve(e,n,r){let s=await this.packageService.extractImports(e),i=r?[...s,...r]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,n)))).filter(a=>!!a)}async resolveOne(e,n){let{effectivePackage:r}=await this.versionResolver.effectivePackage(e,n);return this.withInFlight(r,async()=>{let s=new U(e),i=await this.fetchRootDts(e,n)??(s.subpath?await this.fetchRootDts(s.name,n):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,n):this.createStubDef(e)})}async buildDefFromContent(e,n,r,s){let{dts:i,url:o,resolvedPkg:a}=n,c=new U(a||r),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let h=d.map(C=>C.content).join(`
2529
+ `);await this.prefetchBareDeps(h,l,d,p,s);let m=c.format(),g=e===m?[e]:[e,m],b=g.some(C=>this.ambientlyDeclares(i,C));return b?this.markFileAmbient(d,f):p.push(...g.map(C=>({module:C,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:b}}};yf();kt();Pr();ui();mf();Or();import*as Gr from"path";var HN=Gr.join(Ba,"pkg"),zN=Gr.join(Ba,"files"),YN=Gr.join(Ba,"negative.json"),Uc=class{pkgMem=new Map;fileMem=new Map;negativeCache=new $n(new _r(YN));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await se();let n=await xt(bk(e));return this.pkgMem.set(e,n),n}async setCachedDts(e,n,r){let s={content:n,url:r};this.pkgMem.set(e,s),await Fc(async()=>{await se(),await qe(bk(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await se();let n=await Da(wk(e));return this.fileMem.set(e,n),n}async setCachedFile(e,n){this.fileMem.set(e,n),await Fc(async()=>{await se(),await qe(wk(e),n)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Fc(async()=>{await se(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Fc(()=>this.negativeCache.clearNegative(e))}};async function Fc(t){try{await t()}catch{}}function bk(t){return Gr.join(HN,nt(t)+".json")}function wk(t){return Gr.join(zN,nt(t)+".txt")}Pr();var $p;function VN(){return $p||($p=new Ri({cache:new Uc,cdnClient:Uw,packageService:qa,versionResolver:Fw})),$p}var vk="file:///node_modules/";async function Sk(t){let e=ja(t.emitKey,"typecheck");await se(),await Ae.rm(e,{recursive:!0,force:!0}),await Ae.mkdir(e,{recursive:!0});let n=ZN(t.jsxImportSource,t.dependencies),r=await VN().resolve(t.code,t.dependencies,n),s=t.local?.name,i=s?r.filter(f=>f.pkg!==s):r,o=new Set;for(let f of i)for(let u of f.files){let d=qc(u.path);if(!d||o.has(d))continue;o.add(d);let p=ke.join(e,"node_modules",d);await Ae.mkdir(ke.dirname(p),{recursive:!0}),await Ae.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=qc(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=qc(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=qc(u.path);d&&c.add(`node_modules/${d}`)}if(t.local){delete a[t.local.name];let f=await eL(t.local,e);f?a[t.local.name]=[`./node_modules/${t.local.name}/${f}`]:console.warn(` local: '${t.local.name}' ships no type defs; check cannot type against it.`)}let l=GN(t.jsxImportSource,a,[...c]);return await Ae.writeFile(ke.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
2530
+ `,"utf8"),await Ae.writeFile(ke.join(e,"code.tsx"),t.code,"utf8"),await Ae.writeFile(ke.join(e,"tb.d.ts"),_p,"utf8"),{dir:e}}var Np={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function GN(t,e,n=[]){return{compilerOptions:{...Np,lib:XN([...Cp,...Op]),jsx:"react-jsx",jsxImportSource:t??"react",paths:e},include:["code.tsx","tb.d.ts",...n]}}function XN(t){return Pp(t).map(e=>QN(e.name))}function QN(t){return t.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function ZN(t,e){let n=t??("react"in e?"react":void 0);return n?[`${n}/jsx-runtime`,`${n}/jsx-dev-runtime`]:[]}function qc(t){if(!t.startsWith(vk))return;let e=t.slice(vk.length),n=e.indexOf("/");if(!(n<0))return e.slice(n+1)}async function eL(t,e){if(!t.typesAbs)return;let n=ke.dirname(t.typesAbs),r=ke.join(e,"node_modules",t.name);for(let s of await tL(n)){let i=ke.join(r,ke.relative(n,s));await Ae.mkdir(ke.dirname(i),{recursive:!0}),await Ae.copyFile(s,i)}return ke.basename(t.typesAbs)}async function tL(t){let e=[];async function n(r){let s=await Ae.readdir(r,{withFileTypes:!0});for(let i of s){let o=ke.join(r,i.name);i.isDirectory()?await n(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await n(t),e}import*as Ke from"fs/promises";import*as Ot from"path";import{existsSync as nL}from"fs";Pr();wf();var rL="^22";async function kk(t){let e=ja(t.emitKey,"typecheck-server");await se(),await Ke.rm(e,{recursive:!0,force:!0}),await Ke.mkdir(e,{recursive:!0});let n=Ot.join(t.bulbDir,".typebulb"),r=Va(t.server).filter(o=>o!==t.local?.name);await Ya([`@types/node@${rL}`,...r],n,t.dependencies,{ignoreScripts:!0});let s=Ot.join(n,"node_modules"),i=Ot.join(e,"node_modules");return await iL(s,i),await Ke.writeFile(Ot.join(e,"server.ts"),t.server,"utf8"),await Ke.writeFile(Ot.join(e,"tb.d.ts"),Rp,"utf8"),await Ke.writeFile(Ot.join(e,"tsconfig.json"),JSON.stringify(sL(t.local),null,2)+`
2531
+ `,"utf8"),{dir:e}}function sL(t){let e={...Np,lib:["ES2023"],types:["node"]};if(t?.typesAbs){let n=i=>i.replace(/\\/g,"/"),r=n(Ot.dirname(t.typesAbs)),s=n(t.typesAbs).replace(/\.d\.ts$/,"");e.paths={[t.name]:[s],[`${t.name}/*`]:[`${r}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function iL(t,e){if(!nL(t)){await Ke.mkdir(e,{recursive:!0});return}await Ke.rm(e,{recursive:!0,force:!0});let n=process.platform==="win32"?"junction":"dir";await Ke.symlink(t,e,n)}xa();re();async function Ek(t,e){let{bulb:n,config:r,warnings:s,starts:i}=await st(t),o=He.basename(t),a=m=>i.get(m)??1;!n.code&&!n.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let c=!1,l=!1;for(let m of s)console.log(`structure ${m}`);s.length&&(c=!0);let f=Nr(He.resolve(t)),u=f?sr(n.name):"";f&&u&&u!==f.slug&&(console.log(`naming filename '${f.slug}.bulb.md' doesn't match the title '${n.name}' \u2014 its slug derives to '${u}'. Rename the file to '${u}.bulb.md', or change name: to suit the filename.`),l=!0),n.code&&(c=xk(Ys(n.code,{target:"client",dependencies:r.dependencies??{},lineOffset:a("code.tsx")}),"client")||c),n.server&&(c=xk(Ys(n.server,{target:"server",lineOffset:a("server.ts")}),"server")||c);let d=pL([process.cwd(),He.dirname(t)]);if(!d){let m=He.relative(process.cwd(),t)||t;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${m}`),process.exit(2)}let p=[];if(n.code){let{dir:m}=await Sk({code:n.code,dependencies:r.dependencies??{},jsxImportSource:r.ts?.jsxImportSource,emitKey:t,local:e});p.push({role:"client",dir:m})}if(n.server){let{dir:m}=await kk({server:n.server,bulbDir:He.dirname(t),emitKey:t,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:r.dependencies});p.push({role:"server",dir:m})}for(let{role:m,dir:g}of p){let{stdout:b,exitCode:C}=await dL(d,g);for(let T of b.split(/\r?\n/))T.trim()&&console.log(`${m} ${uL(T,o,a)}`);C!==0&&(c=!0)}c&&process.exit(1);let h=[n.code&&"code.tsx",n.server&&"server.ts"].filter(Boolean).join(", ");console.error(l?`\u2713 type-checks (${h}) \u2014 see the naming warning above`:`\u2713 no issues (${h})`)}function xk(t,e){for(let n of t)for(let r of n.message.split(`
2532
+ `))console.log(`${e} ${r}`);return t.length>0}function uL(t,e,n){return t.replace(/\b(code\.tsx|server\.ts)\((\d+),(\d+)\)/g,(r,s,i,o)=>`${e}(${Number(i)+n(s)-1},${o})`)}function dL(t,e){return new Promise(n=>{let r=oL(process.execPath,[t,"--noEmit"],{cwd:e}),s="";r.stdout?.on("data",i=>{s+=i.toString()}),r.stderr?.on("data",i=>{s+=i.toString()}),r.on("close",i=>n({stdout:s,exitCode:i??1}))})}var fL=cL(import.meta.url);function pL(t){let e=r=>{try{let s=fL.resolve("typescript/package.json",{paths:r}),i=He.join(He.dirname(s),"lib","tsc.js");return lL(i)?i:void 0}catch{return}},n=e(t);if(n)return n;try{let r=aL("npm root -g",{encoding:"utf8"}).trim();return e([r])}catch{return}}Tt();ka();Gs();async function Ak(t,e){let{bulb:n}=await st(t),r=yr(n);if(Tn(t)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),r&&console.log(` (it uses ${r})`);return}r?(console.log(`This bulb appears to use ${r}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}Gs();import*as Ii from"path";async function Tk(t,e){if(!t){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let r=jd();if(!r.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of r)console.log(` ${s}`);return}let n=Ii.resolve(t);n.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));try{br(n,e)}catch(r){console.error(r.message),process.exit(1)}console.log(e?`Trusted ${Ii.basename(n)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Ii.basename(n)} \u2014 runs Restricted.`),console.log(` ${n}`)}$e();import*as Pk from"readline";rf();function Lp(t){let e=n=>r=>t?`\x1B[${n}m${r}\x1B[0m`:r;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}var hL=5e3,Jc=()=>Math.round(performance.now()),Ck=t=>t>=1e3?`${(t/1e3).toFixed(1)}s`:`${t}ms`;async function _k(t){let e=rk(process.cwd()),n=Jc();if("ambiguous"in e){let r=await mL(t,e.ambiguous);return r?Ok(t,r,{boot:n,from:Jc()}):gL(t,e.ambiguous)}return Ok(t,e.name,{boot:n,from:Jc()})}async function Ok(t,e,n){let r,s;try{r=await Hs(e)}catch(p){s=p instanceof Error?p.message:String(p)}let i=Jc()-n.from,{lit:o,litLink:a,brand:c}=Lp(process.stdout.isTTY===!0),l=[" Read the authoring skill before writing a bulb:",` \u2022 ${o(ei())}`],f=r?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${o("\u25CF")} ${a(r.url)}`," Inline bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${o(".bulb.md")}`," Show something inline \u2192 emit an inline bulb"," emit it with no .bulb.md draft first",...e==="codex"?[" verify it this turn \u2014 foreground-wait, bounded:",` \u2022 ${o('typebulb wait agent --match "[inline <name>" --timeout 120')}`," via exec_command; while it still runs,"," poll it with write_stdin until it exits"]:[e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${o('typebulb wait agent --match "[inline <name>"')}`],...l," End this reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${s})`,` \u25CF Start it manually: ${o(`npx typebulb agent:${e}`)}`," Agents:",...l],u=n.boot+i>hL?[` slow launch: boot ${Ck(n.boot)} \xB7 mirror ${Ck(i)}`]:[],d=[` ${c(`typebulb v${t}`)}`,...u,...f,""];process.stdout.write(d.join(`
2533
2533
  `)+`
2534
- `)}async function hL(t,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:n,brand:r}=Lp(!0),s=[` ${r(`typebulb v${t}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${n(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
2534
+ `)}async function mL(t,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:n,brand:r}=Lp(!0),s=[` ${r(`typebulb v${t}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${n(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
2535
2535
  `)+`
2536
- `);let i=Pk.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function mL(t,e){let{lit:n,brand:r}=Lp(process.stdout.isTTY===!0),s=[` ${r(`typebulb v${t}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${n(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
2536
+ `);let i=Pk.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function gL(t,e){let{lit:n,brand:r}=Lp(process.stdout.isTTY===!0),s=[` ${r(`typebulb v${t}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${n(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
2537
2537
  `)+`
2538
- `)}tt();Cn();async function Rk(t){ve(t);let e=await vt();if(e.length>0){console.log(ow(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Ud()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[n,r]of Object.entries(wr))console.log(` ${r.padEnd(20)} (${n})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}re();function Ik(t){t?.trim()||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1));let e=sr(t);e||(console.error(`'${t}' has no slug \u2014 a bulb name needs at least one letter or digit.`),process.exit(1)),console.log(e)}Ue();import*as Lk from"path";import{valid as Nk,lt as yL}from"semver";$e();var ot={connected:"[page] connected",disconnected:"[page] disconnected",closed:t=>`[page] closed: ${t}`},Mp=3e3,$k=1e4,gL=2500,Wc=class{attached=new Set;leaving=new Set;arrivalWaiters=new Set;goneWaiters=new Set;arrivalSubs=[];settledEmpty;dropAt=0;get count(){return this.attached.size}get lastDropAt(){return this.dropAt}[Symbol.iterator](){return this.attached[Symbol.iterator]()}add(e,n){this.attached.add(e);for(let s of[...this.arrivalWaiters])s(!0);let r={page:e,firstAttach:n,count:this.attached.size};for(let s of this.arrivalSubs)s(r)}closing(e){this.attached.delete(e)&&this.leaving.add(e)}dropped(e){if(this.leaving.delete(e)){this.drainIfGone();return}if(!this.attached.delete(e))return;let n=this.dropAt=Date.now();setTimeout(()=>{this.attached.size===0&&this.dropAt===n&&this.settledEmpty?.()},Mp).unref()}async closeAll(e){let n=[...this.attached];if(!n.length)return{told:0,gone:0};await Promise.all(n.map(s=>s.close(e).catch(()=>{}))),await this.whenGone(n,gL);let r=n.filter(s=>!this.leaving.has(s)).length;for(let s of n)this.leaving.delete(s);return{told:n.length,gone:r}}whenArrives(e){return this.attached.size>0?Promise.resolve(!0):e>0?new Promise(n=>{let r=i=>{clearTimeout(s),this.arrivalWaiters.delete(r),n(i)},s=setTimeout(()=>r(!1),e);s.unref(),this.arrivalWaiters.add(r)}):Promise.resolve(!1)}onArrival(e){this.arrivalSubs.push(e)}onSettledEmpty(e){this.settledEmpty=e}whenGone(e,n){return e.some(r=>this.leaving.has(r))?new Promise(r=>{let s=()=>{e.some(o=>this.leaving.has(o))||(clearTimeout(i),this.goneWaiters.delete(s),r())},i=setTimeout(()=>{this.goneWaiters.delete(s),r()},n);i.unref(),this.goneWaiters.add(s)}):Promise.resolve()}drainIfGone(){for(let e of[...this.goneWaiters])e()}};ha();function bL(t,e,n,r){if(/^\d+$/.test(e))return t.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?t.filter(we):t.filter(i=>i.agent===e);if(s.length){if(!n)return s[0];let i=s.filter(o=>hr(o,n));return r&&i.find(o=>o.agent===r)||i[0]}return t.find(i=>ae(i.file)===ae(e))}var on=t=>t.agent??Lk.basename(t.file);function Mk(t){return t===Pe?!1:t&&Nk(t)&&Nk(Pe)?yL(t,Pe):!0}function wL(t){return t===Pe?"":t?Mk(t)?` STALE runtime v${t} (this CLI is v${Pe} \u2014 relaunch to update)`:` runtime v${t} (newer than this CLI's v${Pe})`:" STALE runtime (predates the version stamp \u2014 relaunch to update)"}function vL(t,e){return e===void 0?" pages ?":e>0?` ${e} page${e===1?"":"s"}`:we(t)?" NO PAGE (no tab open on it)":" NO PAGE (nothing of it is running)"}function Dk(t,e,n){t.forEach((r,s)=>e(` ${r.url} pid ${r.pid} ${r.trust?"trusted":"restricted"}${n?vL(r,n[s]):""}${wL(r.version)} ${r.file}`))}async function Bp(t,e){if(!t.length){console.log("No running bulb servers.");return}let n=await Promise.all(t.map(_d));console.log("Running bulb servers:"),Dk(t,r=>console.log(r),n),console.log(`
2539
- `+e)}function Kc(t,e,n,r,s){let i=bL(t,e,r,s);if(i)return i;console.error(`No running server for '${e}'.`),t.length?(console.error(`Running servers (try \`typebulb ${n} <file|pid>\`):`),Dk(t,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Bk(t,e){if(!t){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),await Bp(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let n=Kc(await Q(),t,"logs",process.cwd(),it());if(e.clear){xd(n.pid),console.log(`Cleared log for ${on(n)} (pid ${n.pid}).`);return}let r=Ze(n.pid),s=r.text;if(e.run!==void 0?(s=Ad(s,e.run),s||console.error(e.run==="latest"?"No output in the latest run yet (the server has logged nothing since its last reload).":`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)):!s&&!e.follow&&console.error("Log is empty \u2014 this server has logged nothing yet."),e.lines&&e.lines>0){let i=s.split(`
2538
+ `)}tt();Cn();async function Rk(t){ve(t);let e=await vt();if(e.length>0){console.log(ow(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Ud()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[n,r]of Object.entries(wr))console.log(` ${r.padEnd(20)} (${n})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}re();function Ik(t){t?.trim()||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1));let e=sr(t);e||(console.error(`'${t}' has no slug \u2014 a bulb name needs at least one letter or digit.`),process.exit(1)),console.log(e)}Ue();import*as Lk from"path";import{valid as Nk,lt as bL}from"semver";$e();var ot={connected:"[page] connected",disconnected:"[page] disconnected",closed:t=>`[page] closed: ${t}`},Mp=3e3,$k=1e4,yL=2500,Wc=class{attached=new Set;leaving=new Set;arrivalWaiters=new Set;goneWaiters=new Set;arrivalSubs=[];settledEmpty;dropAt=0;get count(){return this.attached.size}get lastDropAt(){return this.dropAt}[Symbol.iterator](){return this.attached[Symbol.iterator]()}add(e,n){this.attached.add(e);for(let s of[...this.arrivalWaiters])s(!0);let r={page:e,firstAttach:n,count:this.attached.size};for(let s of this.arrivalSubs)s(r)}closing(e){this.attached.delete(e)&&this.leaving.add(e)}dropped(e){if(this.leaving.delete(e)){this.drainIfGone();return}if(!this.attached.delete(e))return;let n=this.dropAt=Date.now();setTimeout(()=>{this.attached.size===0&&this.dropAt===n&&this.settledEmpty?.()},Mp).unref()}async closeAll(e){let n=[...this.attached];if(!n.length)return{told:0,gone:0};await Promise.all(n.map(s=>s.close(e).catch(()=>{}))),await this.whenGone(n,yL);let r=n.filter(s=>!this.leaving.has(s)).length;for(let s of n)this.leaving.delete(s);return{told:n.length,gone:r}}whenArrives(e){return this.attached.size>0?Promise.resolve(!0):e>0?new Promise(n=>{let r=i=>{clearTimeout(s),this.arrivalWaiters.delete(r),n(i)},s=setTimeout(()=>r(!1),e);s.unref(),this.arrivalWaiters.add(r)}):Promise.resolve(!1)}onArrival(e){this.arrivalSubs.push(e)}onSettledEmpty(e){this.settledEmpty=e}whenGone(e,n){return e.some(r=>this.leaving.has(r))?new Promise(r=>{let s=()=>{e.some(o=>this.leaving.has(o))||(clearTimeout(i),this.goneWaiters.delete(s),r())},i=setTimeout(()=>{this.goneWaiters.delete(s),r()},n);i.unref(),this.goneWaiters.add(s)}):Promise.resolve()}drainIfGone(){for(let e of[...this.goneWaiters])e()}};ha();function wL(t,e,n,r){if(/^\d+$/.test(e))return t.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?t.filter(we):t.filter(i=>i.agent===e);if(s.length){if(!n)return s[0];let i=s.filter(o=>hr(o,n));return r&&i.find(o=>o.agent===r)||i[0]}return t.find(i=>ae(i.file)===ae(e))}var on=t=>t.agent??Lk.basename(t.file);function Mk(t){return t===Pe?!1:t&&Nk(t)&&Nk(Pe)?bL(t,Pe):!0}function vL(t){return t===Pe?"":t?Mk(t)?` STALE runtime v${t} (this CLI is v${Pe} \u2014 relaunch to update)`:` runtime v${t} (newer than this CLI's v${Pe})`:" STALE runtime (predates the version stamp \u2014 relaunch to update)"}function SL(t,e){return e===void 0?" pages ?":e>0?` ${e} page${e===1?"":"s"}`:we(t)?" NO PAGE (no tab open on it)":" NO PAGE (nothing of it is running)"}function Dk(t,e,n){t.forEach((r,s)=>e(` ${r.url} pid ${r.pid} ${r.trust?"trusted":"restricted"}${n?SL(r,n[s]):""}${vL(r.version)} ${r.file}`))}async function Bp(t,e){if(!t.length){console.log("No running bulb servers.");return}let n=await Promise.all(t.map(_d));console.log("Running bulb servers:"),Dk(t,r=>console.log(r),n),console.log(`
2539
+ `+e)}function Kc(t,e,n,r,s){let i=wL(t,e,r,s);if(i)return i;console.error(`No running server for '${e}'.`),t.length?(console.error(`Running servers (try \`typebulb ${n} <file|pid>\`):`),Dk(t,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Bk(t,e){if(!t){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),await Bp(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let n=Kc(await Q(),t,"logs",process.cwd(),it());if(e.clear){xd(n.pid),console.log(`Cleared log for ${on(n)} (pid ${n.pid}).`);return}let r=Ze(n.pid),s=r.text;if(e.run!==void 0?(s=Ad(s,e.run),s||console.error(e.run==="latest"?"No output in the latest run yet (the server has logged nothing since its last reload).":`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)):!s&&!e.follow&&console.error("Log is empty \u2014 this server has logged nothing yet."),e.lines&&e.lines>0){let i=s.split(`
2540
2540
  `);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
2541
2541
  `)}if(process.stdout.write(s),s&&!s.endsWith(`
2542
2542
  `)&&process.stdout.write(`
2543
- `),e.follow&&e.run===void 0){let i=r.offset,o=setInterval(()=>{let c=Ze(n.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var SL=t=>new Promise(e=>setTimeout(e,t));async function jk(t,e){if(!t){Bp(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let n=Kc(await Q(),t,"wait",process.cwd(),it()),r=e.wake?await kL():void 0,s=process.env.TYPEBULB_WAIT_SHIM==="1",i=process.env.TYPEBULB_WAIT_FOLLOW==="1",o=s||i,a=e.timeoutSec??1800,c=e.match??"",l=Ze(n.pid).offset,f=i?void 0:ga(n.pid,c)??(c?ga(n.pid):void 0),u=i?l:f!==void 0&&f<=l?f:c?0:l,d=Date.now()+a*1e3,p=we(n)?1e4:1e3,h=2e3,m=!we(n)&&!i,g,b="",C=[],T="",E=0,R=!1;for(;;){let O=u>=l,_=Ze(n.pid,u);if(u=_.offset,_.text){b+=_.text;let x=b.split(`
2544
- `);b=x.pop()??"";let M=!1;for(let F of x)F.trim()&&(m&&O&&F.startsWith(ot.disconnected)&&(M=!0),!(e.match&&!F.includes(e.match))&&(console.log(F),C.push(F),!i&&(g??=Date.now()+p,we(n)&&(F.includes("] compile error")||F.includes("] runtime error"))&&(g=Math.min(g,Date.now()+h)))));if(M&&!g){T=`the last page of ${on(n)} closed while waiting \u2014 a bulb runs in its page, so nothing can log ${e.match?`'${e.match}'`:"anything"} now`,console.error(T),E=3;break}}if(g&&Date.now()>=g)break;if(!o&&!g&&Date.now()>=d){T=`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${on(n)} within ${a}s`,console.error(T),E=2;break}if(!Jt(n.pid)){g||(T=`server ${on(n)} (pid ${n.pid}) exited while waiting`,console.error(T),E=3,R=!0);break}await SL(400)}if(r){console.error(`detected ${new Date().toISOString()}`);try{await r.adapter.wake(r.sessionId,"typebulb_wait",C.length?C.join(`
2545
- `):T)}catch(O){console.error(`Not delivered: ${O instanceof Error?O.message:O}`),process.exit(4)}console.error(`accepted ${new Date().toISOString()}`)}R&&process.exit(3),i||Ws(n.pid,u,c),process.exit(E)}async function kL(){let t=it(),e=t?Yr()[t]?.():void 0,n=e?.wake?e.callerSessionId?.(process.cwd()):void 0;(!e||!n)&&(console.error(e?.wake?"Can't --wake: your own session couldn't be identified in this project, and a wake goes to no other.":`--wake needs a harness that wakes through its host (here: ${t??"none detected"}); on Claude Code, a background wait already wakes you.`),process.exit(1));let r=await e.wakeRoute(n);return r.error&&(console.error(`Can't --wake: ${r.error}.`),process.exit(1)),{adapter:e,sessionId:n}}function Fk(t,e){if(e==="killed")return` \u2014 forced (${Mk(t.version)?`its runtime ${t.version?`v${t.version} `:""}predates the stop route`:"it did not answer"}); a page it opened may still be open`;let n=[];return e.closed&&n.push(`closed ${e.closed} page${e.closed===1?"":"s"}`),e.stuck&&n.push(`${e.stuck} did not close`),n.length?` \u2014 ${n.join(", ")}`:""}async function Uk(t){if(!t){await Bp(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Kc(await Q(),t,"stop",process.cwd(),it()),n=await wt(e);console.log(`Stopped ${on(e)} (pid ${e.pid}, ${e.url}).${Fk(e,n)}`)}async function qk(t){let e=await Dp(t),n=t==="global"?"server":t==="agent"?"mirror":"bulb";if(!e.length){console.log(t==="global"?"No running bulb servers.":`No running ${n}s for this project.`);return}let r=await Promise.all(e.map(s=>wt(s)));console.log(`Stopped ${e.length} ${n}${e.length===1?"":"s"}:`),e.forEach((s,i)=>console.log(` ${s.url} pid ${s.pid} ${on(s)}${Fk(s,r[i])}`))}async function Dp(t){let e=process.cwd(),n=t==="agent"?it():void 0;return t==="global"?await Q():t==="bulbs"?await Q(e):(await Q()).filter(r=>hr(r,e)&&(!n||r.agent===n))}async function Jk(t,e){let n=process.cwd(),r=t?[Kc(await Q(),t,"restart",n,it())]:e?await Dp(e):[...await Q(n),...await Dp("agent")];if(!r.length){console.log(e==="global"?"No running bulb servers.":"No running bulbs or mirrors for this project.");return}console.log(`Restarting on v${Pe}:`);for(let s of r){let i=s.version?`v${s.version}`:"unknown version";try{let o=we(s)?(await wt(s,"keep"),await Hs(s.agent,s.cwd??n)):await xn(s.file,{cwd:s.cwd??n,open:!1,trust:s.trust,noTrust:!s.trust,mode:s.mode,watch:s.watch,replace:s.replace});console.log(` ${o.url} ${on(s)} ${i} \u2192 v${Pe}`)}catch(o){console.log(` ${s.url} ${on(s)} failed: ${o instanceof Error?o.message:o}`),process.exitCode=1}}}$e();Ue();vn();import*as Hc from"path";import*as Wk from"http";import{mkdir as xL,writeFile as EL}from"fs/promises";async function Xr(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}function $i(t){return(t.charCodeAt(0)===65279?t.slice(1):t).replace(/\r\n/g,`
2546
- `).trimEnd()}function AL(t,e){return new Promise((n,r)=>{let s=new URL(t),i=Wk.request({hostname:s.hostname,port:s.port,path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(e)}},o=>{let a="";o.setEncoding("utf8"),o.on("data",c=>{a+=c}),o.on("end",()=>n({status:o.statusCode??0,text:a}))});i.setTimeout(0),i.on("error",r),i.end(e)})}var TL=t=>{let e=Math.round((Date.now()-t)/6e4);return e<1?"moments ago":e<60?`${e}m ago`:`${Math.round(e/60)}h ago`};async function Kk(t,e,n=0){e==="-"&&(e=$i(await Xr()));let r=e!==void 0&&e.startsWith("tb:");r&&n<=0&&(n=Tp);let s=e!==void 0&&/^tb:(click|set)( |$)/.test(e),i=Hc.resolve(t),o=kn(await Q(),i)[0];if(!o){let h=(await wn(process.cwd()))(i);console.error(h?`No running server for '${t}' \u2014 it last ran ${TL(h)}. Relaunching reuses the same URL (a stale tab is one reload from live): npx typebulb ${t}`:`No running server for '${t}'. Start it first: npx typebulb ${t}`),process.exit(1)}let a=async h=>{let m=[h>0?`reply=${h}`:"",s?"solo=1":"","open=1"].filter(Boolean).join("&"),g=await AL(`${o.url}/__send${m?`?${m}`:""}`,e??"");(g.status<200||g.status>=300)&&(console.error(`send failed: HTTP ${g.status} from ${o.url}/__send`),process.exit(1));try{return JSON.parse(g.text)}catch{return{}}},c={},l=Date.now();try{c=await a(n)}catch(h){console.error(`send failed: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let f=c.clients??0,u=`${f} page${f===1?"":"s"}`;if(c.refused&&(console.error(`Actuation needs exactly one connected page; ${u} are open on ${o.url} \u2014 the reset is \`typebulb stop ${t}\` then relaunch.`),process.exit(1)),f===0){let h=c.droppedMsAgo,m=c.opening==="none"?" and no agent mirror page is open to open one through":"",g=c.opening==="unreached"?` \u2014 the page was opened ${c.via?`in VS Code via ${c.via}`:"in your browser"} and never attached; is the browser it opened in still there?`:h!==void 0?` \u2014 a page disconnected ${Math.round(h/1e3)}s ago and hasn't reconnected${m}; reload it, or open ${o.url}`:` \u2014 no page has ever connected${m}; share ${o.url} and arm: typebulb wait ${t} --match "${ot.connected}"`;console.error(`No page connected after ${((Date.now()-l)/1e3).toFixed(1)}s, so nothing was delivered${g}`),process.exit(1)}c.opening==="editor"?console.error(`Opened in VS Code via ${c.via}.`):c.opening==="external"&&console.error("Opened in your browser, where the agent mirror is."),console.error(`Sent to ${u}.`);let d=c.results??[],p=c.errors??[];for(let h of p)console.error(`handler error: ${h}`);if(p.length&&process.exit(1),d.length>1&&(console.error(`${d.length} replies from ${u} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),d.length===1){if(e!==void 0&&/^tb:png( |$)/.test(e)){let m={};try{m=JSON.parse(d[0])}catch{}typeof m.png!="string"&&(console.error("tb:png replied with an unexpected shape \u2014 an older runtime? (`typebulb logs` lists server versions)"),process.exit(1));let g=Eb(i);await xL(Hc.dirname(g),{recursive:!0}),await EL(g,Buffer.from(m.png,"base64"));let b=[m.via?`inside "${m.via}"`:"",m.backdrop?`backdrop ${m.backdrop}`:""].filter(Boolean);console.error(`canvas ${m.width}\xD7${m.height} \u2192 PNG${b.length?` (${b.join("; ")})`:""}`),console.log(g);return}let h;try{h=JSON.parse(d[0])}catch{h=void 0}console.log(typeof h=="string"?h:d[0])}else c.timedOut&&(r&&(console.error(`No reply to '${e}' within ${n/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${n/1e3}s \u2014 slow work needs a larger --wait=ms; a reply that NEVER comes is a done-promise that missed an exit, or a blocked main thread: tb:snapshot runs no page code, so its silence too means blocked)`))}rc();Of();re();import*as Hk from"fs/promises";async function zk(t,e){let n=await Hk.readFile(t,"utf-8"),r=Hn(n),s=pe[e].path,i=r.files.get(s);i||(console.error(i===void 0?`No **${s}** block in ${t}`:`The **${s}** block in ${t} is empty`),process.exit(2)),process.stdout.write(i.endsWith(`
2543
+ `),e.follow&&e.run===void 0){let i=r.offset,o=setInterval(()=>{let c=Ze(n.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var kL=t=>new Promise(e=>setTimeout(e,t));async function jk(t,e){if(!t){Bp(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let n=Kc(await Q(),t,"wait",process.cwd(),it()),r=e.wake?await xL():void 0,s=process.env.TYPEBULB_WAIT_SHIM==="1",i=process.env.TYPEBULB_WAIT_FOLLOW==="1",o=s||i,a=e.timeoutSec??1800,c=e.match??"",l=Ze(n.pid).offset,f=i?void 0:ga(n.pid,c)??(c?ga(n.pid):void 0),u=i?l:f!==void 0&&f<=l?f:c?0:l,d=Date.now()+a*1e3,p=we(n)?1e4:1e3,h=2e3,m=!we(n)&&!i,g,b="",C=[],T="",E=0,R=!1;for(;;){let O=u>=l,_=Ze(n.pid,u);if(u=_.offset,_.text){b+=_.text;let x=b.split(`
2544
+ `);b=x.pop()??"";let M=!1;for(let F of x)F.trim()&&(m&&O&&F.startsWith(ot.disconnected)&&(M=!0),!(e.match&&!F.includes(e.match))&&(console.log(F),C.push(F),!i&&(g??=Date.now()+p,we(n)&&(F.includes("] compile error")||F.includes("] runtime error"))&&(g=Math.min(g,Date.now()+h)))));if(M&&!g){T=`the last page of ${on(n)} closed while waiting \u2014 a bulb runs in its page, so nothing can log ${e.match?`'${e.match}'`:"anything"} now`,console.error(T),E=3;break}}if(g&&Date.now()>=g)break;if(!o&&!g&&Date.now()>=d){T=`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${on(n)} within ${a}s`,console.error(T),E=2;break}if(!Jt(n.pid)){g||(T=`server ${on(n)} (pid ${n.pid}) exited while waiting`,console.error(T),E=3,R=!0);break}await kL(400)}if(r){console.error(`detected ${new Date().toISOString()}`);try{await r.adapter.wake(r.sessionId,"typebulb_wait",C.length?C.join(`
2545
+ `):T)}catch(O){console.error(`Not delivered: ${O instanceof Error?O.message:O}`),process.exit(4)}console.error(`accepted ${new Date().toISOString()}`)}R&&process.exit(3),i||Ws(n.pid,u,c),process.exit(E)}async function xL(){let t=it(),e=t?Yr()[t]?.():void 0,n=e?.wake?e.callerSessionId?.(process.cwd()):void 0;(!e||!n)&&(console.error(e?.wake?"Can't --wake: your own session couldn't be identified in this project, and a wake goes to no other.":`--wake needs a harness that wakes through its host (here: ${t??"none detected"}); on Claude Code, a background wait already wakes you.`),process.exit(1));let r=await e.wakeRoute(n);return r.error&&(console.error(`Can't --wake: ${r.error}.`),process.exit(1)),{adapter:e,sessionId:n}}function Fk(t,e){if(e==="killed")return` \u2014 forced (${Mk(t.version)?`its runtime ${t.version?`v${t.version} `:""}predates the stop route`:"it did not answer"}); a page it opened may still be open`;let n=[];return e.closed&&n.push(`closed ${e.closed} page${e.closed===1?"":"s"}`),e.stuck&&n.push(`${e.stuck} did not close`),n.length?` \u2014 ${n.join(", ")}`:""}async function Uk(t){if(!t){await Bp(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Kc(await Q(),t,"stop",process.cwd(),it()),n=await wt(e);console.log(`Stopped ${on(e)} (pid ${e.pid}, ${e.url}).${Fk(e,n)}`)}async function qk(t){let e=await Dp(t),n=t==="global"?"server":t==="agent"?"mirror":"bulb";if(!e.length){console.log(t==="global"?"No running bulb servers.":`No running ${n}s for this project.`);return}let r=await Promise.all(e.map(s=>wt(s)));console.log(`Stopped ${e.length} ${n}${e.length===1?"":"s"}:`),e.forEach((s,i)=>console.log(` ${s.url} pid ${s.pid} ${on(s)}${Fk(s,r[i])}`))}async function Dp(t){let e=process.cwd(),n=t==="agent"?it():void 0;return t==="global"?await Q():t==="bulbs"?await Q(e):(await Q()).filter(r=>hr(r,e)&&(!n||r.agent===n))}async function Jk(t,e){let n=process.cwd(),r=t?[Kc(await Q(),t,"restart",n,it())]:e?await Dp(e):[...await Q(n),...await Dp("agent")];if(!r.length){console.log(e==="global"?"No running bulb servers.":"No running bulbs or mirrors for this project.");return}console.log(`Restarting on v${Pe}:`);for(let s of r){let i=s.version?`v${s.version}`:"unknown version";try{let o=we(s)?(await wt(s,"keep"),await Hs(s.agent,s.cwd??n)):await xn(s.file,{cwd:s.cwd??n,open:!1,trust:s.trust,noTrust:!s.trust,mode:s.mode,watch:s.watch,replace:s.replace});console.log(` ${o.url} ${on(s)} ${i} \u2192 v${Pe}`)}catch(o){console.log(` ${s.url} ${on(s)} failed: ${o instanceof Error?o.message:o}`),process.exitCode=1}}}$e();Ue();vn();import*as Hc from"path";import*as Wk from"http";import{mkdir as EL,writeFile as AL}from"fs/promises";async function Xr(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}function $i(t){return(t.charCodeAt(0)===65279?t.slice(1):t).replace(/\r\n/g,`
2546
+ `).trimEnd()}function TL(t,e){return new Promise((n,r)=>{let s=new URL(t),i=Wk.request({hostname:s.hostname,port:s.port,path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(e)}},o=>{let a="";o.setEncoding("utf8"),o.on("data",c=>{a+=c}),o.on("end",()=>n({status:o.statusCode??0,text:a}))});i.setTimeout(0),i.on("error",r),i.end(e)})}var CL=t=>{let e=Math.round((Date.now()-t)/6e4);return e<1?"moments ago":e<60?`${e}m ago`:`${Math.round(e/60)}h ago`};async function Kk(t,e,n=0){e==="-"&&(e=$i(await Xr()));let r=e!==void 0&&e.startsWith("tb:");r&&n<=0&&(n=Tp);let s=e!==void 0&&/^tb:(click|set)( |$)/.test(e),i=Hc.resolve(t),o=kn(await Q(),i)[0];if(!o){let h=(await wn(process.cwd()))(i);console.error(h?`No running server for '${t}' \u2014 it last ran ${CL(h)}. Relaunching reuses the same URL (a stale tab is one reload from live): npx typebulb ${t}`:`No running server for '${t}'. Start it first: npx typebulb ${t}`),process.exit(1)}let a=async h=>{let m=[h>0?`reply=${h}`:"",s?"solo=1":"","open=1"].filter(Boolean).join("&"),g=await TL(`${o.url}/__send${m?`?${m}`:""}`,e??"");(g.status<200||g.status>=300)&&(console.error(`send failed: HTTP ${g.status} from ${o.url}/__send`),process.exit(1));try{return JSON.parse(g.text)}catch{return{}}},c={},l=Date.now();try{c=await a(n)}catch(h){console.error(`send failed: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let f=c.clients??0,u=`${f} page${f===1?"":"s"}`;if(c.refused&&(console.error(`Actuation needs exactly one connected page; ${u} are open on ${o.url} \u2014 the reset is \`typebulb stop ${t}\` then relaunch.`),process.exit(1)),f===0){let h=c.droppedMsAgo,m=c.opening==="none"?" and no agent mirror page is open to open one through":"",g=c.opening==="unreached"?` \u2014 the page was opened ${c.via?`in VS Code via ${c.via}`:"in your browser"} and never attached; is the browser it opened in still there?`:h!==void 0?` \u2014 a page disconnected ${Math.round(h/1e3)}s ago and hasn't reconnected${m}; reload it, or open ${o.url}`:` \u2014 no page has ever connected${m}; share ${o.url} and arm: typebulb wait ${t} --match "${ot.connected}"`;console.error(`No page connected after ${((Date.now()-l)/1e3).toFixed(1)}s, so nothing was delivered${g}`),process.exit(1)}c.opening==="editor"?console.error(`Opened in VS Code via ${c.via}.`):c.opening==="external"&&console.error("Opened in your browser, where the agent mirror is."),console.error(`Sent to ${u}.`);let d=c.results??[],p=c.errors??[];for(let h of p)console.error(`handler error: ${h}`);if(p.length&&process.exit(1),d.length>1&&(console.error(`${d.length} replies from ${u} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),d.length===1){if(e!==void 0&&/^tb:png( |$)/.test(e)){let m={};try{m=JSON.parse(d[0])}catch{}typeof m.png!="string"&&(console.error("tb:png replied with an unexpected shape \u2014 an older runtime? (`typebulb logs` lists server versions)"),process.exit(1));let g=Eb(i);await EL(Hc.dirname(g),{recursive:!0}),await AL(g,Buffer.from(m.png,"base64"));let b=[m.via?`inside "${m.via}"`:"",m.backdrop?`backdrop ${m.backdrop}`:""].filter(Boolean);console.error(`canvas ${m.width}\xD7${m.height} \u2192 PNG${b.length?` (${b.join("; ")})`:""}`),console.log(g);return}let h;try{h=JSON.parse(d[0])}catch{h=void 0}console.log(typeof h=="string"?h:d[0])}else c.timedOut&&(r&&(console.error(`No reply to '${e}' within ${n/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${n/1e3}s \u2014 slow work needs a larger --wait=ms; a reply that NEVER comes is a done-promise that missed an exit, or a blocked main thread: tb:snapshot runs no page code, so its silence too means blocked)`))}rc();Of();re();import*as Hk from"fs/promises";async function zk(t,e){let n=await Hk.readFile(t,"utf-8"),r=Hn(n),s=pe[e].path,i=r.files.get(s);i||(console.error(i===void 0?`No **${s}** block in ${t}`:`The **${s}** block in ${t} is empty`),process.exit(2)),process.stdout.write(i.endsWith(`
2547
2547
  `)?i:i+`
2548
- `)}re();import*as Ni from"fs/promises";async function Gk(t,e){let n=await Ni.readFile(t,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await Xr():await Ni.readFile(o,"utf-8")}catch(c){Vk(`Cannot read ${i}'s source: ${c instanceof Error?c.message:String(c)}`)}r.push({kind:i,content:$i(a),label:o==="-"?"stdin":o})}let s;try{s=CL(n,r)}catch(i){Vk(`${t}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${pe[i].path}: already up to date`);if(s.written.length){await Ni.writeFile(t,s.text);for(let i of s.written)console.log(i.action==="removed"?`${pe[i.kind].path}: removed (${i.label} is empty)`:`${pe[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function CL(t,e){let n=Hn(t),r=t,s=[],i=[];for(let{kind:o,content:a,label:c}of e){let l=pe[o].path,f=n.files.get(l);if(!a){if(f===void 0){i.push(o);continue}r=Yk(ph(r,o),r,l),s.push({kind:o,action:"removed",chars:0,label:c});continue}if(f!==void 0&&$i(f)===a){i.push(o);continue}r=Yk(Zr(r,o,a),r,l),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:c})}return{text:r,written:s,upToDate:i}}function Yk(t,e,n){if(t===e)throw new Error(`the **${n}** block's fence is unterminated; refusing to rewrite inside it`);return t}function Vk(t){console.error(t),process.exit(1)}tt();ki();xc();bc();Dn();jr();function jp(){let t=Yr(),e=it();return{caller:e,adapters:(e?[e]:Object.keys(t)).map(n=>t[n]()).filter(n=>n.listChildren)}}async function Qk(t,e,n){ve(e);let{caller:r,adapters:s}=jp();if(!s.length){console.error(`Sub-agent status isn't supported for ${r} sessions.`),process.exitCode=1;return}let i;for(let o of s){let{sessionId:a,cwd:c}=Si(o,process.cwd());if(!t){let l=a?kc(o,c,a):Sc(o,c).next().value,f=l?Bv(jn(o,c,l.sessionId,l.file,l.children).threads,Date.now()):[];if(!l?.children.length){if(a){en(a,n),console.log([...f,...f.length?[""]:[],"No sub-agents in this session yet."].join(`
2549
- `));return}continue}en(a??l.sessionId,n);let{reports:u,files:d}=await tn(o,c,l);console.log(nS(l.sessionId,u,d,Date.now(),f));return}for(let l of Sc(o,c)){i??=l;let f=aS(l,t);if(f.length){if(f.length>1){console.error(`Several agents match "${t}"; name one by its id:`);for(let u of f)console.error(` ${Xk(u)}`);process.exitCode=1;return}en(a??l.sessionId,n),console.log(Qv((await tn(o,c,l,f[0].id)).reports[0],Date.now()));return}}}if(!i){console.log("No sub-agents in this project's sessions.");return}console.error(`No agent matches "${t}". The agents of session ${i.sessionId}:`);for(let o of i.children)console.error(` ${Xk(o)}`);process.exitCode=1}var Xk=t=>`${t.id} ${pc(t).padEnd(7)} ${ft(t)}`;tt();Ue();$e();ki();xc();bc();import{mkdirSync as OL,readFileSync as tx,writeFileSync as nx,rmSync as PL}from"fs";import{join as zc}from"path";var _L=1e4,RL=720*6e4,Zk="typebulb_babysit";async function rx(t,e){ve(t);let{caller:n,adapters:r}=jp(),s=r.map(m=>({adapter:m,...(m.wake?Si:oS)(m,process.cwd())})).find(m=>m.sessionId);if(!s?.sessionId)return ex(r.length?r.some(m=>m.wake)?"Can't babysit: your own session couldn't be identified in this project, and a wake goes to no other.":"No session to babysit in this project.":`Babysit isn't supported for ${n} sessions.`);let{adapter:i,sessionId:o,cwd:a}=s;if(en(o,e),i.wake){let m=await i.wakeRoute(o);if(m.error)return ex(`Can't babysit: ${m.error}.`)}let c=zc(Ee(),"babysit"),l=zc(c,`${o}.json`),f=zc(c,`${o}.lock`),u=IL(f),d=[];try{d=JSON.parse(tx(l,"utf8"))}catch{}let p=m=>{try{nx(l,JSON.stringify(m))}catch{}};u&&console.error(`Took over from the babysit already watching this session (pid ${u}), which stops at its next check.`),console.error(`Babysitting session ${o}: this exits with a line when a sub-agent or the user's answer needs you; run it again after handling that.`);let h=Date.now()+RL;for(;Date.now()<h;){let m=Fp(f);m!==void 0&&m!==process.pid&&Li(5,"A newer babysit took over this session."),i.sessionEnded?.(o,a)&&Li(3,"The session this babysits has ended.");let g=kc(i,a,o),{reports:b}=await tn(i,a,g),{threads:C}=jn(i,a,o,g.file,g.children),T=rS(b,Date.now(),!!i.sessionsWorking?.(a)?.has(o),en(o),C),E=[...T].filter(([R])=>!d.includes(R));if(!E.length)d=[...T.keys()],p(d);else{let R=E.map(([,O])=>O).join(`
2550
- `);if(i.wake){console.error(`detected ${new Date().toISOString()}`);try{await i.wake(o,Zk,R)}catch(O){p([...T.keys()].filter(_=>!E.some(([x])=>x===_))),console.log(R),Li(4,`Not delivered: ${O instanceof Error?O.message:O}`)}console.error(`accepted ${new Date().toISOString()}`)}p([...T.keys()]),console.log(R),Li(0)}await new Promise(R=>setTimeout(R,_L))}i.wake&&await i.wake(o,Zk,"typebulb babysit stopped after 12 hours with nothing to report; run it again to keep watching.").catch(()=>{}),Li(2,"Nothing needed attention; gave up.")}function ex(t){console.error(t),process.exitCode=1}function Li(t,e){e&&console.error(e),process.exit(t)}function IL(t){try{OL(zc(t,".."),{recursive:!0})}catch{}let e=Fp(t);try{nx(t,String(process.pid))}catch{}return process.on("exit",()=>{try{Fp(t)===process.pid&&PL(t)}catch{}}),e&&e!==process.pid&&Jt(e)?e:void 0}function Fp(t){try{return Number(tx(t,"utf8"))||void 0}catch{return}}tt();Tt();re();ka();import*as cn from"fs/promises";import*as Wn from"path";import{EventEmitter as eM}from"events";Wt();re();import{Hono as BL}from"hono";import{serve as jL}from"@hono/node-server";import{streamSSE as FL}from"hono/streaming";import*as Jp from"fs/promises";import UL from"open";Pr();ui();Or();import*as Up from"fs/promises";import*as Mi from"path";var Yc=class{async get(e){let n=nt(e),r=Mi.join(li,n+".bin"),s=Mi.join(li,n+".json");try{let[i,o]=await Promise.all([Up.readFile(r),Up.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,n){await se();let r=nt(e),s=Mi.join(li,r+".bin"),i=Mi.join(li,r+".json"),o={url:e,contentType:n.contentType,cacheControl:n.cacheControl};await Promise.all([qe(s,n.body),qe(i,JSON.stringify(o))])}};var sx=`
2548
+ `)}re();import*as Ni from"fs/promises";async function Gk(t,e){let n=await Ni.readFile(t,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await Xr():await Ni.readFile(o,"utf-8")}catch(c){Vk(`Cannot read ${i}'s source: ${c instanceof Error?c.message:String(c)}`)}r.push({kind:i,content:$i(a),label:o==="-"?"stdin":o})}let s;try{s=OL(n,r)}catch(i){Vk(`${t}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${pe[i].path}: already up to date`);if(s.written.length){await Ni.writeFile(t,s.text);for(let i of s.written)console.log(i.action==="removed"?`${pe[i.kind].path}: removed (${i.label} is empty)`:`${pe[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function OL(t,e){let n=Hn(t),r=t,s=[],i=[];for(let{kind:o,content:a,label:c}of e){let l=pe[o].path,f=n.files.get(l);if(!a){if(f===void 0){i.push(o);continue}r=Yk(ph(r,o),r,l),s.push({kind:o,action:"removed",chars:0,label:c});continue}if(f!==void 0&&$i(f)===a){i.push(o);continue}r=Yk(Zr(r,o,a),r,l),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:c})}return{text:r,written:s,upToDate:i}}function Yk(t,e,n){if(t===e)throw new Error(`the **${n}** block's fence is unterminated; refusing to rewrite inside it`);return t}function Vk(t){console.error(t),process.exit(1)}tt();ki();xc();bc();Dn();jr();function jp(){let t=Yr(),e=it();return{caller:e,adapters:(e?[e]:Object.keys(t)).map(n=>t[n]()).filter(n=>n.listChildren)}}async function Qk(t,e,n){ve(e);let{caller:r,adapters:s}=jp();if(!s.length){console.error(`Sub-agent status isn't supported for ${r} sessions.`),process.exitCode=1;return}let i;for(let o of s){let{sessionId:a,cwd:c}=Si(o,process.cwd());if(!t){let l=a?kc(o,c,a):Sc(o,c).next().value,f=l?Bv(jn(o,c,l.sessionId,l.file,l.children).threads,Date.now()):[];if(!l?.children.length){if(a){en(a,n),console.log([...f,...f.length?[""]:[],"No sub-agents in this session yet."].join(`
2549
+ `));return}continue}en(a??l.sessionId,n);let{reports:u,files:d}=await tn(o,c,l);console.log(nS(l.sessionId,u,d,Date.now(),f));return}for(let l of Sc(o,c)){i??=l;let f=aS(l,t);if(f.length){if(f.length>1){console.error(`Several agents match "${t}"; name one by its id:`);for(let u of f)console.error(` ${Xk(u)}`);process.exitCode=1;return}en(a??l.sessionId,n),console.log(Qv((await tn(o,c,l,f[0].id)).reports[0],Date.now()));return}}}if(!i){console.log("No sub-agents in this project's sessions.");return}console.error(`No agent matches "${t}". The agents of session ${i.sessionId}:`);for(let o of i.children)console.error(` ${Xk(o)}`);process.exitCode=1}var Xk=t=>`${t.id} ${pc(t).padEnd(7)} ${ft(t)}`;tt();Ue();$e();ki();xc();bc();import{mkdirSync as PL,readFileSync as tx,writeFileSync as nx,rmSync as _L}from"fs";import{join as zc}from"path";var RL=1e4,IL=720*6e4,Zk="typebulb_babysit";async function rx(t,e){ve(t);let{caller:n,adapters:r}=jp(),s=r.map(m=>({adapter:m,...(m.wake?Si:oS)(m,process.cwd())})).find(m=>m.sessionId);if(!s?.sessionId)return ex(r.length?r.some(m=>m.wake)?"Can't babysit: your own session couldn't be identified in this project, and a wake goes to no other.":"No session to babysit in this project.":`Babysit isn't supported for ${n} sessions.`);let{adapter:i,sessionId:o,cwd:a}=s;if(en(o,e),i.wake){let m=await i.wakeRoute(o);if(m.error)return ex(`Can't babysit: ${m.error}.`)}let c=zc(Ee(),"babysit"),l=zc(c,`${o}.json`),f=zc(c,`${o}.lock`),u=$L(f),d=[];try{d=JSON.parse(tx(l,"utf8"))}catch{}let p=m=>{try{nx(l,JSON.stringify(m))}catch{}};u&&console.error(`Took over from the babysit already watching this session (pid ${u}), which stops at its next check.`),console.error(`Babysitting session ${o}: this exits with a line when a sub-agent or the user's answer needs you; run it again after handling that.`);let h=Date.now()+IL;for(;Date.now()<h;){let m=Fp(f);m!==void 0&&m!==process.pid&&Li(5,"A newer babysit took over this session."),i.sessionEnded?.(o,a)&&Li(3,"The session this babysits has ended.");let g=kc(i,a,o),{reports:b}=await tn(i,a,g),{threads:C}=jn(i,a,o,g.file,g.children),T=rS(b,Date.now(),!!i.sessionsWorking?.(a)?.has(o),en(o),C),E=[...T].filter(([R])=>!d.includes(R));if(!E.length)d=[...T.keys()],p(d);else{let R=E.map(([,O])=>O).join(`
2550
+ `);if(i.wake){console.error(`detected ${new Date().toISOString()}`);try{await i.wake(o,Zk,R)}catch(O){p([...T.keys()].filter(_=>!E.some(([x])=>x===_))),console.log(R),Li(4,`Not delivered: ${O instanceof Error?O.message:O}`)}console.error(`accepted ${new Date().toISOString()}`)}p([...T.keys()]),console.log(R),Li(0)}await new Promise(R=>setTimeout(R,RL))}i.wake&&await i.wake(o,Zk,"typebulb babysit stopped after 12 hours with nothing to report; run it again to keep watching.").catch(()=>{}),Li(2,"Nothing needed attention; gave up.")}function ex(t){console.error(t),process.exitCode=1}function Li(t,e){e&&console.error(e),process.exit(t)}function $L(t){try{PL(zc(t,".."),{recursive:!0})}catch{}let e=Fp(t);try{nx(t,String(process.pid))}catch{}return process.on("exit",()=>{try{Fp(t)===process.pid&&_L(t)}catch{}}),e&&e!==process.pid&&Jt(e)?e:void 0}function Fp(t){try{return Number(tx(t,"utf8"))||void 0}catch{return}}tt();Tt();re();ka();import*as cn from"fs/promises";import*as Wn from"path";import{EventEmitter as tM}from"events";Wt();re();import{Hono as jL}from"hono";import{serve as FL}from"@hono/node-server";import{streamSSE as UL}from"hono/streaming";import*as Jp from"fs/promises";import qL from"open";Pr();ui();Or();import*as Up from"fs/promises";import*as Mi from"path";var Yc=class{async get(e){let n=nt(e),r=Mi.join(li,n+".bin"),s=Mi.join(li,n+".json");try{let[i,o]=await Promise.all([Up.readFile(r),Up.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,n){await se();let r=nt(e),s=Mi.join(li,r+".bin"),i=Mi.join(li,r+".json"),o={url:e,contentType:n.contentType,cacheControl:n.cacheControl};await Promise.all([qe(s,n.body),qe(i,JSON.stringify(o))])}};var sx=`
2551
2551
  const CSS = '\\n' +
2552
2552
  /* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
2553
2553
  chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
@@ -2930,9 +2930,9 @@ export function runInference(ctx) {
2930
2930
  showConfirm();
2931
2931
  document.body.appendChild(host);
2932
2932
  }
2933
- `;Rr();$e();Cn();$a();Wt();import{stream as $L}from"hono/streaming";var NL="X-TB-Stream";function Di(t){return t instanceof Le?{message:t.message,code:t.code,retryable:t.retryable}:{message:t instanceof Error?t.message:"Unknown error",code:"unknown",retryable:!1}}function Vc(t,e){return t.header("Content-Type","application/x-ndjson; charset=utf-8"),t.header("Cache-Control","no-cache"),t.header(NL,"1"),$L(t,async n=>{let r=e[Symbol.asyncIterator]();n.onAbort(()=>{r.return?.()});try{for(;;){let{done:s,value:i}=await r.next();if(s)break;await n.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await n.writeln(JSON.stringify({type:"error",error:Di(s)}))}finally{try{await r.return?.()}catch{}}})}var Gc={log:(...t)=>console.log(...t)};function Xc(t,e){let n=t?.[e]??(Object.hasOwn(Gc,e)?Gc[e]:void 0);return typeof n=="function"?n:void 0}function Qc(t){return t.constructor?.name==="AsyncGeneratorFunction"}vf();var LL=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,ML=/[?&]target=/,DL=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function ix(t,e=""){return LL.test(t)?!0:DL.test(t)&&ML.test(e)}var qL="127.0.0.1",JL=new Set(["localhost","127.0.0.1","::1"]),ux=(t,e)=>!!t&&typeof t=="object"&&e in t,ox=t=>{let e={};return Array.isArray(t.data)&&(e.data=t.data),ux(t,"insight")&&(e.insight=t.insight),e},ax=8*1024*1024,WL=0;function KL(t){if(t)try{return new URL(t.includes("://")?t:`http://${t}`).hostname}catch{return}}function dx(t){let e=KL(t);return!!e&&JL.has(e)}function HL(t){try{let e=new URL(t);return(e.protocol==="http:"||e.protocol==="https:")&&dx(e.host)}catch{return!1}}function zL(t){return!!t&&/\bCode\/\d/.test(t)&&/\bElectron\//.test(t)}function YL(t,e){if(!e)return!1;try{return new URL(t).host===e}catch{return!1}}function Bi(t){return t instanceof Error?t.message:"Unknown error"}var cx=t=>t.how==="editor"||t.how==="unreached"?t.via:void 0,VL=2e3;async function fx(t){let{getHtml:e,basePath:n,fsBase:r,port:s,reloadEmitter:i,sendChannel:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:h,sourceFile:m,bulbKey:g,onStop:b}=t,C=`${process.pid}-${++WL}-${Date.now()}`,T=r??n,E=new BL;E.use("*",async(w,A)=>{if(!dx(w.req.header("host")))return w.text("Forbidden: untrusted Host",403);await A()}),E.use("*",async(w,A)=>{await A(),w.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),w.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let R=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],O=async(w,A)=>{if(!u){let I=new URL(w.req.url).pathname,L=R.find(([K])=>K.endsWith("/*")?I.startsWith(K.slice(0,-2)):I===K)?.[1]??"server-side code (server.ts)";Cd(process.pid,L);let B=d?`
2934
- ${d}`:"";return w.text(`Forbidden: this capability requires --trust.${B}`,403)}await A()},_=async(w,A)=>{let I=w.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return w.text(`Forbidden: ${I} request`,403)}else{let L=w.req.header("origin");if(L&&!YL(L,w.req.header("host")))return w.text("Forbidden: cross-origin request",403)}await A()};for(let[w]of R)E.use(w,O),E.use(w,_);E.use("/__log",_),E.post("/__log",async w=>{try{let{args:A}=await w.req.json();console.log(...A||[])}catch{}return w.json({ok:!0})});let x=new Wc,M=new Set,F=new Set,ee=Date.now();x.onArrival(({page:w,firstAttach:A,count:I})=>{o&&I===1&&console.log(ot.connected),A&&I>1&&w.close("yielded").catch(()=>{})}),o&&x.onSettledEmpty(()=>console.log(ot.disconnected));let q,ue=0,ie=async w=>{let A=Math.max(w.fresh?0:ee,x.lastDropAt);if(await x.whenArrives(Mp-(Date.now()-A)))return{how:"attached"};if(Date.now()-ue<VL)return{how:"none"};let I=`http://localhost:${s}#tb-relay`,L=await Pd(I,n),B;return L?.where==="editor"?B={how:"editor",via:L.via}:(w.external==="force"||w.external==="follow"&&L?.where==="external")&&(await UL(I),B={how:"external"}),B?await x.whenArrives($k)?B:{how:"unreached",via:cx(B)}:(ue=Date.now(),{how:"none"})},ye=w=>x.count>0?Promise.resolve({how:"attached"}):q??=ie(w).finally(()=>{q=void 0});if(o){let w=0,A=new Map;E.use("/__send",_),E.post("/__send",async I=>{let L="";try{L=await I.req.text()}catch{}let B=Number(I.req.query("reply"))||0,K=x.count===0&&I.req.query("open")!==void 0?await ye({external:"follow",fresh:!1}):void 0,H=x.count,Be=H===0&&x.lastDropAt?Date.now()-x.lastDropAt:void 0,Y={clients:H,droppedMsAgo:Be,...K?{opening:K.how,via:cx(K)}:{}};if(I.req.query("solo")!==void 0&&H!==1)return I.json({...Y,refused:H>1});if(H===0)return I.json(Y);let fe=un=>{for(let _t of x)_t.send(un).catch(()=>{})};if(B<=0)return fe({payload:L}),I.json(Y);let Re=++w,Qr=await new Promise(un=>{let _t={expected:H,received:0,results:[],errors:[],finish:tl=>{clearTimeout(el),A.delete(Re),un({results:_t.results,errors:_t.errors,timedOut:tl})}},el=setTimeout(()=>_t.finish(!0),B);A.set(Re,_t),fe({id:Re,payload:L})});return I.json({...Y,...Qr})}),E.use("/__send-reply",_),E.post("/__send-reply",async I=>{try{let{id:L,results:B,errors:K}=await I.req.json(),H=A.get(L);H&&(H.results.push(...B??[]),H.errors.push(...K??[]),++H.received>=H.expected&&H.finish(!1))}catch{}return I.json({ok:!0})})}E.get("/",w=>w.html(e())),E.post("/__fs/read",async w=>{try{let{path:A}=await w.req.json(),I=await di(A,T);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(A){let I=Bi(A);return w.json({error:I},400)}}),E.post("/__fs/write",async w=>{try{let A=w.req.query("path");return A?(await Ga(A,new Uint8Array(await w.req.arrayBuffer()),T),w.json({success:!0})):w.json({error:"Missing path"},400)}catch(A){let I=Bi(A);return w.json({error:I},400)}}),E.post("/__fs/list",async w=>{try{let{path:A}=await w.req.json();return w.json(await Xa(A??".",T))}catch(A){return w.json({error:Bi(A)},400)}}),E.post("/__fs/remove",async w=>{try{let{path:A}=await w.req.json();return await Qa(A,T),w.json({success:!0})}catch(A){return w.json({error:Bi(A)},400)}}),E.post("/__api/:name",async w=>{try{let A=w.req.param("name"),I=Xc(a?.(),A);if(!I)return w.json({error:`API function '${A}' not found`},404);let{args:L}=await w.req.json();if(Qc(I))return Vc(w,I(...L||[]));let B=await I(...L||[]);return w.json({result:B})}catch(A){let I=Bi(A);return w.json({error:I},500)}}),E.post("/__ai",async w=>{try{let{messages:A,system:I,effort:L,provider:B,model:K,webSearch:H,stream:Be}=await w.req.json();if(!A||!Array.isArray(A)||A.length===0)return w.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Y=St(B,K);if(typeof Y=="string")return w.json({message:Y,code:"unknown",retryable:!1},400);let fe=await Ht(Y,{messages:A,system:I,effort:L,webSearch:H,signal:w.req.raw.signal});if(!fe.ok){let un=await xr(fe,Y.protocol);return w.json(un,fe.status)}if(Be)return Vc(w,_n(fe,Y.protocol));let{text:Re,usage:Qr}=await Er(fe,Y.protocol);return Re||console.warn("[tb.ai] Empty response from provider"),w.json({text:Re,usage:Qr})}catch(A){return w.json(Di(A),500)}}),E.post("/__infer",async w=>{try{let{data:A}=await w.req.json().catch(()=>({})),I=c?.();if(!I?.infer.trim())return w.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let L=St();if(typeof L=="string")return w.json({message:L,code:"unknown",retryable:!1},400);let B=Array.isArray(A)?A.map(String):[],K=Zd(I,B),H=await Ht(L,{messages:[{role:"user",content:K}],signal:w.req.raw.signal});if(!H.ok){let Y=await xr(H,L.protocol);return w.json(Y,H.status)}let Be=(async function*(){let Y="";for await(let Re of _n(H,L.protocol))Re.kind!=="text"||!Re.text||(Y+=Re.text,yield{kind:"delta",text:Re.text});let fe=ef(Y);if(fe.parsed===void 0)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
2935
- `+Y.slice(-4e3)),new Le("LLM output is not valid JSON","parse_error",!0);fe.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",fe.fixesApplied.join(", ")),yield{kind:"complete",insight:fe.parsed,data:B,fixesApplied:fe.fixesApplied}})();return Vc(w,Be)}catch(A){return w.json(Di(A),500)}}),E.post("/__infer-save",async w=>{try{if(!l)return w.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let A=ox(await w.req.json().catch(()=>({})));return Object.keys(A).length?(await l(A.data,ux(A,"insight")?JSON.stringify(A.insight,null,2):void 0),w.json({ok:!0})):w.json({message:"Nothing to save \u2014 this page holds no runtime state.",code:"unknown",retryable:!1},400)}catch(A){return w.json(Di(A),500)}}),E.get("/__infer-info",w=>{let A=c?.(),I=es(A?.config??"").inference,L=Ho(A?.data??""),B=!!A?.infer.trim(),K=St();return typeof K=="string"?w.json({error:K,inference:I,data:L,hasInfer:B}):w.json({provider:K.protocol,model:K.model,inference:I,data:L,hasInfer:B})}),E.use("/__tb-decode",_),E.post("/__tb-decode",async w=>{let{hash:A}=await w.req.json().catch(()=>({})),I=typeof A=="string"?nf(A):void 0;return w.json(I??{error:"invalid fragment"})}),E.use("/__tb-encode",_),E.post("/__tb-encode",async w=>{let A=Number(w.req.header("content-length"));if(Number.isFinite(A)&&A>ax)return w.json({hash:""});let I=await w.req.text().catch(()=>"");if(I.length>ax)return w.json({hash:""});let L;try{L=JSON.parse(I)}catch{return w.json({hash:""})}return w.json({hash:tf(ox(L))})}),E.get("/__infer-ui.js",w=>w.body(sx,200,{"Content-Type":"text/javascript; charset=utf-8"})),E.get("/__models",async w=>{try{let A=await vt();return w.json(A)}catch{return w.json([],200)}}),E.get("/__ai-access",async w=>{try{return w.json(await Aa())}catch{return w.json("none",200)}}),m&&E.get("/__source/*",async w=>{let A=await Jp.readFile(m,"utf-8").catch(()=>{});return A===void 0?w.text("Not Found",404):new Response(A,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let xe=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],de=new Yc;E.get("/proxy/*",async w=>{let A=new URL(w.req.url),L=(A.pathname+A.search).slice(7),B=L.lastIndexOf("https://");return B===-1?w.text("Invalid proxy URL",400):be(w,L.slice(B))}),f&&lx(E,`/local/${f.name}/`,f.serveDir),p&&lx(E,p.mount,p.dir),h&&E.get("/assets/*",async w=>{let{pathname:A}=new URL(w.req.url),I=A.slice(8),L;try{L=decodeURIComponent(I)}catch{return w.text("Not Found",404)}let B=yh(L);if(B)return w.text(`${B} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{let H=await px(L,h.dir,{"Cache-Control":"no-cache"});if(H)return H}catch{return w.text("Not Found",404)}let K=h.remoteBase;return K?w.redirect(K+I,302):w.text("Not Found",404)});async function be(w,A){let I;try{I=new URL(A)}catch{return w.text("Invalid URL",400)}if(I.protocol!=="https:")return w.text("HTTPS only",400);if(!xe.includes(I.hostname))return w.text("Host not allowed",403);let L=await de.get(A);if(L)return new Response(L.body,{status:200,headers:qp(L.contentType,L.cacheControl)});try{let B=await fetch(A,{headers:{Accept:w.req.header("Accept")||"*/*"},redirect:"follow"});if(!B.ok)return w.text(`Upstream ${B.status}`,B.status);let K=B.headers.get("Content-Type")||void 0,H=B.headers.get("Cache-Control")||void 0;if(B.body){let[Be,Y]=B.body.tee();return(async()=>{try{let fe=await new Response(Y).arrayBuffer();await de.set(A,{body:Buffer.from(fe),contentType:K,cacheControl:H})}catch{}})(),new Response(Be,{status:B.status,headers:qp(K,H)})}return new Response(null,{status:B.status,headers:qp(K,H)})}catch(B){return w.text(`Proxy fetch failed: ${B instanceof Error?B.message:B}`,502)}}(i||o)&&(E.get("/__reload",w=>FL(w,async A=>{let I=w.req.query("bulb")||void 0;if(g&&I&&I!==g){M.has(I)||(M.add(I),console.log(ot.closed("foreign"))),await A.writeSSE({event:"close",data:"foreign"});return}let L=()=>{A.writeSSE({event:"reload",data:""})};i?.on("reload",L);let B=()=>i?.removeListener("reload",L),K=w.req.query("relay")||void 0,H={inEditor:zL(w.req.header("user-agent")),doc:K,open:Y=>A.writeSSE({event:"open-url",data:Y}),send:Y=>A.writeSSE({event:"message",data:JSON.stringify(Y)}),close:Y=>(B(),x.closing(H),console.log(ot.closed(Y)),A.writeSSE({event:"close",data:Y}))},Be=!!K&&!F.has(K);for(K&&F.add(K),x.add(H,Be),A.onAbort(()=>{B(),x.dropped(H)}),await A.writeSSE({event:"hello",data:C,retry:bf});!A.aborted;)await A.sleep(3e4)})),E.use("/__open",_),E.post("/__open",async w=>{let A="";try{A=String((await w.req.json()).url??"")}catch{}if(!HL(A))return w.json({error:"a local http URL is required"},400);let I=[...x].find(L=>L.inEditor);return await I?.open(A),w.json({opened:!!I,pages:x.count})})),E.use("/__stop",_),E.post("/__stop",async w=>{if(w.req.header("sec-fetch-site")||w.req.header("origin"))return w.text("Forbidden: browser request",403);let A="close";try{let L=await w.req.json();(L?.pages==="keep"||L?.pages==="close")&&(A=L.pages)}catch{}let I=A==="close"?await x.closeAll("stopped"):{told:0,gone:0};return b&&setTimeout(()=>{b({pages:A})},50),w.json({closed:I.gone,stuck:I.told-I.gone,exiting:!!b})}),E.get("/__pages",w=>w.json({pages:x.count})),E.notFound(async w=>{if(w.req.method!=="GET")return w.text("Not Found",404);let A=new URL(w.req.url);return ix(A.pathname,A.search)?be(w,"https://esm.sh"+A.pathname+A.search):w.text("Not Found",404)});let ln=jL({fetch:E.fetch,port:s,hostname:qL});return ln.listening||await new Promise((w,A)=>{let I=L=>A(L);ln.once("error",I),ln.once("listening",()=>{ln.removeListener("error",I),w()})}),{port:s,close:()=>ln.close(),requestPage:ye,closePages:w=>x.closeAll(w),pageCount:()=>x.count}}function qp(t,e){let n=new Headers;return t&&n.set("Content-Type",t),e&&n.set("Cache-Control",e),n.set("Access-Control-Allow-Origin","*"),n.set("Cross-Origin-Resource-Policy","cross-origin"),n}function lx(t,e,n){t.get(`${e}*`,async r=>{let{pathname:s}=new URL(r.req.url);if(!s.startsWith(e))return r.text("Not Found",404);try{return await px(decodeURIComponent(s.slice(e.length)),n)??r.text("Not Found",404)}catch{return r.text("Not Found",404)}})}async function px(t,e,n={}){let r=Ir(t,e),s=await Jp.readFile(r).catch(()=>{});if(s)return new Response(s,{headers:{"Content-Type":gh(r),...n}})}$e();vn();async function Zc(t){let{port:e,portNote:n,makeServerOptions:r,makeEntry:s,displayName:i,waitTarget:o,stopLog:a}=t,c=`http://localhost:${e}`,l=s(e,c),f=[],u,d=!1,p=async m=>{if(!d){d=!0,console.log(`
2933
+ `;Rr();$e();Cn();$a();Wt();import{stream as NL}from"hono/streaming";var LL="X-TB-Stream";function Di(t){return t instanceof Le?{message:t.message,code:t.code,retryable:t.retryable}:{message:t instanceof Error?t.message:"Unknown error",code:"unknown",retryable:!1}}function Vc(t,e){return t.header("Content-Type","application/x-ndjson; charset=utf-8"),t.header("Cache-Control","no-cache"),t.header(LL,"1"),NL(t,async n=>{let r=e[Symbol.asyncIterator]();n.onAbort(()=>{r.return?.()});try{for(;;){let{done:s,value:i}=await r.next();if(s)break;await n.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await n.writeln(JSON.stringify({type:"error",error:Di(s)}))}finally{try{await r.return?.()}catch{}}})}var Gc={log:(...t)=>console.log(...t)};function Xc(t,e){let n=t?.[e]??(Object.hasOwn(Gc,e)?Gc[e]:void 0);return typeof n=="function"?n:void 0}function Qc(t){return t.constructor?.name==="AsyncGeneratorFunction"}vf();var ML=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,DL=/[?&]target=/,BL=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function ix(t,e=""){return ML.test(t)?!0:BL.test(t)&&DL.test(e)}var JL="127.0.0.1",WL=new Set(["localhost","127.0.0.1","::1"]),ux=(t,e)=>!!t&&typeof t=="object"&&e in t,ox=t=>{let e={};return Array.isArray(t.data)&&(e.data=t.data),ux(t,"insight")&&(e.insight=t.insight),e},ax=8*1024*1024,KL=0;function HL(t){if(t)try{return new URL(t.includes("://")?t:`http://${t}`).hostname}catch{return}}function dx(t){let e=HL(t);return!!e&&WL.has(e)}function zL(t){try{let e=new URL(t);return(e.protocol==="http:"||e.protocol==="https:")&&dx(e.host)}catch{return!1}}function YL(t){return!!t&&/\bCode\/\d/.test(t)&&/\bElectron\//.test(t)}function VL(t,e){if(!e)return!1;try{return new URL(t).host===e}catch{return!1}}function Bi(t){return t instanceof Error?t.message:"Unknown error"}var cx=t=>t.how==="editor"||t.how==="unreached"?t.via:void 0,GL=2e3;async function fx(t){let{getHtml:e,basePath:n,fsBase:r,port:s,reloadEmitter:i,sendChannel:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:h,sourceFile:m,bulbKey:g,onStop:b}=t,C=`${process.pid}-${++KL}-${Date.now()}`,T=r??n,E=new jL;E.use("*",async(w,A)=>{if(!dx(w.req.header("host")))return w.text("Forbidden: untrusted Host",403);await A()}),E.use("*",async(w,A)=>{await A(),w.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),w.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let R=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],O=async(w,A)=>{if(!u){let I=new URL(w.req.url).pathname,L=R.find(([K])=>K.endsWith("/*")?I.startsWith(K.slice(0,-2)):I===K)?.[1]??"server-side code (server.ts)";Cd(process.pid,L);let B=d?`
2934
+ ${d}`:"";return w.text(`Forbidden: this capability requires --trust.${B}`,403)}await A()},_=async(w,A)=>{let I=w.req.header("sec-fetch-site");if(I){if(I!=="same-origin")return w.text(`Forbidden: ${I} request`,403)}else{let L=w.req.header("origin");if(L&&!VL(L,w.req.header("host")))return w.text("Forbidden: cross-origin request",403)}await A()};for(let[w]of R)E.use(w,O),E.use(w,_);E.use("/__log",_),E.post("/__log",async w=>{try{let{args:A}=await w.req.json();console.log(...A||[])}catch{}return w.json({ok:!0})});let x=new Wc,M=new Set,F=new Set,ee=Date.now();x.onArrival(({page:w,firstAttach:A,count:I})=>{o&&I===1&&console.log(ot.connected),A&&I>1&&w.close("yielded").catch(()=>{})}),o&&x.onSettledEmpty(()=>console.log(ot.disconnected));let q,ue=0,ie=async w=>{let A=Math.max(w.fresh?0:ee,x.lastDropAt);if(await x.whenArrives(Mp-(Date.now()-A)))return{how:"attached"};if(Date.now()-ue<GL)return{how:"none"};let I=`http://localhost:${s}#tb-relay`,L=await Pd(I,n),B;return L?.where==="editor"?B={how:"editor",via:L.via}:(w.external==="force"||w.external==="follow"&&L?.where==="external")&&(await qL(I),B={how:"external"}),B?await x.whenArrives($k)?B:{how:"unreached",via:cx(B)}:(ue=Date.now(),{how:"none"})},ye=w=>x.count>0?Promise.resolve({how:"attached"}):q??=ie(w).finally(()=>{q=void 0});if(o){let w=0,A=new Map;E.use("/__send",_),E.post("/__send",async I=>{let L="";try{L=await I.req.text()}catch{}let B=Number(I.req.query("reply"))||0,K=x.count===0&&I.req.query("open")!==void 0?await ye({external:"follow",fresh:!1}):void 0,H=x.count,Be=H===0&&x.lastDropAt?Date.now()-x.lastDropAt:void 0,Y={clients:H,droppedMsAgo:Be,...K?{opening:K.how,via:cx(K)}:{}};if(I.req.query("solo")!==void 0&&H!==1)return I.json({...Y,refused:H>1});if(H===0)return I.json(Y);let fe=un=>{for(let _t of x)_t.send(un).catch(()=>{})};if(B<=0)return fe({payload:L}),I.json(Y);let Re=++w,Qr=await new Promise(un=>{let _t={expected:H,received:0,results:[],errors:[],finish:tl=>{clearTimeout(el),A.delete(Re),un({results:_t.results,errors:_t.errors,timedOut:tl})}},el=setTimeout(()=>_t.finish(!0),B);A.set(Re,_t),fe({id:Re,payload:L})});return I.json({...Y,...Qr})}),E.use("/__send-reply",_),E.post("/__send-reply",async I=>{try{let{id:L,results:B,errors:K}=await I.req.json(),H=A.get(L);H&&(H.results.push(...B??[]),H.errors.push(...K??[]),++H.received>=H.expected&&H.finish(!1))}catch{}return I.json({ok:!0})})}E.get("/",w=>w.html(e())),E.post("/__fs/read",async w=>{try{let{path:A}=await w.req.json(),I=await di(A,T);return new Response(new Uint8Array(I),{headers:{"Content-Type":"application/octet-stream"}})}catch(A){let I=Bi(A);return w.json({error:I},400)}}),E.post("/__fs/write",async w=>{try{let A=w.req.query("path");return A?(await Ga(A,new Uint8Array(await w.req.arrayBuffer()),T),w.json({success:!0})):w.json({error:"Missing path"},400)}catch(A){let I=Bi(A);return w.json({error:I},400)}}),E.post("/__fs/list",async w=>{try{let{path:A}=await w.req.json();return w.json(await Xa(A??".",T))}catch(A){return w.json({error:Bi(A)},400)}}),E.post("/__fs/remove",async w=>{try{let{path:A}=await w.req.json();return await Qa(A,T),w.json({success:!0})}catch(A){return w.json({error:Bi(A)},400)}}),E.post("/__api/:name",async w=>{try{let A=w.req.param("name"),I=Xc(a?.(),A);if(!I)return w.json({error:`API function '${A}' not found`},404);let{args:L}=await w.req.json();if(Qc(I))return Vc(w,I(...L||[]));let B=await I(...L||[]);return w.json({result:B})}catch(A){let I=Bi(A);return w.json({error:I},500)}}),E.post("/__ai",async w=>{try{let{messages:A,system:I,effort:L,provider:B,model:K,webSearch:H,stream:Be}=await w.req.json();if(!A||!Array.isArray(A)||A.length===0)return w.json({message:"messages array is required",code:"unknown",retryable:!1},400);let Y=St(B,K);if(typeof Y=="string")return w.json({message:Y,code:"unknown",retryable:!1},400);let fe=await Ht(Y,{messages:A,system:I,effort:L,webSearch:H,signal:w.req.raw.signal});if(!fe.ok){let un=await xr(fe,Y.protocol);return w.json(un,fe.status)}if(Be)return Vc(w,_n(fe,Y.protocol));let{text:Re,usage:Qr}=await Er(fe,Y.protocol);return Re||console.warn("[tb.ai] Empty response from provider"),w.json({text:Re,usage:Qr})}catch(A){return w.json(Di(A),500)}}),E.post("/__infer",async w=>{try{let{data:A}=await w.req.json().catch(()=>({})),I=c?.();if(!I?.infer.trim())return w.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let L=St();if(typeof L=="string")return w.json({message:L,code:"unknown",retryable:!1},400);let B=Array.isArray(A)?A.map(String):[],K=Zd(I,B),H=await Ht(L,{messages:[{role:"user",content:K}],signal:w.req.raw.signal});if(!H.ok){let Y=await xr(H,L.protocol);return w.json(Y,H.status)}let Be=(async function*(){let Y="";for await(let Re of _n(H,L.protocol))Re.kind!=="text"||!Re.text||(Y+=Re.text,yield{kind:"delta",text:Re.text});let fe=ef(Y);if(fe.parsed===void 0)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
2935
+ `+Y.slice(-4e3)),new Le("LLM output is not valid JSON","parse_error",!0);fe.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",fe.fixesApplied.join(", ")),yield{kind:"complete",insight:fe.parsed,data:B,fixesApplied:fe.fixesApplied}})();return Vc(w,Be)}catch(A){return w.json(Di(A),500)}}),E.post("/__infer-save",async w=>{try{if(!l)return w.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let A=ox(await w.req.json().catch(()=>({})));return Object.keys(A).length?(await l(A.data,ux(A,"insight")?JSON.stringify(A.insight,null,2):void 0),w.json({ok:!0})):w.json({message:"Nothing to save \u2014 this page holds no runtime state.",code:"unknown",retryable:!1},400)}catch(A){return w.json(Di(A),500)}}),E.get("/__infer-info",w=>{let A=c?.(),I=es(A?.config??"").inference,L=Ho(A?.data??""),B=!!A?.infer.trim(),K=St();return typeof K=="string"?w.json({error:K,inference:I,data:L,hasInfer:B}):w.json({provider:K.protocol,model:K.model,inference:I,data:L,hasInfer:B})}),E.use("/__tb-decode",_),E.post("/__tb-decode",async w=>{let{hash:A}=await w.req.json().catch(()=>({})),I=typeof A=="string"?nf(A):void 0;return w.json(I??{error:"invalid fragment"})}),E.use("/__tb-encode",_),E.post("/__tb-encode",async w=>{let A=Number(w.req.header("content-length"));if(Number.isFinite(A)&&A>ax)return w.json({hash:""});let I=await w.req.text().catch(()=>"");if(I.length>ax)return w.json({hash:""});let L;try{L=JSON.parse(I)}catch{return w.json({hash:""})}return w.json({hash:tf(ox(L))})}),E.get("/__infer-ui.js",w=>w.body(sx,200,{"Content-Type":"text/javascript; charset=utf-8"})),E.get("/__models",async w=>{try{let A=await vt();return w.json(A)}catch{return w.json([],200)}}),E.get("/__ai-access",async w=>{try{return w.json(await Aa())}catch{return w.json("none",200)}}),m&&E.get("/__source/*",async w=>{let A=await Jp.readFile(m,"utf-8").catch(()=>{});return A===void 0?w.text("Not Found",404):new Response(A,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let xe=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],de=new Yc;E.get("/proxy/*",async w=>{let A=new URL(w.req.url),L=(A.pathname+A.search).slice(7),B=L.lastIndexOf("https://");return B===-1?w.text("Invalid proxy URL",400):be(w,L.slice(B))}),f&&lx(E,`/local/${f.name}/`,f.serveDir),p&&lx(E,p.mount,p.dir),h&&E.get("/assets/*",async w=>{let{pathname:A}=new URL(w.req.url),I=A.slice(8),L;try{L=decodeURIComponent(I)}catch{return w.text("Not Found",404)}let B=yh(L);if(B)return w.text(`${B} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{let H=await px(L,h.dir,{"Cache-Control":"no-cache"});if(H)return H}catch{return w.text("Not Found",404)}let K=h.remoteBase;return K?w.redirect(K+I,302):w.text("Not Found",404)});async function be(w,A){let I;try{I=new URL(A)}catch{return w.text("Invalid URL",400)}if(I.protocol!=="https:")return w.text("HTTPS only",400);if(!xe.includes(I.hostname))return w.text("Host not allowed",403);let L=await de.get(A);if(L)return new Response(L.body,{status:200,headers:qp(L.contentType,L.cacheControl)});try{let B=await fetch(A,{headers:{Accept:w.req.header("Accept")||"*/*"},redirect:"follow"});if(!B.ok)return w.text(`Upstream ${B.status}`,B.status);let K=B.headers.get("Content-Type")||void 0,H=B.headers.get("Cache-Control")||void 0;if(B.body){let[Be,Y]=B.body.tee();return(async()=>{try{let fe=await new Response(Y).arrayBuffer();await de.set(A,{body:Buffer.from(fe),contentType:K,cacheControl:H})}catch{}})(),new Response(Be,{status:B.status,headers:qp(K,H)})}return new Response(null,{status:B.status,headers:qp(K,H)})}catch(B){return w.text(`Proxy fetch failed: ${B instanceof Error?B.message:B}`,502)}}(i||o)&&(E.get("/__reload",w=>UL(w,async A=>{let I=w.req.query("bulb")||void 0;if(g&&I&&I!==g){M.has(I)||(M.add(I),console.log(ot.closed("foreign"))),await A.writeSSE({event:"close",data:"foreign"});return}let L=()=>{A.writeSSE({event:"reload",data:""})};i?.on("reload",L);let B=()=>i?.removeListener("reload",L),K=w.req.query("relay")||void 0,H={inEditor:YL(w.req.header("user-agent")),doc:K,open:Y=>A.writeSSE({event:"open-url",data:Y}),send:Y=>A.writeSSE({event:"message",data:JSON.stringify(Y)}),close:Y=>(B(),x.closing(H),console.log(ot.closed(Y)),A.writeSSE({event:"close",data:Y}))},Be=!!K&&!F.has(K);for(K&&F.add(K),x.add(H,Be),A.onAbort(()=>{B(),x.dropped(H)}),await A.writeSSE({event:"hello",data:C,retry:bf});!A.aborted;)await A.sleep(3e4)})),E.use("/__open",_),E.post("/__open",async w=>{let A="";try{A=String((await w.req.json()).url??"")}catch{}if(!zL(A))return w.json({error:"a local http URL is required"},400);let I=[...x].find(L=>L.inEditor);return await I?.open(A),w.json({opened:!!I,pages:x.count})})),E.use("/__stop",_),E.post("/__stop",async w=>{if(w.req.header("sec-fetch-site")||w.req.header("origin"))return w.text("Forbidden: browser request",403);let A="close";try{let L=await w.req.json();(L?.pages==="keep"||L?.pages==="close")&&(A=L.pages)}catch{}let I=A==="close"?await x.closeAll("stopped"):{told:0,gone:0};return b&&setTimeout(()=>{b({pages:A})},50),w.json({closed:I.gone,stuck:I.told-I.gone,exiting:!!b})}),E.get("/__pages",w=>w.json({pages:x.count})),E.notFound(async w=>{if(w.req.method!=="GET")return w.text("Not Found",404);let A=new URL(w.req.url);return ix(A.pathname,A.search)?be(w,"https://esm.sh"+A.pathname+A.search):w.text("Not Found",404)});let ln=FL({fetch:E.fetch,port:s,hostname:JL});return ln.listening||await new Promise((w,A)=>{let I=L=>A(L);ln.once("error",I),ln.once("listening",()=>{ln.removeListener("error",I),w()})}),{port:s,close:()=>ln.close(),requestPage:ye,closePages:w=>x.closeAll(w),pageCount:()=>x.count}}function qp(t,e){let n=new Headers;return t&&n.set("Content-Type",t),e&&n.set("Cache-Control",e),n.set("Access-Control-Allow-Origin","*"),n.set("Cross-Origin-Resource-Policy","cross-origin"),n}function lx(t,e,n){t.get(`${e}*`,async r=>{let{pathname:s}=new URL(r.req.url);if(!s.startsWith(e))return r.text("Not Found",404);try{return await px(decodeURIComponent(s.slice(e.length)),n)??r.text("Not Found",404)}catch{return r.text("Not Found",404)}})}async function px(t,e,n={}){let r=Ir(t,e),s=await Jp.readFile(r).catch(()=>{});if(s)return new Response(s,{headers:{"Content-Type":gh(r),...n}})}$e();vn();async function Zc(t){let{port:e,portNote:n,makeServerOptions:r,makeEntry:s,displayName:i,waitTarget:o,stopLog:a}=t,c=`http://localhost:${e}`,l=s(e,c),f=[],u,d=!1,p=async m=>{if(!d){d=!0,console.log(`
2936
2936
  Shutting down...`),(m?.pages??(we(l)?"keep":"close"))==="close"&&await u?.closePages("stopped"),u?.close();for(let g of f)try{await g()}catch{}a(),await Sn(process.pid),process.exit(0)}},h=await fx({...r(e),onStop:p}).catch(async m=>{if(m?.code!=="EADDRINUSE")throw m;return bd(e)});return u=h,await Td(l),console.log(`
2937
2937
  ${i}`),console.log(` ${c}`),n&&console.log(` ${n}`),process.on("SIGINT",()=>{p()}),process.on("SIGTERM",()=>{p()}),{port:e,url:c,pageCount:()=>h.pageCount(),async handOver({mode:m,fresh:g,replacedLive:b}){if(m==="none")return;let C={fresh:g,external:b?"never":m==="window"?"force":"follow"},T=await h.requestPage(C);T.how==="attached"?console.log(` Reusing the open browser tab.
2938
2938
  `):T.how==="editor"?console.log(` Opened in VS Code via ${T.via}.
@@ -2940,12 +2940,12 @@ Shutting down...`),(m?.pages??(we(l)?"keep":"close"))==="close"&&await u?.closeP
2940
2940
  `):console.log(` ${T.how==="unreached"?`Opened ${T.via?`in VS Code via ${T.via}`:"in your browser"}, but no page attached \u2014 is the browser it opened in still there?`:we(l)?"No page opened \u2014 nothing is reading this mirror until someone opens it.":"No page opened \u2014 no agent mirror page to open one through, and a bulb runs in its page."}
2941
2941
  Share ${c}, and wake on the arrival:
2942
2942
  typebulb wait ${o} --match "${ot.connected}"
2943
- `)},onCleanup(m){f.push(m)}}}vn();import GL from"chokidar";import hx from"node:fs";import XL from"node:path";var QL={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function an(t){let{target:e,onChange:n,events:r="change",debounceMs:s=150}=t,i,o=GL.watch(e,QL);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(n,s)};return r==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}var ZL=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase()==="assets":t==="assets";function mx(t,e,n=150){let r,s=()=>{r&&clearTimeout(r),r=setTimeout(e,n)};try{let i=hx.watch(t,{recursive:!0},(o,a)=>{a&&ZL(a.split(/[\\/]/)[0])&&s()});return i.on("error",o=>console.warn(`watch: ${o instanceof Error?o.message:o} \u2014 continuing`)),()=>{r&&clearTimeout(r),i.close()}}catch{let i=XL.join(t,"assets");return hx.existsSync(i)?an({target:i,onChange:e,events:"all",debounceMs:n}):()=>{}}}$e();Ue();Rr();async function gx(t,e,n,r){e.port!==void 0&&(console.error("--port isn't supported when running a bulb: a bulb keeps its assigned project port across runs, and moving it strands the open tab."),console.error("It applies to `typebulb agent`. Run the bulb with no --port; `typebulb logs` prints the URL it kept."),process.exit(1));let s=process.cwd(),i=Ks(process.pid),o=e.watch?new eM:void 0,a=ve(e.mode),c=(await wn(process.cwd()))(t),l=await dr({kind:"bulb",file:t},process.cwd()),f=await ba(t,l);f.length&&console.log(`Replacing the running server for this bulb (pid ${f.map(ie=>ie.pid).join(", ")})`);let u=f.length>0||Date.now()-c<Jw,{port:d,note:p}=await pa({target:{kind:"bulb",file:t},cwd:process.cwd()});l!==void 0&&d!==l&&u&&(console.error(`
2943
+ `)},onCleanup(m){f.push(m)}}}vn();import XL from"chokidar";import hx from"node:fs";import QL from"node:path";var ZL={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function an(t){let{target:e,onChange:n,events:r="change",debounceMs:s=150}=t,i,o=XL.watch(e,ZL);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(n,s)};return r==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}var eM=t=>process.platform==="win32"||process.platform==="darwin"?t.toLowerCase()==="assets":t==="assets";function mx(t,e,n=150){let r,s=()=>{r&&clearTimeout(r),r=setTimeout(e,n)};try{let i=hx.watch(t,{recursive:!0},(o,a)=>{a&&eM(a.split(/[\\/]/)[0])&&s()});return i.on("error",o=>console.warn(`watch: ${o instanceof Error?o.message:o} \u2014 continuing`)),()=>{r&&clearTimeout(r),i.close()}}catch{let i=QL.join(t,"assets");return hx.existsSync(i)?an({target:i,onChange:e,events:"all",debounceMs:n}):()=>{}}}$e();Ue();Rr();async function gx(t,e,n,r){e.port!==void 0&&(console.error("--port isn't supported when running a bulb: a bulb keeps its assigned project port across runs, and moving it strands the open tab."),console.error("It applies to `typebulb agent`. Run the bulb with no --port; `typebulb logs` prints the URL it kept."),process.exit(1));let s=process.cwd(),i=Ks(process.pid),o=e.watch?new tM:void 0,a=ve(e.mode),c=(await wn(process.cwd()))(t),l=await dr({kind:"bulb",file:t},process.cwd()),f=await ba(t,l);f.length&&console.log(`Replacing the running server for this bulb (pid ${f.map(ie=>ie.pid).join(", ")})`);let u=f.length>0||Date.now()-c<Jw,{port:d,note:p}=await pa({target:{kind:"bulb",file:t},cwd:process.cwd()});l!==void 0&&d!==l&&u&&(console.error(`
2944
2944
  Port ${l} is this bulb's, and a page of it may be waiting there, but something else took it.`),console.error("Free that port and relaunch; starting elsewhere would leave that page running with no way to reach it."),process.exit(1));let h=0,m=()=>console.log(Ed(++h));m(),console.log(`Loading ${Wn.basename(t)}...`);let{html:g,bulb:b,serverExports:C}=await kf(t,e.watch,e.trust,r);Kt(a,t,b.server);let T=Nn(t),E=Nr(Wn.resolve(t)),R=e.trust?void 0:yr(b),{port:O,onCleanup:_,handOver:x,pageCount:M}=await Zc({port:d,portNote:p,displayName:b.name,stopLog:i,makeServerOptions:ie=>({getHtml:()=>g,basePath:s,fsBase:$r(t),port:ie,reloadEmitter:o,sendChannel:!0,getServerExports:()=>C,getBulbBlocks:()=>({infer:b.infer,insight:b.insight,code:b.code,config:b.config,data:b.data}),saveInferenceResult:async(ye,xe)=>{let de=await cn.readFile(t,"utf-8");ye!==void 0&&(de=Zr(de,"data",ye.join(gy))),xe!==void 0&&(de=Zr(de,"insight",xe)),await cn.writeFile(t,de)},localOverride:r?{name:r.name,serveDir:r.serveDir}:void 0,bulbAssets:{dir:T,remoteBase:E&&zi(E.userSlug,E.slug)},sourceFile:t,bulbKey:Js(t),trusted:e.trust,trustHint:n}),makeEntry:(ie,ye)=>({pid:process.pid,port:ie,url:ye,file:t,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,mode:e.mode,predicted:R,watch:e.watch?void 0:!1,replace:e.local?`${e.local.name}=${e.local.dir}`:void 0}),waitTarget:Wn.relative(process.cwd(),t)||Wn.basename(t)});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(R?` trust: restricted \u2014 this bulb appears to use ${R}; re-run with --trust to enable it:
2945
2945
  ${n}
2946
2946
  `:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
2947
2947
  `),e.watch&&console.log(` Watching for changes...
2948
- `);let F,ee,q=()=>{M()===0&&console.log(" No page attached \u2014 nothing reloaded; this change is not live."),o?.emit("reload")},ue=ie=>{console.log(ie),m(),q()};if(e.watch&&o){let ie=0,ye=Promise.resolve();if(F=an({target:t,onChange:()=>{let de=++ie;ye=ye.then(async()=>{if(de===ie)try{console.log("Recompiling...");let be=await kf(t,!0,e.trust,r);g=be.html,C=be.serverExports,b=be.bulb,be.buildError||m(),q()}catch(be){console.error("Recompile failed:",be)}})}}),r){let{name:de,serveDir:be}=r;ee=an({target:be,events:"all",onChange:()=>ue(`Local package '${de}' changed.`)})}let xe=$r(t);await cn.stat(xe).then(de=>de.isDirectory()).catch(()=>!1)&&_(mx(xe,()=>ue("Assets changed.")))}F&&_(F),ee&&_(ee),_(()=>cn.rm(Sf(t),{force:!0})),await x({mode:e.open,fresh:!u,replacedLive:f.some(ie=>ie.port===O)})}tt();import{readFileSync as Kp,copyFileSync as nM,existsSync as rM,writeFileSync as sM,renameSync as iM,rmSync as oM}from"fs";import*as me from"path";import{fileURLToPath as aM}from"url";import{EventEmitter as cM}from"events";import lM from"open";vn();$e();Rr();var Wp=t=>`/agents/${t}/client.js`,tM=`
2948
+ `);let F,ee,q=()=>{M()===0&&console.log(" No page attached \u2014 nothing reloaded; this change is not live."),o?.emit("reload")},ue=ie=>{console.log(ie),m(),q()};if(e.watch&&o){let ie=0,ye=Promise.resolve();if(F=an({target:t,onChange:()=>{let de=++ie;ye=ye.then(async()=>{if(de===ie)try{console.log("Recompiling...");let be=await kf(t,!0,e.trust,r);g=be.html,C=be.serverExports,b=be.bulb,be.buildError||m(),q()}catch(be){console.error("Recompile failed:",be)}})}}),r){let{name:de,serveDir:be}=r;ee=an({target:be,events:"all",onChange:()=>ue(`Local package '${de}' changed.`)})}let xe=$r(t);await cn.stat(xe).then(de=>de.isDirectory()).catch(()=>!1)&&_(mx(xe,()=>ue("Assets changed.")))}F&&_(F),ee&&_(ee),_(()=>cn.rm(Sf(t),{force:!0})),await x({mode:e.open,fresh:!u,replacedLive:f.some(ie=>ie.port===O)})}tt();import{readFileSync as Kp,copyFileSync as rM,existsSync as sM,writeFileSync as iM,renameSync as oM,rmSync as aM}from"fs";import*as me from"path";import{fileURLToPath as cM}from"url";import{EventEmitter as lM}from"events";import uM from"open";vn();$e();Rr();var Wp=t=>`/agents/${t}/client.js`,nM=`
2949
2949
  (() => {
2950
2950
  const api = async (name, ...args) => {
2951
2951
  const resp = await fetch('/__api/' + name, {
@@ -3000,18 +3000,18 @@ ${i}
3000
3000
  ${o?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
3001
3001
 
3002
3002
  <script>
3003
- ${tM}
3003
+ ${nM}
3004
3004
  </script>
3005
3005
 
3006
3006
  <script type="module" src="${c}"></script>
3007
3007
  </body>
3008
3008
  </html>`}async function bx(t){let e=process.cwd(),n=t.agentTarget;ek(n)||(console.error(`Unknown agent '${n}'. Known: ${zr().join(", ")}.`),process.exit(1));let r=await ya(e,n);if(r){console.log(`Mirror '${n}' is already running for this project:
3009
- ${r.url}`),t.open==="window"&&await lM(r.url);return}let s=Ks(process.pid),i=t.watch?new cM:void 0,o=ve(t.mode),a=await tk(n),c=a.displayName||`${n} mirror`;Kt(o,me.join(e,"mirror"));let l=me.dirname(aM(import.meta.url)),f=me.join(l,"agents",n),u=me.join(l,"..","cli","agents"),d=me.join(f,"styles.css"),p=me.join(f,"katex.min.css"),h=me.join(f,"index.html"),m=()=>yx({name:c,agent:n,styles:Kp(d,"utf8"),katex:Kp(p,"utf8"),mountHtml:Kp(h,"utf8"),watch:t.watch}),{port:g,note:b}=await pa({explicit:t.port,target:{kind:"mirror",agent:n},cwd:e}),{port:C,url:T,onCleanup:E,handOver:R,pageCount:O}=await Zc({port:g,portNote:b,displayName:c,stopLog:s,waitTarget:"agent",makeServerOptions:q=>({getHtml:m,basePath:e,port:q,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${me.posix.dirname(Wp(n))}/`,dir:f}}),makeEntry:(q,ue)=>({pid:process.pid,port:q,url:ue,file:`agent:${n}`,cwd:e,startedAt:Date.now(),trust:!0,agent:n})}),_=me.join(u,n,"client"),x=me.join(u,"core","client"),M=rM(_);t.watch&&M&&console.log(` Watching for changes...
3010
- `);async function F(){let q=await import("esbuild"),{outputFiles:ue}=await q.build({entryPoints:[me.join(_,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:me.join(f,"client.js"),write:!1}),ie=me.join(f,"client.js"),ye=`${ie}.${process.pid}.tmp`;sM(ye,ue[0].contents);for(let xe=1;;xe++)try{iM(ye,ie);break}catch(de){if(xe===10)throw oM(ye,{force:!0}),de;await new Promise(be=>setTimeout(be,50))}for(let xe of["styles.css","index.html","typebulb.png","typebulb-inv.png"])nM(me.join(x,xe),me.join(f,xe))}let ee;if(t.watch&&M&&i){let q=!1;ee=an({target:u,events:"all",onChange:async()=>{if(!q){q=!0;try{await F(),console.log(O()?`Mirror rebuilt. Reloading.
3009
+ ${r.url}`),t.open==="window"&&await uM(r.url);return}let s=Ks(process.pid),i=t.watch?new lM:void 0,o=ve(t.mode),a=await tk(n),c=a.displayName||`${n} mirror`;Kt(o,me.join(e,"mirror"));let l=me.dirname(cM(import.meta.url)),f=me.join(l,"agents",n),u=me.join(l,"..","cli","agents"),d=me.join(f,"styles.css"),p=me.join(f,"katex.min.css"),h=me.join(f,"index.html"),m=()=>yx({name:c,agent:n,styles:Kp(d,"utf8"),katex:Kp(p,"utf8"),mountHtml:Kp(h,"utf8"),watch:t.watch}),{port:g,note:b}=await pa({explicit:t.port,target:{kind:"mirror",agent:n},cwd:e}),{port:C,url:T,onCleanup:E,handOver:R,pageCount:O}=await Zc({port:g,portNote:b,displayName:c,stopLog:s,waitTarget:"agent",makeServerOptions:q=>({getHtml:m,basePath:e,port:q,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${me.posix.dirname(Wp(n))}/`,dir:f}}),makeEntry:(q,ue)=>({pid:process.pid,port:q,url:ue,file:`agent:${n}`,cwd:e,startedAt:Date.now(),trust:!0,agent:n})}),_=me.join(u,n,"client"),x=me.join(u,"core","client"),M=sM(_);t.watch&&M&&console.log(` Watching for changes...
3010
+ `);async function F(){let q=await import("esbuild"),{outputFiles:ue}=await q.build({entryPoints:[me.join(_,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:me.join(f,"client.js"),write:!1}),ie=me.join(f,"client.js"),ye=`${ie}.${process.pid}.tmp`;iM(ye,ue[0].contents);for(let xe=1;;xe++)try{oM(ye,ie);break}catch(de){if(xe===10)throw aM(ye,{force:!0}),de;await new Promise(be=>setTimeout(be,50))}for(let xe of["styles.css","index.html","typebulb.png","typebulb-inv.png"])rM(me.join(x,xe),me.join(f,xe))}let ee;if(t.watch&&M&&i){let q=!1;ee=an({target:u,events:"all",onChange:async()=>{if(!q){q=!0;try{await F(),console.log(O()?`Mirror rebuilt. Reloading.
3011
3011
  `:`Mirror rebuilt. No tab open on it \u2014 nobody is reading this.
3012
3012
  `),i.emit("reload")}catch(ue){console.error("Mirror rebuild failed:",ue instanceof Error?ue.message:ue)}finally{q=!1}}}})}await R({mode:t.open,fresh:!1,replacedLive:!1}),E(()=>a.shutdownSwitcher?.()),E(()=>a.shutdownComposer?.()),ee&&E(ee)}tt();Tt();import*as wx from"path";async function vx(t,e,n,r){let s=ve(n),i=!1,o=async()=>{let{bulb:a,config:c}=await st(t);i||(Kt(s,t,a.server),i=!0),await fi(a.server,t,r,c.dependencies)};if(console.log(`Running ${wx.basename(t)}...`),await o(),e){console.log(`Watching for changes...
3013
- `);let a=0,c=Promise.resolve();an({target:t,onChange:()=>{let l=++a;c=c.then(async()=>{if(l===a)try{console.log("Re-running..."),await o()}catch(f){console.error("Error:",f)}})}})}}tt();Tt();import{Console as uM}from"node:console";$e();async function xx(t,e,n,r){mM();try{let d=kn(await Q(),t)[0];d&&(Ws(d.pid,Ze(d.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${d.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let s=ve(n),{bulb:i,config:o}=await st(t);i.server||ji("This bulb has no **server.ts** block; nothing to call."),Kt(s,t,i.server);let a;try{a=await fi(i.server,t,r,o.dependencies)}catch(d){ji(d instanceof Error?d.message:String(d))}let c=Xc(a,e.fn);if(!c){let d=[...Object.keys(a).filter(p=>typeof a[p]=="function"),...Object.keys(Gc)];ji(`Function '${e.fn}' not found. Available: ${d.length?d.join(", "):"(none)"}.`)}let l=await dM(e);if(Qc(c)){try{for await(let d of c(...l))await kx(JSON.stringify(d,Ex)+`
3014
- `)}catch(d){ji(d instanceof Error?d.stack??d.message:String(d))}return Sx(0)}let f;try{f=await c(...l)}catch(d){ji(d instanceof Error?d.stack??d.message:String(d))}let u=hM(f);u!==void 0&&await kx(u+`
3015
- `),Sx(0)}function Sx(t){process.exitCode=t,setTimeout(()=>process.exit(t),2e3).unref?.()}async function dM(t){if(t.hasArgsFlag){let e=t.argsJson??"";return e==="-"&&(e=await Xr()),pM(e)}return fM(t.positional)}function fM(t){return t.map(e=>{try{return JSON.parse(e)}catch{return e}})}function pM(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`--args must be a JSON array: ${n instanceof Error?n.message:String(n)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function hM(t){if(t!==void 0)return JSON.stringify(t,Ex,2)}function Ex(t,e){return typeof e=="bigint"?e.toString():e}function ji(t){process.stderr.write(t+`
3016
- `),process.exit(1)}function mM(){let t=new uM(process.stderr,process.stderr);console.log=t.log.bind(t),console.info=t.info.bind(t),console.debug=t.debug.bind(t),console.dir=t.dir.bind(t)}function kx(t){return new Promise((e,n)=>{process.stdout.write(t,r=>r?n(r):e())})}ha();for(let t of[process.stdout,process.stderr])t.on("error",e=>{if(e?.code!=="EPIPE")throw e});function Ax(t,e){t||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
3017
- ${e}`),process.exit(1))}async function gM(){let t=sk(process.argv.slice(2));if(t.version&&(console.log(`typebulb ${Pe}`),process.exit(0)),t.help&&(ik(),process.exit(0)),nk(),t.subcommand==="logs"){await Bk(t.file||void 0,{follow:t.follow,clear:t.clear,run:t.run,lines:t.lines});return}if(t.subcommand==="wait"){await jk(t.file||void 0,{match:t.match,timeoutSec:t.timeoutSec,wake:t.wake});return}if(t.subcommand==="stop"){t.stopScope?await qk(t.stopScope):await Uk(t.file||void 0);return}if(t.subcommand==="restart"){await Jk(t.file||void 0,t.stopScope);return}if(t.subcommand==="babysit"){await rx(t.mode,t.slowMs);return}if(t.subcommand==="send"){await Kk(t.file,t.sendMessage,t.sendWaitMs??0);return}if(t.subcommand==="models"){await Rk(t.mode);return}if(t.subcommand==="slug"){Ik(t.slugName);return}if(t.subcommand==="status"){await Qk(t.statusQuery,t.mode,t.slowMs);return}if(t.subcommand==="pull"){await ev(t.file||void 0,{force:t.force,mode:t.mode});return}if(t.subcommand==="push"){await nv(t.file||void 0,{force:t.force,mode:t.mode});return}if(t.subcommand==="agent"){await(t.agentTarget?bx(t):_k(Pe));return}if(t.subcommand==="trust"||t.subcommand==="untrust"){await Tk(t.file||void 0,t.subcommand==="trust");return}let e;if(!t.file||t.file==="."){let c=await Qw(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Pt.resolve(t.file);if(await Tx.access(e).then(()=>!0,()=>!1)||(zr().includes(t.file)&&(console.error(`To open the ${t.file} agent mirror, run: npx typebulb agent:${t.file}`),process.exit(1)),console.error(`File not found: ${e}`+(Pt.isAbsolute(t.file)?"":` (resolved from cwd ${process.cwd()})`)),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),t.subcommand==="get"){await zk(e,t.blockKind);return}if(t.subcommand==="put"){await Gk(e,t.blockPairs);return}let r=t.file&&t.file!=="."?t.file:Pt.relative(process.cwd(),e)||Pt.basename(e),s=`npx typebulb --trust ${r.includes(" ")?`"${r}"`:r}`;if(t.subcommand==="predict"){await Ak(e,s);return}let i=!t.noTrust&&Tn(e);i&&!t.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),t.trust=t.noTrust?!1:t.trust||i;let o;try{o=await st(e)}catch{}let a;if(t.local){o&&!(t.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${t.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&t.subcommand!=="call"&&(!o.bulb.code||t.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await eh(t.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Pt.relative(process.cwd(),a.dir)||"."}`)}if(t.subcommand==="check"){await Ek(e,a);return}if(t.subcommand==="call"){Ax(t.trust,s),await xx(e,{fn:t.fn,positional:t.callArgs,argsJson:t.argsJson,hasArgsFlag:t.hasArgsFlag},t.mode,a);return}if(o&&o.bulb.server&&(wa(o.bulb)||t.server)){Ax(t.trust,s),await vx(e,t.watch,t.mode,a);return}await gx(e,t,s,a)}gM().catch(t=>{console.error("Error:",t.message),process.exit(1)});
3013
+ `);let a=0,c=Promise.resolve();an({target:t,onChange:()=>{let l=++a;c=c.then(async()=>{if(l===a)try{console.log("Re-running..."),await o()}catch(f){console.error("Error:",f)}})}})}}tt();Tt();import{Console as dM}from"node:console";$e();async function xx(t,e,n,r){gM();try{let d=kn(await Q(),t)[0];d&&(Ws(d.pid,Ze(d.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${d.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let s=ve(n),{bulb:i,config:o}=await st(t);i.server||ji("This bulb has no **server.ts** block; nothing to call."),Kt(s,t,i.server);let a;try{a=await fi(i.server,t,r,o.dependencies)}catch(d){ji(d instanceof Error?d.message:String(d))}let c=Xc(a,e.fn);if(!c){let d=[...Object.keys(a).filter(p=>typeof a[p]=="function"),...Object.keys(Gc)];ji(`Function '${e.fn}' not found. Available: ${d.length?d.join(", "):"(none)"}.`)}let l=await fM(e);if(Qc(c)){try{for await(let d of c(...l))await kx(JSON.stringify(d,Ex)+`
3014
+ `)}catch(d){ji(d instanceof Error?d.stack??d.message:String(d))}return Sx(0)}let f;try{f=await c(...l)}catch(d){ji(d instanceof Error?d.stack??d.message:String(d))}let u=mM(f);u!==void 0&&await kx(u+`
3015
+ `),Sx(0)}function Sx(t){process.exitCode=t,setTimeout(()=>process.exit(t),2e3).unref?.()}async function fM(t){if(t.hasArgsFlag){let e=t.argsJson??"";return e==="-"&&(e=await Xr()),hM(e)}return pM(t.positional)}function pM(t){return t.map(e=>{try{return JSON.parse(e)}catch{return e}})}function hM(t){let e;try{e=JSON.parse(t)}catch(n){throw new Error(`--args must be a JSON array: ${n instanceof Error?n.message:String(n)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function mM(t){if(t!==void 0)return JSON.stringify(t,Ex,2)}function Ex(t,e){return typeof e=="bigint"?e.toString():e}function ji(t){process.stderr.write(t+`
3016
+ `),process.exit(1)}function gM(){let t=new dM(process.stderr,process.stderr);console.log=t.log.bind(t),console.info=t.info.bind(t),console.debug=t.debug.bind(t),console.dir=t.dir.bind(t)}function kx(t){return new Promise((e,n)=>{process.stdout.write(t,r=>r?n(r):e())})}ha();for(let t of[process.stdout,process.stderr])t.on("error",e=>{if(e?.code!=="EPIPE")throw e});function Ax(t,e){t||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
3017
+ ${e}`),process.exit(1))}async function yM(){let t=sk(process.argv.slice(2));if(t.version&&(console.log(`typebulb ${Pe}`),process.exit(0)),t.help&&(ik(),process.exit(0)),nk(),t.subcommand==="logs"){await Bk(t.file||void 0,{follow:t.follow,clear:t.clear,run:t.run,lines:t.lines});return}if(t.subcommand==="wait"){await jk(t.file||void 0,{match:t.match,timeoutSec:t.timeoutSec,wake:t.wake});return}if(t.subcommand==="stop"){t.stopScope?await qk(t.stopScope):await Uk(t.file||void 0);return}if(t.subcommand==="restart"){await Jk(t.file||void 0,t.stopScope);return}if(t.subcommand==="babysit"){await rx(t.mode,t.slowMs);return}if(t.subcommand==="send"){await Kk(t.file,t.sendMessage,t.sendWaitMs??0);return}if(t.subcommand==="models"){await Rk(t.mode);return}if(t.subcommand==="slug"){Ik(t.slugName);return}if(t.subcommand==="status"){await Qk(t.statusQuery,t.mode,t.slowMs);return}if(t.subcommand==="pull"){await ev(t.file||void 0,{force:t.force,mode:t.mode});return}if(t.subcommand==="push"){await nv(t.file||void 0,{force:t.force,mode:t.mode});return}if(t.subcommand==="agent"){await(t.agentTarget?bx(t):_k(Pe));return}if(t.subcommand==="trust"||t.subcommand==="untrust"){await Tk(t.file||void 0,t.subcommand==="trust");return}let e;if(!t.file||t.file==="."){let c=await Qw(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=Pt.resolve(t.file);if(await Tx.access(e).then(()=>!0,()=>!1)||(zr().includes(t.file)&&(console.error(`To open the ${t.file} agent mirror, run: npx typebulb agent:${t.file}`),process.exit(1)),console.error(`File not found: ${e}`+(Pt.isAbsolute(t.file)?"":` (resolved from cwd ${process.cwd()})`)),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),t.subcommand==="get"){await zk(e,t.blockKind);return}if(t.subcommand==="put"){await Gk(e,t.blockPairs);return}let r=t.file&&t.file!=="."?t.file:Pt.relative(process.cwd(),e)||Pt.basename(e),s=`npx typebulb --trust ${r.includes(" ")?`"${r}"`:r}`;if(t.subcommand==="predict"){await Ak(e,s);return}let i=!t.noTrust&&Tn(e);i&&!t.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),t.trust=t.noTrust?!1:t.trust||i;let o;try{o=await st(e)}catch{}let a;if(t.local){o&&!(t.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${t.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&t.subcommand!=="call"&&(!o.bulb.code||t.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await eh(t.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${Pt.relative(process.cwd(),a.dir)||"."}`)}if(t.subcommand==="check"){await Ek(e,a);return}if(t.subcommand==="call"){Ax(t.trust,s),await xx(e,{fn:t.fn,positional:t.callArgs,argsJson:t.argsJson,hasArgsFlag:t.hasArgsFlag},t.mode,a);return}if(o&&o.bulb.server&&(wa(o.bulb)||t.server)){Ax(t.trust,s),await vx(e,t.watch,t.mode,a);return}await gx(e,t,s,a)}yM().catch(t=>{console.error("Error:",t.message),process.exit(1)});