typebulb 0.60.4 → 0.60.5

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
@@ -312,7 +312,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
312
312
  `))if(t.trim())try{let r=JSON.parse(t);if(r.type==="turn_context"&&typeof r.payload?.model=="string")return r.payload.model}catch{}}var mT,ys,vu,wT,kT,xT,ET,AT,RT,LT,Ao,Lg,zn,DT,Su=S(()=>{"use strict";ms();bo();mT=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<node_repl_review_evidence>","# AGENTS.md instructions for "];ys=n=>!!n&&typeof n=="object"&&!Array.isArray(n),vu=n=>n==="shell_command"||n==="exec_command",wT=new Set(["max_output_tokens","yield_time_ms","timeout_ms"]);kT=/^(Get-Content|gc|cat|type|nl|bat|sed|head|tail)$/i,xT=/^-(Path|LiteralPath)$/i,ET=/^-(Encoding|TotalCount|Head|Tail|ReadCount|Delimiter)$/i,AT=/^(sed -n|head|tail|Select-Object|select)(\s|$)/i;RT={n:`
313
313
  `,t:" ",r:"\r",b:"\b",f:"\f",v:"\v",0:"\0"};LT=n=>n?n.replace(/\r?\n$/,"").split(`
314
314
  `).length:0;Ao=n=>{let e=hT(n);return process.platform==="win32"?e.toLowerCase():e},Lg=12e4,zn=class extends $t{constructor(t=wu(Ig(),".codex","sessions")){super();this.root=t}displayName="Codex Mirror";#e=0;#l;#t=!1;#i;#m=0;#s=new Map;#d=new Map;#a=new Map;#u=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}detectsInstalled(){return pT(wu(Ig(),".codex"))}sessionsDir(t){return this.root}listSessionFiles(t){let r=Ao(t),s=[];for(let i of this.#o()){let o=0,a=0;try{let d=Eo(i);if(!d.isFile())continue;o=d.size,a=d.mtimeMs}catch{continue}let l=this.#s.get(i);if(l===void 0){if(l=Mg(i),l===void 0)continue;this.#s.set(i,l)}if(l.subagent||Ao(l.cwd)!==r)continue;let c=Rg(i,".jsonl");this.#a.set(c,i),s.push({sessionId:c,file:i,mtime:this.#r(i,o,a)})}return s}listChildren(t,r){let s=Ao(t),i=new Map,o,a;for(let d of this.#o()){let u=0,f=0;try{let g=Eo(d);if(!g.isFile())continue;u=g.size,f=g.mtimeMs}catch{continue}let p=this.#s.get(d);if(p===void 0){if(p=Mg(d),p===void 0)continue;this.#s.set(d,p)}Rg(d,".jsonl")===r&&(o=p.id,a=p.model),!(!p.spawn||Ao(p.cwd)!==s)&&i.set(p.spawn.id,{file:d,mtime:this.#r(d,u,f),running:this.#n(d,u,f),spawn:p.spawn,model:p.model})}if(!o)return[];let l=(d,u=new Set)=>{if(d.parent===o)return!0;if(u.has(d.id))return!1;u.add(d.id);let f=i.get(d.parent);return f?l(f.spawn,u):!1},c=[];for(let{file:d,mtime:u,running:f,spawn:p,model:g}of i.values())l(p)&&c.push({id:p.id,file:d,mtime:u,label:p.path.split("/").filter(Boolean).pop()??p.path,kind:p.role||"agent",model:g&&g!==a?g:void 0,parentId:i.has(p.parent)?p.parent:void 0,depth:p.depth,stopped:!1,running:f});return c}#n(t,r,s){return this.#c(t,r,s).running}sessionsWorking(t){let r=new Set,s=Date.now();for(let{sessionId:i,file:o,mtime:a}of this.listSessionFiles(t)){if(s-a>=Lg)continue;let l;try{let c=Eo(o);l=this.#c(o,c.size,c.mtimeMs)}catch{continue}l.running&&r.add(i)}return r}#r(t,r,s){return Math.max(s,this.#c(t,r,s).ms??0)}#c(t,r,s){let i=this.#d.get(t);if(i&&i.size===r&&i.mtime===s)return i;let o={size:r,mtime:s,...jT(t)};return this.#d.set(t,o),o}#o(){let t=[],r=s=>{try{return fT(s).map(i=>wu(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")&&t.push(a);return t}parseEntry(t){let r;try{r=JSON.parse(t)}catch{return null}return!r||typeof r.type!="string"?null:r}idOf(t){return t.ord===void 0&&(this.#h(t),t.ord=String(this.#e++),t.parent=this.#l,this.#l=t.ord),t.ord}#h(t){let r=t.payload;if(t.type==="session_meta"){if(++this.#m===1){let s=typeof r?.source=="object"?r.source?.subagent?.thread_spawn:void 0;this.#i=s?.agent_path,this.#t=!!s}}else this.#m=0,this.#t&&r?.type==="agent_message"&&r.recipient===this.#i&&(this.#t=!1);t.inherited=this.#t}parentOf(t){return t.parent}timestampOf(t){return t.timestamp}isSidechain(t,r){return r==="child"&&!!t.inherited}isLeafType(t){return!0}isRecoveryNoise(t){return!1}apply(t,r){let s=[],i=t.payload;if(!i)return{events:s};let o=()=>{let a=Date.parse(t.timestamp??"");return!isNaN(a)&&a>=r};if(t.type==="response_item"){if(i.type==="message"){if(i.role==="user"){let a=Vn(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=Vn(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=Vn(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:l,...c}=i.type==="custom_tool_call"?bT(i.name??"",i.input):{name:i.name??"",input:MT(i.arguments)};return l&&this.#u.set(a,l),s.push({type:"assistant",text:"",thinking:"",tools:[{id:a,...c}],live:o()}),{events:s}}if(i.type==="custom_tool_call_output"||i.type==="function_call_output"){let a=i.call_id??"",l=this.#u.get(a);return this.#u.delete(a),s.push({type:"tool_result",id:a,...NT(yT(i.output),l)}),{events:s}}return{events:s}}if(t.type==="event_msg"){if(i.type==="token_count"){let a=i.info?.last_token_usage;if(!a)return{events:s};let l={in:Math.max(0,(a.input_tokens??0)-(a.cached_input_tokens??0)),out:a.output_tokens??0,cached:a.cached_input_tokens??0,cacheCreate:a.cache_write_input_tokens??0};return{events:s,usage:l}}return{events:s}}return t.type==="turn_context"?{events:s,model:i.model}:{events:s}}chainWorking(t){let r=!1;for(let s of t){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(t){let r=this.#a.get(t);if(!r)return;let s;try{let i=Eo(r);s=this.#r(r,i.size,i.mtimeMs)}catch{return}return Date.now()-s<Lg}readPreview(t){for(let r of(Jg(t,256*1024)?.text??"").split(`
315
- `))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"?Vn(i.item.content,!0):void 0)??"").replace(/\s+/g," ").trim();if(a)return a.slice(0,200)}catch{}return""}searchText(t){if(t?.type!=="response_item"||t.payload?.type!=="message")return"";let r=t.payload.role;return r!=="user"&&r!=="assistant"?"":Vn(t.payload.content,r==="user").replace(/\s+/g," ").trim()}};DT=[64*1024,1024*1024]});import{realpathSync as qT}from"fs";import{createHash as JT}from"crypto";import{join as Po,resolve as WT}from"path";import{homedir as KT}from"os";function Mt(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?Po(n,".."):Po(KT(),".typebulb")}function ut(){Wg||(Wg=!0,console.error(`${Mt()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function dt(){return process.env.TYPEBULB_SERVERS_DIR||Po(Mt(),"servers")}function Kg(n){let e=se(n),t=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return Po(Mt(),"canvas",`${t}-${bs(n)}.png`)}function bs(n){return JT("sha1").update(se(n)).digest("hex").slice(0,8)}function se(n){let e=WT(n),t=e;try{t=qT.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Hg(n,e){let t=se(n),r=se(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Wg,nt=S(()=>{"use strict";Wg=!1});import*as zg from"net";import{mkdir as HT,readFile as YT,writeFile as Gg}from"fs/promises";import{existsSync as VT}from"fs";import{join as Xg}from"path";function ey(){return Xg(Mt(),"blocks")}function ku(n){return Xg(ey(),`${n}.json`)}function Co(n){return new Promise(e=>{let t=zg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function QT(n){for(let e=n;e<65535;e++)if(await Co(e))return e;throw new Error(`No free port found above ${n}`)}async function xu(n){let{listBulbServers:e}=await Promise.resolve().then(()=>($e(),ty)),t=(await e()).find(s=>s.port===n),r=t?` (pid ${t.pid}, ${t.agent?`agent:${t.agent}`:t.file})`:"";console.error(`port ${n} in use${r}`),process.exit(1)}async function _o(n){try{let e=JSON.parse(await YT(ku(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Ro(n,e){try{return await Gg(ku(n),JSON.stringify(e,null,2)),!0}catch{return ut(),!1}}async function ZT(n){let e=se(n);try{await HT(ey(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Zg;o++)t.push(Qg+o*an);let r=await Promise.all(t.map(async o=>({base:o,block:await _o(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 Gg(ku(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await _o(o))?.cwd===e)return o;l.code!=="EEXIST"&&ut();continue}if(!VT(a.cwd))return await Ro(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Yg(o.block)-Yg(a.block))[0];if(i)return await Ro(i.base,s)?i.base:void 0}function Yg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function eP(n,e){let t=await _o(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Vg(t),a=o.has(0)?GT:0;for(;a>Oo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Ro(n,t),a}let r=se(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Vg(t);for(s=Oo;s<an&&i.has(s);)s++;if(s>=an){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:Oo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Ro(n,t),s}function Vg(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function Gn(n,e){let t=await ZT(e);return t===void 0?void 0:t+await eP(t,n)}async function ln(n){let e=se(n);for(let t=0;t<Zg;t++){let r=await _o(Qg+t*an);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function Io(n){if(n.explicit!==void 0)return await Co(n.explicit)||await xu(n.explicit),n.target.kind==="bulb"&&await Gn(n.target,n.cwd),{port:n.explicit};let e=await Gn(n.target,n.cwd);if(e!==void 0){let r=e-e%an,s=Date.now()+XT;do{if(await Co(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=Oo;i<an;i++){let o=r+i;if(o!==e&&await Co(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await QT(zT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Qg,an,Zg,zT,Oo,GT,XT,cn=S(()=>{"use strict";nt();Qg=20100,an=100,Zg=19,zT=23e3,Oo=1,GT=an-1,XT=3e3});var Le,No=S(()=>{"use strict";Le="0.60.4"});var ty={};ci(ty,{agentViewerCommand:()=>dy,bulbServerCommand:()=>uy,clearServerLog:()=>Ou,findProjectViewer:()=>Mo,isAlive:()=>Xn,isMirror:()=>me,isProjectBulb:()=>Nu,isProjectMirror:()=>er,launchAgentViewer:()=>Mu,launchBulbServer:()=>Ss,listBulbServers:()=>Q,probePageCount:()=>Lu,readServerLog:()=>Ye,readWaitCursor:()=>Lo,recordDenial:()=>Iu,registerServer:()=>Ru,relayOpen:()=>$u,runMarker:()=>Cu,serverLogPath:()=>Zn,serversForBulb:()=>dn,sliceRunLog:()=>_u,startServerLog:()=>vs,stopBulbServer:()=>Qn,stopServer:()=>Bt,stopServersForBulb:()=>Bo,typebulbBinPath:()=>tr,unregisterServer:()=>un,writeWaitCursor:()=>ws});import{spawn as ny}from"child_process";import{readdir as tP,readFile as iy,writeFile as oy,unlink as Eu,mkdir as nP}from"fs/promises";import{mkdirSync as ay,writeFileSync as $o,appendFileSync as rP,readFileSync as Au}from"fs";import*as Te from"path";import{fileURLToPath as sP}from"url";function Tu(n){return Te.join(dt(),`${n}.json`)}function Zn(n){return Te.join(dt(),`${n}.log`)}function Pu(n){return Te.join(dt(),`${n}.wait.json`)}function ly(n){try{let e=JSON.parse(Au(Pu(n),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Lo(n,e=""){let t=ly(n)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ws(n,e,t=""){try{ay(dt(),{recursive:!0});let r=ly(n);r[t]=e,$o(Pu(n),JSON.stringify({cursors:r}))}catch{}}function vs(n){let e=Zn(n);try{ay(dt(),{recursive:!0}),$o(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(rP(e,l),s+=l.length,s>2*ry){let c=Au(e),d=c.subarray(Math.max(0,c.length-ry));$o(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),t(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=t,process.stderr.write=r}}function Ou(n){try{$o(Zn(n),"")}catch{}}function Ye(n,e=0){try{let t=Au(Zn(n)),r=e>=0&&e<=t.length?e:0;return{text:t.subarray(r).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function Cu(n){return`\u2500\u2500 run ${n} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function oP(n){let e=iP.exec(n);return e?Number(e[1]):void 0}function _u(n,e){let t=n.split(`
315
+ `))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"?Vn(i.item.content,!0):void 0)??"").replace(/\s+/g," ").trim();if(a)return a.slice(0,200)}catch{}return""}searchText(t){if(t?.type!=="response_item"||t.payload?.type!=="message")return"";let r=t.payload.role;return r!=="user"&&r!=="assistant"?"":Vn(t.payload.content,r==="user").replace(/\s+/g," ").trim()}};DT=[64*1024,1024*1024]});import{realpathSync as qT}from"fs";import{createHash as JT}from"crypto";import{join as Po,resolve as WT}from"path";import{homedir as KT}from"os";function Mt(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?Po(n,".."):Po(KT(),".typebulb")}function ut(){Wg||(Wg=!0,console.error(`${Mt()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function dt(){return process.env.TYPEBULB_SERVERS_DIR||Po(Mt(),"servers")}function Kg(n){let e=se(n),t=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return Po(Mt(),"canvas",`${t}-${bs(n)}.png`)}function bs(n){return JT("sha1").update(se(n)).digest("hex").slice(0,8)}function se(n){let e=WT(n),t=e;try{t=qT.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Hg(n,e){let t=se(n),r=se(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Wg,nt=S(()=>{"use strict";Wg=!1});import*as zg from"net";import{mkdir as HT,readFile as YT,writeFile as Gg}from"fs/promises";import{existsSync as VT}from"fs";import{join as Xg}from"path";function ey(){return Xg(Mt(),"blocks")}function ku(n){return Xg(ey(),`${n}.json`)}function Co(n){return new Promise(e=>{let t=zg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function QT(n){for(let e=n;e<65535;e++)if(await Co(e))return e;throw new Error(`No free port found above ${n}`)}async function xu(n){let{listBulbServers:e}=await Promise.resolve().then(()=>($e(),ty)),t=(await e()).find(s=>s.port===n),r=t?` (pid ${t.pid}, ${t.agent?`agent:${t.agent}`:t.file})`:"";console.error(`port ${n} in use${r}`),process.exit(1)}async function _o(n){try{let e=JSON.parse(await YT(ku(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Ro(n,e){try{return await Gg(ku(n),JSON.stringify(e,null,2)),!0}catch{return ut(),!1}}async function ZT(n){let e=se(n);try{await HT(ey(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Zg;o++)t.push(Qg+o*an);let r=await Promise.all(t.map(async o=>({base:o,block:await _o(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 Gg(ku(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await _o(o))?.cwd===e)return o;l.code!=="EEXIST"&&ut();continue}if(!VT(a.cwd))return await Ro(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Yg(o.block)-Yg(a.block))[0];if(i)return await Ro(i.base,s)?i.base:void 0}function Yg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function eP(n,e){let t=await _o(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Vg(t),a=o.has(0)?GT:0;for(;a>Oo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Ro(n,t),a}let r=se(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Vg(t);for(s=Oo;s<an&&i.has(s);)s++;if(s>=an){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:Oo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Ro(n,t),s}function Vg(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function Gn(n,e){let t=await ZT(e);return t===void 0?void 0:t+await eP(t,n)}async function ln(n){let e=se(n);for(let t=0;t<Zg;t++){let r=await _o(Qg+t*an);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function Io(n){if(n.explicit!==void 0)return await Co(n.explicit)||await xu(n.explicit),n.target.kind==="bulb"&&await Gn(n.target,n.cwd),{port:n.explicit};let e=await Gn(n.target,n.cwd);if(e!==void 0){let r=e-e%an,s=Date.now()+XT;do{if(await Co(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=Oo;i<an;i++){let o=r+i;if(o!==e&&await Co(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await QT(zT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Qg,an,Zg,zT,Oo,GT,XT,cn=S(()=>{"use strict";nt();Qg=20100,an=100,Zg=19,zT=23e3,Oo=1,GT=an-1,XT=3e3});var Le,No=S(()=>{"use strict";Le="0.60.5"});var ty={};ci(ty,{agentViewerCommand:()=>dy,bulbServerCommand:()=>uy,clearServerLog:()=>Ou,findProjectViewer:()=>Mo,isAlive:()=>Xn,isMirror:()=>me,isProjectBulb:()=>Nu,isProjectMirror:()=>er,launchAgentViewer:()=>Mu,launchBulbServer:()=>Ss,listBulbServers:()=>Q,probePageCount:()=>Lu,readServerLog:()=>Ye,readWaitCursor:()=>Lo,recordDenial:()=>Iu,registerServer:()=>Ru,relayOpen:()=>$u,runMarker:()=>Cu,serverLogPath:()=>Zn,serversForBulb:()=>dn,sliceRunLog:()=>_u,startServerLog:()=>vs,stopBulbServer:()=>Qn,stopServer:()=>Bt,stopServersForBulb:()=>Bo,typebulbBinPath:()=>tr,unregisterServer:()=>un,writeWaitCursor:()=>ws});import{spawn as ny}from"child_process";import{readdir as tP,readFile as iy,writeFile as oy,unlink as Eu,mkdir as nP}from"fs/promises";import{mkdirSync as ay,writeFileSync as $o,appendFileSync as rP,readFileSync as Au}from"fs";import*as Te from"path";import{fileURLToPath as sP}from"url";function Tu(n){return Te.join(dt(),`${n}.json`)}function Zn(n){return Te.join(dt(),`${n}.log`)}function Pu(n){return Te.join(dt(),`${n}.wait.json`)}function ly(n){try{let e=JSON.parse(Au(Pu(n),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Lo(n,e=""){let t=ly(n)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ws(n,e,t=""){try{ay(dt(),{recursive:!0});let r=ly(n);r[t]=e,$o(Pu(n),JSON.stringify({cursors:r}))}catch{}}function vs(n){let e=Zn(n);try{ay(dt(),{recursive:!0}),$o(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(rP(e,l),s+=l.length,s>2*ry){let c=Au(e),d=c.subarray(Math.max(0,c.length-ry));$o(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),t(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=t,process.stderr.write=r}}function Ou(n){try{$o(Zn(n),"")}catch{}}function Ye(n,e=0){try{let t=Au(Zn(n)),r=e>=0&&e<=t.length?e:0;return{text:t.subarray(r).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function Cu(n){return`\u2500\u2500 run ${n} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function oP(n){let e=iP.exec(n);return e?Number(e[1]):void 0}function _u(n,e){let t=n.split(`
316
316
  `),r=[];if(t.forEach((o,a)=>{let l=oP(o);l!==void 0&&r.push({id:l,idx:a})}),!r.length)return e==="latest"?n:"";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 t.slice(s.idx,i?i.idx:t.length).join(`
317
317
  `)}function Xn(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function Ru(n){try{await nP(dt(),{recursive:!0}),await oy(Tu(n.pid),JSON.stringify({version:Le,...n}))}catch{ut()}}async function Iu(n,e){let t=Tu(n);try{let r=JSON.parse(await iy(t,"utf8"));if(r.denied===e)return;r.denied=e,await oy(t,JSON.stringify(r))}catch{}}async function un(n){await Eu(Tu(n)).catch(()=>{}),await Eu(Zn(n)).catch(()=>{}),await Eu(Pu(n)).catch(()=>{})}function me(n){return n.agent!=null}function er(n,e){return me(n)&&n.cwd!=null&&se(n.cwd)===se(e)}function Nu(n,e){return!me(n)&&Hg(n.file,e)}async function Q(n){let e;try{e=await tP(dt())}catch{return[]}let t=[];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 iy(Te.join(dt(),s),"utf8"))}catch{await un(i);return}o&&typeof o.pid=="number"&&Xn(o.pid)?t.push(o):await un(i)})),(n?t.filter(s=>Nu(s,n)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Mo(n,e){return(await Q()).find(t=>er(t,n)&&(e?t.agent===e:!0))}async function $u(n,e){let t=new URL(n).port,r=(await Q()).filter(a=>String(a.port)!==t),s=r.filter(a=>er(a,e)),i=r.filter(a=>Nu(a,e)),o=0;for(let a of[...s,...i])try{let l=await fetch(`${a.url}/__open`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n}),signal:AbortSignal.timeout(2e3)});if(!l.ok)continue;let{opened:c,pages:d}=await l.json();if(c)return{where:"editor",via:a.agent?"the agent mirror":`${Te.basename(a.file)}'s page`};me(a)&&(o+=d??0)}catch{}return o>0?{where:"external"}:void 0}async function Qn(n){try{process.kill(n,"SIGTERM")}catch{}await un(n)}async function Lu(n){try{let e=await fetch(`${n.url}/__pages`,{signal:AbortSignal.timeout(aP)});if(!e.ok)return;let{pages:t}=await e.json();return typeof t=="number"?t:void 0}catch{return}}async function Bt(n,e=me(n)?"keep":"close"){try{let t=await fetch(`${n.url}/__stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pages:e}),signal:AbortSignal.timeout(sy)});if(!t.ok)throw new Error(`/__stop ${t.status}`);let{closed:r=0,stuck:s=0}=await t.json(),i=Date.now()+sy;for(;Xn(n.pid)&&Date.now()<i;)await cy(100);return Xn(n.pid)?(await Qn(n.pid),"killed"):(await un(n.pid),{closed:r,stuck:s})}catch{return await Qn(n.pid),"killed"}}function dn(n,e){let t=se(e);return n.filter(r=>!me(r)&&r.pid!==process.pid&&se(r.file)===t)}async function Bo(n,e){let t=dn(await Q(),n);for(let r of t)await Bt(r,e!==void 0&&r.port===e?"keep":"close");return t}function lP(n,e,t){(process.platform==="win32"?ny("cmd",["/c","start","","/b",n,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):ny(n,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function tr(){return Te.join(Te.dirname(sP(import.meta.url)),"index.js")}function uy(n,e={}){return{command:process.execPath,args:[tr(),...e.trust?["--trust"]:[],...e.mode?["--mode",e.mode]:[],n,...e.open===!1?["--no-open"]:[]]}}function dy(n){return{command:process.execPath,args:[tr(),`agent:${n}`,"--no-open"]}}async function fy(n,e,t,r){let s=await n();if(s)return s;lP(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await cy(150);let o=await n();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function Ss(n,e={}){let t=e.cwd??process.cwd(),r=Te.resolve(t,n),s=await Gn({kind:"bulb",file:r},t),[i]=await Bo(r,s),o={...e,mode:e.mode??i?.mode};return fy(async()=>dn(await Q(),r)[0],uy(n,o),t,Te.basename(n))}async function Mu(n,e=process.cwd()){return fy(()=>Mo(e,n),dy(n),e,`the ${n} mirror`)}var ry,iP,sy,aP,cy,$e=S(()=>{"use strict";nt();cn();No();ry=1e6;iP=/^── run (\d+) ── /;sy=6e3,aP=500;cy=n=>new Promise(e=>setTimeout(e,n))});function nr(n){return{...tp(n),server:n.files.get("server.ts")??""}}function Do(n){return!!n.server&&!n.code}var ks=S(()=>{"use strict";ee();ee()});function jo(n){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(n),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Bu(n){return Kn(jo(n)??"bulb")||"bulb"}var Du=S(()=>{"use strict";ee()});import{readdirSync as cP,readFileSync as uP,statSync as dP}from"fs";import{join as py,basename as fP}from"path";function my(n,e,t){if(e>8)return t;let r;try{r=cP(n,{withFileTypes:!0})}catch{return t}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;my(py(n,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(py(n,s.name));return t}function pP(n,e){let t,r=!1;try{let s=uP(n,"utf8");t=jo(s.slice(0,1024));let i=We(s);r=!!i&&Do(nr(i))}catch{}return{mtime:e,name:t??fP(n).replace(/\.bulb\.md$/,""),serverOnly:r}}function Fo(n){let e=new Map,t=my(n,0,[]).map(r=>{let s=0;try{s=dP(r).mtimeMs}catch{}let i=s?hy.get(r):void 0,o=i?.mtime===s?i:pP(r,s);return s&&e.set(r,o),{path:r,...o}});return hy=e,t}var hy,gy=S(()=>{"use strict";ee();ks();Du();hy=new Map});function rr(n){if(n.server.trim())return"server-side code (server.ts)";let e=n.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")||n.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 Uo=S(()=>{"use strict"});import{readFile as hP}from"fs/promises";async function ju(n){try{let e=We(await hP(n,"utf-8"));return e?rr(nr(e)):void 0}catch{return}}var yy=S(()=>{"use strict";ks();Uo()});function Fu(n){let e=n.split(""),t=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
318
318
  `&&(e[a]=" ")},r=0,s="";for(;r<n.length;){let i=n[r],o=n[r+1];if(i==="/"&&o==="/"){let a=r;for(;a<n.length&&n[a]!==`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typebulb",
3
- "version": "0.60.4",
3
+ "version": "0.60.5",
4
4
  "description": "Typebulb CLI to run single-file markdown apps called bulbs, either as standalone web apps or embedded in agent responses.",
5
5
  "keywords": [
6
6
  "bulb",