typebulb 0.62.7 → 0.62.8

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/README.md CHANGED
@@ -69,7 +69,7 @@ typebulb trust [file] Remember a bulb as trusted (no arg: list trusted
69
69
  typebulb untrust <file> Forget a bulb's trust (back to Restricted)
70
70
  typebulb status [agent] A sub-agent's status: what it waits on, its commands and files (no arg: the session's overview)
71
71
  typebulb status --slow <dur> When a call counts as slow for this session (default 3m)
72
- typebulb babysit Watch your sub-agents silently; print and exit when one needs you (run it in the background — the exit is your wake-up)
72
+ typebulb babysit Watch your sub-agents silently; print and exit when one needs you (run it in the background: each exit is one wake-up, so re-arm it after handling)
73
73
  typebulb babysit --slow <dur> When a call counts as slow for this session (default 3m)
74
74
  typebulb --no-watch <file> Disable hot reload
75
75
  typebulb --no-open <file> Open nothing at launch, not even inside VS Code
@@ -326,7 +326,7 @@ The host owns light/dark; you style for both.
326
326
  - **A bulb's working files land beside it automatically** — relative `tb.fs` paths resolve to the bulb's folder, in `code.tsx` and `server.ts` alike: `tb.fs.write('run.json')`, no path prefix, no mkdir.
327
327
  - **Images & media: an `assets/` subfolder of the bulb's folder** (`birds.bulb.md` → `birds/assets/robin.png`) — `<img src="assets/robin.png">` just works (always that relative form, never `/assets/…`), every tier except inline. It holds what the bulb ships in order to run (e.g. images), never results.
328
328
  - **See what's already running** — `typebulb logs` with no argument lists every running bulb and mirror; check it before launching anything.
329
- - **Checking on sub-agents you spawned** — `typebulb status` is your session's overview (what's running, failure streaks, files to check before `git add`), and `typebulb status <id>` one agent's; run it before committing. Arm `typebulb babysit` in the background when you fan out (Claude Code: `run_in_background`; Codex: experimental, may need elevated permissions): it exits with a line when an agent needs you, so handle it and arm it again. Run babysit unpiped, and brief their checks unpiped or after `set -o pipefail`: a command piped into `tail` exits with `tail`'s code, hiding its own. Both take `--slow` (when a call counts as slow, default `3m`): set it to your project's pace once, e.g. `--slow 10m` where the test suite takes 8, and the session keeps it.
329
+ - **Checking on sub-agents you spawned** — `typebulb status` is your session's overview (what's running, failure streaks, files to check before `git add`), and `typebulb status <id>` one agent's; run it before committing. Arm `typebulb babysit` in the background when you fan out (Claude Code: `run_in_background`; Codex: experimental, may need elevated permissions): it exits with a line when an agent needs you, because a background command wakes you only by exiting. Handle it and arm it again right away; the re-arm loses nothing, as what came up meanwhile fires at once and what it already reported doesn't repeat. Run babysit unpiped, and brief their checks unpiped or after `set -o pipefail`: a command piped into `tail` exits with `tail`'s code, hiding its own. Both take `--slow` (when a call counts as slow, default `3m`): set it to your project's pace once, e.g. `--slow 10m` where the test suite takes 8, and the session keeps it.
330
330
  - **Self-testing a local bulb** — To confirm a bulb works, run it, instrument with `tb.log(...)`, and read it back with `typebulb logs`. That's the loop to verify behaviour without asking the user to copy-paste console output. `tb.fs.write(...)` is handy for dumping large outputs.
331
331
  - **Self-testing client code** — gate checks behind `tb.onMessage(m => { if (m === 'selftest') return run() })`, trigger with `typebulb send <file> selftest --wait`, and assert on the JSON reply — see [Interrogating the live page](#interrogating-the-live-page).
332
332
  - **Probe handlers go in the first draft** — the selftest, readback, and set handlers you'll want later: adding one is an edit, and that hot reload destroys the very state you meant to inspect.
package/SKILL.md CHANGED
@@ -1,10 +1,10 @@
1
1
  ---
2
2
  name: typebulb
3
3
  description: "Author and run Typebulb bulbs — single-file markdown apps (TypeScript/TSX) that run locally via `npx typebulb` (full power: filesystem, database, `server.ts`, `tb.ai`) or render live inline in your coding agent's session through Typebulb's agent mirror (sandboxed, client-only). A bulb can be a visual widget (chart, simulation, diagram, calculator, UI), a full-stack tool with a Node backend, or an AI app that calls models at runtime. Covers the bulb format, the `tb.*` API, trust, and the local run/inline workflow. Use when the user wants a bulb, a quick local tool (visual, backend-backed, or AI-powered), or something visual rendered inline in the conversation."
4
- version: 0.62.7
4
+ version: 0.62.8
5
5
  ---
6
6
 
7
- > Generated from typebulb v0.62.7. `npx typebulb agent` prints the running version alongside the path to its packaged SKILL.md: if that version is newer than this one, replace this file with that one.
7
+ > Generated from typebulb v0.62.8. `npx typebulb agent` prints the running version alongside the path to its packaged SKILL.md: if that version is newer than this one, replace this file with that one.
8
8
 
9
9
  # typebulb
10
10
 
@@ -77,7 +77,7 @@ typebulb trust [file] Remember a bulb as trusted (no arg: list trusted
77
77
  typebulb untrust <file> Forget a bulb's trust (back to Restricted)
78
78
  typebulb status [agent] A sub-agent's status: what it waits on, its commands and files (no arg: the session's overview)
79
79
  typebulb status --slow <dur> When a call counts as slow for this session (default 3m)
80
- typebulb babysit Watch your sub-agents silently; print and exit when one needs you (run it in the background — the exit is your wake-up)
80
+ typebulb babysit Watch your sub-agents silently; print and exit when one needs you (run it in the background: each exit is one wake-up, so re-arm it after handling)
81
81
  typebulb babysit --slow <dur> When a call counts as slow for this session (default 3m)
82
82
  typebulb --no-watch <file> Disable hot reload
83
83
  typebulb --no-open <file> Open nothing at launch, not even inside VS Code
@@ -334,7 +334,7 @@ The host owns light/dark; you style for both.
334
334
  - **A bulb's working files land beside it automatically** — relative `tb.fs` paths resolve to the bulb's folder, in `code.tsx` and `server.ts` alike: `tb.fs.write('run.json')`, no path prefix, no mkdir.
335
335
  - **Images & media: an `assets/` subfolder of the bulb's folder** (`birds.bulb.md` → `birds/assets/robin.png`) — `<img src="assets/robin.png">` just works (always that relative form, never `/assets/…`), every tier except inline. It holds what the bulb ships in order to run (e.g. images), never results.
336
336
  - **See what's already running** — `typebulb logs` with no argument lists every running bulb and mirror; check it before launching anything.
337
- - **Checking on sub-agents you spawned** — `typebulb status` is your session's overview (what's running, failure streaks, files to check before `git add`), and `typebulb status <id>` one agent's; run it before committing. Arm `typebulb babysit` in the background when you fan out (Claude Code: `run_in_background`; Codex: experimental, may need elevated permissions): it exits with a line when an agent needs you, so handle it and arm it again. Run babysit unpiped, and brief their checks unpiped or after `set -o pipefail`: a command piped into `tail` exits with `tail`'s code, hiding its own. Both take `--slow` (when a call counts as slow, default `3m`): set it to your project's pace once, e.g. `--slow 10m` where the test suite takes 8, and the session keeps it.
337
+ - **Checking on sub-agents you spawned** — `typebulb status` is your session's overview (what's running, failure streaks, files to check before `git add`), and `typebulb status <id>` one agent's; run it before committing. Arm `typebulb babysit` in the background when you fan out (Claude Code: `run_in_background`; Codex: experimental, may need elevated permissions): it exits with a line when an agent needs you, because a background command wakes you only by exiting. Handle it and arm it again right away; the re-arm loses nothing, as what came up meanwhile fires at once and what it already reported doesn't repeat. Run babysit unpiped, and brief their checks unpiped or after `set -o pipefail`: a command piped into `tail` exits with `tail`'s code, hiding its own. Both take `--slow` (when a call counts as slow, default `3m`): set it to your project's pace once, e.g. `--slow 10m` where the test suite takes 8, and the session keeps it.
338
338
  - **Self-testing a local bulb** — To confirm a bulb works, run it, instrument with `tb.log(...)`, and read it back with `typebulb logs`. That's the loop to verify behaviour without asking the user to copy-paste console output. `tb.fs.write(...)` is handy for dumping large outputs.
339
339
  - **Self-testing client code** — gate checks behind `tb.onMessage(m => { if (m === 'selftest') return run() })`, trigger with `typebulb send <file> selftest --wait`, and assert on the JSON reply — see [Interrogating the live page](#interrogating-the-live-page).
340
340
  - **Probe handlers go in the first draft** — the selftest, readback, and set handlers you'll want later: adding one is an edit, and that hot reload destroys the very state you meant to inspect.
@@ -2192,7 +2192,7 @@ ${sSt(b)}`};let v=nSt(h.code,{jsxImportSource:p.ts?.jsxImportSource});if(v.error
2192
2192
  `).map(v=>v.replace(/\r$/,""));if(a.length&&a[a.length-1]===""&&a.pop(),s)return a.map(v=>({kind:"add",text:v}));let h=[],p=!1,b=!1;for(let v of a){if(v.startsWith("@@")){b&&h.push({kind:"gap",text:"\u22EF"}),b=!0,p=!0;continue}if(!p){v.startsWith("Binary file")&&h.push({kind:"ctx",text:v});continue}v.startsWith("\\")||(v.startsWith("+")?h.push({kind:"add",text:v.slice(1)}):v.startsWith("-")?h.push({kind:"del",text:v.slice(1)}):h.push({kind:"ctx",text:v.slice(1)}))}return h}function G5n(o,s,a){let h=q5n(o,s),p=o.length>H5n?"txt":a.split(".").pop()??"",b=[],v=[];for(let P of h)(P.kind==="ctx"||P.kind==="del")&&b.push(P.text),(P.kind==="ctx"||P.kind==="add")&&v.push(P.text);let w=dEe(b.join(`
2193
2193
  `),p),S=dEe(v.join(`
2194
2194
  `),p),T=0,D=0,B=[];for(let P of h){if(P.kind==="gap"){B.push('<div class="udiff-gap">\u22EF</div>');continue}let F=P.kind==="del"?w[T++]:(P.kind==="add"||T++,S[D++]);B.push(`<div class="udiff-line${P.kind==="add"?" udiff-add":P.kind==="del"?" udiff-del":""}">${F??""}</div>`)}return{kinds:h.map(P=>P.kind),bodyHtml:B.join("")}}var cie=class extends iw{files=[];repo=!0;root="";viewing;#e=0;#t=!1;#n=()=>document.getElementById(bEe);#r=new lte(this.#n);#s=[];#i=-1;keepOpenSelector=".gitdiff-wrap";filterId="gitdiff-filter";listSelector=".gitdiff-list";onActivate(s){let a=this.rows()[s];a&&this.openDiff(a)}onAttached(){this.refreshFiles(),setInterval(()=>this.refreshFiles(),3e3),setInterval(()=>{this.viewing&&this.refreshDiff()},1500)}rows(){let s=this.filter.trim().toLowerCase();return s?this.files.filter(a=>a.path.toLowerCase().includes(s)):this.files}async refreshFiles(){try{let{repo:s,root:a,files:h}=await tb.server.gitChangedFiles(),p=s!==this.repo||h.length!==this.files.length||h.some((b,v)=>{let w=this.files[v];return b.path!==w?.path||b.status!==w.status||b.add!==w.add||b.del!==w.del||b.binary!==w.binary});this.repo=s,this.root=a,this.files=h,p&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] gitChangedFiles failed",s)}}#o(s,a,h){this.viewing?.path!==s&&(this.#s=[]),this.viewing={path:s,status:a,text:h.text,truncated:!!h.truncated,...G5n(h.text,!!h.untracked,s)},this.#e++,this.update()}async openDiff(s){try{let a=await tb.server.gitDiff(s.path);if(!a.ok){console.error("[mirror] gitDiff failed:",a.error);return}this.#o(s.path,s.status,a),this.#t=!0,this.close()}catch(a){console.error("[mirror] gitDiff failed",a)}}async refreshDiff(){let s=this.viewing;if(s)try{let a=await tb.server.gitDiff(s.path);if(this.viewing!==s||!a.ok||a.text===s.text)return;this.#o(s.path,s.status,a)}catch(a){console.error("[mirror] gitDiff refresh failed",a)}}closeDoc(){this.#r.release(),this.viewing=void 0,this.update()}show(){this.beginOpen(),this.refreshFiles(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.files.length;return!this.repo||s===0&&!this.viewing&&!this.open?tt({class:"gitdiff-wrap"}):tt({class:"gitdiff-wrap pop-center"},this.viewing?this.viewingPill():Ao({class:["pill","glyph","gitdiff-pill",this.open?"on":""],"data-tip":`${s} changed file${s===1?"":"s"} \u2014 view a diff`,ariaLabel:`${s} changed file${s===1?"":"s"}`,onClick:a=>{a.stopPropagation(),this.open?this.close():this.show()}},rw("diff"),Vt({class:"gitdiff-count"},String(s))),this.open?this.popup():null)}viewingPill(){let s=this.viewing,a=s.kinds.filter(p=>p==="add").length,h=s.kinds.filter(p=>p==="del").length;return Ao({class:["pill","glyph","gitdiff-pill","viewing","on"],"data-tip":`${this.files.length} changed file${this.files.length===1?"":"s"} \u2014 switch file`,onClick:p=>{p.stopPropagation(),this.open?this.close():this.show()}},Vt({class:["gitdiff-status",`s-${s.status}`]},s.status),Vt({class:"gitdiff-doc-path",title:`Open ${s.path}`,onClick:p=>{p.stopPropagation(),tb.server.openFile(`${this.root}/${s.path}`)}},s.path),Vt({class:"gitdiff-counts"},Vt({class:"count-add"},`+${a}`),Vt({class:"count-del"},`\u2212${h}`)),ite(()=>this.closeDoc()))}popup(){let s=this.rows();return tt({class:"servers-pop gitdiff-pop"},s.length===0?this.emptyState("No changes in the working tree."):tt({class:"gitdiff-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.files.length,"file"))}row(s,a){return tt({class:["gitdiff-row",a===this.highlighted?"active":"",this.viewing?.path===s.path?"viewing":""],onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openDiff(s)}},Vt({class:["gitdiff-status",`s-${s.status}`]},s.status),Vt({class:"gitdiff-path",title:s.path},s.path),s.add!==void 0||s.del!==void 0?Vt({class:"gitdiff-counts"},Vt({class:"count-add"},`+${s.add??0}`),Vt({class:"count-del"},`\u2212${s.del??0}`)):s.status==="U"?Vt({class:"gitdiff-counts"},Vt({class:"count-add"},"new")):Vt({class:"gitdiff-counts"},Vt({},s.binary?"binary":"\u2014")))}docView(){let s=this.viewing;return tt({class:"diff-doc",onKeyDown:a=>{a.key==="Escape"&&(a.stopPropagation(),this.closeDoc())}},tt({class:"diff-doc-scroll"},tt({class:"diff-doc-body",id:bEe,tabIndex:0,onMounted:a=>a.focus(),onScroll:()=>this.#r.sync()},s.kinds.length===0?tt({class:"diff-doc-empty"},"No changes."):tt({class:"diff-doc-code",key:`diff-code-${this.#e}`,onMounted:a=>{a.innerHTML=s.bodyHtml,this.#c(a),this.#u(a)}},""),s.truncated?tt({class:"diff-doc-trunc"},"Diff truncated \u2014 file too large to show in full."):null),s.kinds.length?this.#r.view(this.#s,{class:"diff-ruler",title:"Jump to a change",label:"Diff scroll position",controls:bEe}):null))}#c(s){if(!this.#t)return;this.#t=!1;let a=s.querySelector(".udiff-add, .udiff-del"),h=this.#n();a&&h&&(h.scrollTop=a.offsetTop-h.clientHeight/3)}#u(s){this.#i!==this.#e&&(this.#i=this.#e,requestAnimationFrame(()=>{this.#f(s),this.update(),this.#r.sync()}))}#f(s){let a=this.viewing,h=this.#n();if(!a||!h?.scrollHeight)return;let p=h.scrollHeight,b=[];for(let v=0;v<a.kinds.length;v++){let w=a.kinds[v];if(w!=="add"&&w!=="del")continue;let S=v;for(;S+1<a.kinds.length&&a.kinds[S+1]===w;)S++;let T=s.children[v],D=s.children[S];T&&D&&b.push({top:T.offsetTop/p,height:(D.offsetTop+D.offsetHeight-T.offsetTop)/p,class:w}),v=S}this.#s=b}};async function mEe(o){try{return await navigator.clipboard.writeText(o),!0}catch{}let s=document.createElement("textarea");s.value=o,s.style.cssText="position:fixed;top:0;left:0;opacity:0",document.body.appendChild(s),s.select();try{return document.execCommand("copy")}catch{return!1}finally{s.remove()}}var oD=class extends Wu{done=!1;#e;constructor(s){super(),this.#e=s}setText(s){this.#e=s}flash(){mEe(this.#e),this.done=!0,this.update(),setTimeout(()=>{this.done=!1,this.update()},600)}view(){return Ao({class:["overlay-pill","copy",this.done?"done":""],onClick:s=>{s.stopPropagation(),this.flash()}},this.done?"copied":"copy")}};var wTt=".typebulb/paste",ATt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"},GC=o=>o.label||o.kind||"agent",wEe=o=>o.failing&&o.state!=="stopped"?"failing":o.state,AEe=o=>`Open this ${o.kind?`${o.kind} `:""}agent's transcript`;var vTt=8,yTt=30,Edr=3*6e4;var uie=o=>new Date(o).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});var vEe=o=>[o.runs?`${o.runs} run, ${o.failed} failed`:"",yEe(o)].filter(Boolean).join(", ")||"none",yEe=o=>o.lookups?`${o.lookups} ${o.lookups===1?"lookup":"lookups"}`:"";var xTt=o=>o.open.filter(s=>!s.interrupted);var ETt=(o,s)=>o.state==="running"?Math.max(0,s-o.asOf):0,CTt=(o,s)=>o.activeMs+ETt(o,s);function Q5n(o,s){let a=o.state==="finished"?xTt(o).filter(h=>h.background):[];return a.length?`finished, background call running ${tf(s-(a[0].at??s))}${a.length>1?` (+${a.length-1} more)`:""}`:o.state}var kEe=(o,s)=>({state:Q5n(o,s),active:`${tf(CTt(o,s))} active`,idle:o.idleMs?`${tf(o.idleMs)} idle`:""}),J5n=(o,s)=>{let a=kEe(o,s);return[a.state,a.active,a.idle].filter(Boolean).join(" \xB7 ")},kTt=(o,s)=>o.interrupted?`${o.label}: interrupted, its process has ended`:`${o.label}, ${tf(s-(o.at??s))}${o.background?" (background)":""}`,U5n=(o,s)=>`nothing open, last entry ${tf(s-o.asOf)} ago`;function z5n(o,s){if(!o.open.length)return[`Now: ${U5n(o,s)}`,...o.latest?[`Latest: ${o.latest.label} \xB7 ${hie(o.latest.run)}${o.latest.run.ms!==void 0?` after ${tf(o.latest.run.ms)}`:""}`]:[]];let a=(h,p)=>h.said?[`${p}"${h.said}"`]:[];return o.open.length===1?[`Now: ${kTt(o.open[0],s)}`,...a(o.open[0]," ")]:["Now:",...o.open.flatMap(h=>[` ${kTt(h,s)}`,...a(h," ")])]}function K5n(o,s){let a=o.latest;return`latest: ${a.interrupted?"interrupted":a.open?`running ${tf(s-(a.at??s))}`:`${hie(a)}${a.ms!==void 0?` after ${tf(a.ms)}`:""}`}${o.streak>=2?`, failed ${o.streak} in a row`:""}`}function STt(o,s){let a=[`Sub-agent "${o.name}" (${o.id}): ${J5n(o,s)}${o.asOf?` \xB7 as of ${uie(o.asOf)}`:""}`,""];a.push(...z5n(o,s));let h=o.commands;a.push(`Commands: ${vEe(h)}`);let{shown:p,more:b}=CEe(h);for(let S of p){let T=fie(S);a.push(` ${S.cmd} \xD7${S.runs}${S.failed?`, ${S.failed} failed`:""}${T?` \xB7 ${T}`:""}`,` ${K5n(S,s)}`);let D=[S.latest.first,S.latest.last].filter(Boolean).map(B=>`"${B}"`).join(" \u2026 ");D&&a.push(` ${D}`)}b&&a.push(` ${SEe(b)}`),aie(h).runs&&a.push(` ${lie(h)}`),o.activeMs&&a.push(`Time: ${W5n(o,s)}`),o.narration.length&&a.push("Narration:",...o.narration.map(S=>` ${S}`)),a.push(`Files written: ${xEe(o)}`);for(let S of o.files){let T=S.also.length?` also ${Y5n(S)}`:"";a.push(` ${die(S)}${S.ignored?" (ignored)":S.committed?" (committed)":""}${T}`,...S.blind.map(D=>` ${D}`))}let{shown:v,earlier:w}=IEe(o);return a.push(`Files read: ${o.read.length||"none"}`,...w?[` +${w} earlier`]:[],...v.map(S=>` ${X5n(S)}`)),a.join(`
2195
- `)}var xEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function EEe(o,s){let a=o.toolMs+(xTt(o).some(h=>!h.background)?ETt(o,s):0);return{tools:a,model:Math.max(0,CTt(o,s)-a)}}var W5n=(o,s)=>{let a=EEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},Y5n=o=>o.also.map(s=>`"${s.name}" ${uie(s.at)}`).join(", "),ITt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,CEe=o=>{let s=o.groups.filter(ITt);return{shown:s.slice(0,vTt),more:Math.max(0,s.length-vTt)}},SEe=o=>`+${o} more like these`,aie=o=>{let s=o.groups.filter(a=>!ITt(a));return{runs:s.reduce((a,h)=>a+h.runs-h.open,0),hidden:s.reduce((a,h)=>a+h.hidden,0),ms:s.reduce((a,h)=>a+h.ms,0)}},lie=(o,s=!0)=>{let a=aie(o),h=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${h?`${h}${p} ${b(h)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},fie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var hie=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",die=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,X5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,IEe=o=>({shown:o.read.slice(-yTt),earlier:Math.max(0,o.read.length-yTt)});var Cdr=5*6e4;var V5n=2e3,TEe=(o="cs-list",s="none")=>tt({class:o},tt({class:"cs-item cs-dim"},s)),TTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},_Ee=o=>`\u200E${o}\u200E`,pie=class extends Wu{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<V5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return tt({class:"messages child-status",key:"child-status"},tt({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return tt({class:"messages child-status",key:"child-status"},this.#f(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#p(s),this.#g(s),tt({class:"child-status-foot"},this.#t?tt({class:"child-status-note err"},this.#t):null,tt({class:"child-status-actions"},lg({onClick:h=>{h.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),lg({onClick:h=>{h.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await mEe(STt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return lg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:h=>{h.preventDefault(),this.#c(s)}},a)}#f(s,a){let h=EEe(s,a),p=kEe(s,a);return tt({class:"cs-header"},tt({class:"cs-title"},s.name),tt({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},tt({class:"cs-tile"},Vt({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),tt({class:"cs-tile"},p.active,s.activeMs?[Vt({class:"cs-tile-rule"}),Vt({class:"cs-time"},Vt(`${tf(h.tools)} tools`),Vt(`${tf(h.model)} model`))]:null),p.idle?tt({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?tt({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let h=s.latest,p=[...s.open.map(b=>tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(b.id,b.label),tt({class:"cs-item-meta"},b.interrupted?Vt({class:"cs-pill bad"},"interrupted"):Vt({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?Vt({class:"cs-pill"},"background"):null)),b.said?tt({class:"cs-item-sub cs-mono"},b.said):null)),h?tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(h.id,h.label),tt({class:"cs-item-meta"},this.#h(h.run),h.run.ms!==void 0?Vt({class:"cs-dim"},tf(h.run.ms)):null))):null].filter(Boolean);return p.length?tt({class:"cs-section"},tt({class:"cs-h"},"Now"),tt({class:"cs-list"},p)):null}#h(s){let a=hie(s);return Vt({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let h=s.commands,{shown:p,more:b}=CEe(h),v=aie(h);return p.length?tt({class:"cs-section"},tt({class:"cs-h"},"Commands",Vt({class:"cs-count"},vEe(h))),tt({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?tt({class:"cs-item-sub cs-mono"},S.map((T,D)=>[D?Vt({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?tt({class:"cs-more"},SEe(b)):null,v.runs?tt({class:"cs-more"},lie(h)):null):tt({class:"cs-section"},tt({class:"cs-h"},"Commands"),TEe("cs-list",[v.runs?lie(h,!1):"",yEe(h)].filter(Boolean).join(", ")||"none"))}#d(s,a){let h=s.latest,p=h.interrupted?Vt({class:"cs-pill bad"},"interrupted"):h.open?Vt({class:"cs-pill run"},`running ${tf(a-(h.at??a))}`):this.#h(h);return tt({class:"cs-item-meta"},p,!h.open&&h.ms!==void 0?Vt({class:"cs-dim"},tf(h.ms)):null,s.runs>1?Vt({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!h.failed)?Vt({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?Vt({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,fie(s)?Vt({class:"cs-pill warn"},fie(s)):null)}#p(s){return tt({class:"cs-section"},tt({class:"cs-h"},"Files written",s.files.length?Vt({class:"cs-count"},xEe(s)):null),s.files.length?tt({class:"cs-list cs-files"},s.files.map(a=>tt({class:"cs-item"},tt({class:"cs-item-main"},a.deleted?Vt({class:"cs-path",title:die(a)},_Ee(die(a))):lg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:TTt(a.path)},_Ee(a.path)),tt({class:"cs-item-meta"},a.from?Vt({class:"cs-dim"},`moved from ${a.from}`):null,Vt({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?tt({class:"cs-item-sub"},a.also.length?tt({class:"cs-chips"},Vt({class:"cs-dim"},"also "),a.also.map(h=>Vt({class:"cs-chip"},h.name,Vt({class:"cs-dim"},` ${uie(h.at)}`)))):null,a.blind.map(h=>tt({class:"cs-blind"},h))):null))):TEe("cs-list cs-files"))}#m(s){return s.narration.length?tt({class:"cs-section"},tt({class:"cs-h"},"Narration"),tt({class:"cs-list cs-files"},s.narration.map(a=>tt({class:"cs-item"},a)))):null}#g(s){let{shown:a,earlier:h}=IEe(s);return tt({class:"cs-section"},tt({class:"cs-h"},"Files read",s.read.length?Vt({class:"cs-count"},`${s.read.length}`):null),s.read.length?tt({class:"cs-list cs-files"},h?tt({class:"cs-item cs-dim"},`+${h} earlier`):null,a.map(p=>tt({class:"cs-item"},tt({class:"cs-item-main"},lg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:TTt(p.path)},_Ee(p.path)),p.times>1?tt({class:"cs-item-meta"},Vt({class:"cs-dim"},`\xD7${p.times}`)):null)))):TEe("cs-list cs-files"))}};var gie=class extends iw{children=[];enabled=!1;viewing=null;status=new pie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=ryt((await tb.server.listChildren()).sort((h,p)=>h.mtime-p.mtime));if(this.open&&this.#e.length){let h=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,h.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((h,p)=>{let b=this.children[p];return h.id!==b?.id||h.state!==b.state||h.mtime!==b.mtime||h.tokens!==b.tokens})||s.some(h=>h.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let h=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==h}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(h){console.error("[mirror] openChild failed",h)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?tt({class:"children-wrap"}):tt({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return Ao({class:["pill","children-pill",_F(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},Vt({class:"glyph-img"},"\u{1F916}"),String(a),Vt({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return Ao({class:["pill","glyph","children-pill","viewing","on",_F(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},Vt({class:"glyph-img"},"\u{1F916}"),Vt({class:"children-doc-label",title:GC(s)},GC(s)),ite(()=>{this.closeChild()}))}popup(){let s=this.rows();return tt({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):tt({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.children.length,"agent"))}row(s,a){return tt({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openChild(s.id)}},Vt({class:["children-dot",wEe(s)]}),Vt({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},GC(s)),s.kind?Vt({class:"children-kind"},s.kind):null,s.model?Vt({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,Vt({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?Vt({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):Vt({class:"children-tokens"},s.tokens?BF(s.tokens):""),Vt({class:"children-status-link","data-tip":"Where this agent stands: what it is waiting on, its commands, files and hand-backs",onClick:h=>{h.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var _Tt=new Map,MTt=(o,s)=>s+`
2195
+ `)}var xEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function EEe(o,s){let a=o.toolMs+(xTt(o).some(h=>!h.background)?ETt(o,s):0);return{tools:a,model:Math.max(0,CTt(o,s)-a)}}var W5n=(o,s)=>{let a=EEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},Y5n=o=>o.also.map(s=>`"${s.name}" ${uie(s.at)}`).join(", "),ITt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,CEe=o=>{let s=o.groups.filter(ITt);return{shown:s.slice(0,vTt),more:Math.max(0,s.length-vTt)}},SEe=o=>`+${o} more like these`,aie=o=>{let s=o.groups.filter(a=>!ITt(a));return{runs:s.reduce((a,h)=>a+h.runs-h.open,0),hidden:s.reduce((a,h)=>a+h.hidden,0),ms:s.reduce((a,h)=>a+h.ms,0)}},lie=(o,s=!0)=>{let a=aie(o),h=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${h?`${h}${p} ${b(h)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},fie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var hie=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",die=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,X5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,IEe=o=>({shown:o.read.slice(-yTt),earlier:Math.max(0,o.read.length-yTt)});var Cdr=5*6e4;var V5n=2e3,TEe=(o="cs-list",s="none")=>tt({class:o},tt({class:"cs-item cs-dim"},s)),TTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},_Ee=o=>`\u200E${o}\u200E`,pie=class extends Wu{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<V5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return tt({class:"messages child-status",key:"child-status"},tt({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return tt({class:"messages child-status",key:"child-status"},this.#f(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#p(s),this.#g(s),tt({class:"child-status-foot"},this.#t?tt({class:"child-status-note err"},this.#t):null,tt({class:"child-status-actions"},lg({onClick:h=>{h.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),lg({onClick:h=>{h.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await mEe(STt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return lg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:h=>{h.preventDefault(),this.#c(s)}},a)}#f(s,a){let h=EEe(s,a),p=kEe(s,a);return tt({class:"cs-header"},tt({class:"cs-title"},s.name),tt({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},tt({class:"cs-tile"},Vt({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),tt({class:"cs-tile"},p.active,s.activeMs?[Vt({class:"cs-tile-rule"}),Vt({class:"cs-time"},Vt(`${tf(h.tools)} tools`),Vt(`${tf(h.model)} model`))]:null),p.idle?tt({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?tt({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let h=s.latest,p=[...s.open.map(b=>tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(b.id,b.label),tt({class:"cs-item-meta"},b.interrupted?Vt({class:"cs-pill bad"},"interrupted"):Vt({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?Vt({class:"cs-pill"},"background"):null)),b.said?tt({class:"cs-item-sub cs-mono"},b.said):null)),h?tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(h.id,h.label),tt({class:"cs-item-meta"},this.#h(h.run),h.run.ms!==void 0?Vt({class:"cs-dim"},tf(h.run.ms)):null))):null].filter(Boolean);return p.length?tt({class:"cs-section"},tt({class:"cs-h"},"Now"),tt({class:"cs-list"},p)):null}#h(s){let a=hie(s);return Vt({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let h=s.commands,{shown:p,more:b}=CEe(h),v=aie(h);return p.length?tt({class:"cs-section"},tt({class:"cs-h"},"Commands",Vt({class:"cs-count"},vEe(h))),tt({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return tt({class:"cs-item"},tt({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?tt({class:"cs-item-sub cs-mono"},S.map((T,D)=>[D?Vt({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?tt({class:"cs-more"},SEe(b)):null,v.runs?tt({class:"cs-more"},lie(h)):null):tt({class:"cs-section"},tt({class:"cs-h"},"Commands"),TEe("cs-list",[v.runs?lie(h,!1):"",yEe(h)].filter(Boolean).join(", ")||"none"))}#d(s,a){let h=s.latest,p=h.interrupted?Vt({class:"cs-pill bad"},"interrupted"):h.open?Vt({class:"cs-pill run"},`running ${tf(a-(h.at??a))}`):this.#h(h);return tt({class:"cs-item-meta"},p,!h.open&&h.ms!==void 0?Vt({class:"cs-dim"},tf(h.ms)):null,s.runs>1?Vt({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!h.failed)?Vt({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?Vt({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,fie(s)?Vt({class:"cs-pill warn"},fie(s)):null)}#p(s){return tt({class:"cs-section"},tt({class:"cs-h"},"Files written",s.files.length?Vt({class:"cs-count"},xEe(s)):null),s.files.length?tt({class:"cs-list cs-files"},s.files.map(a=>tt({class:"cs-item"},tt({class:"cs-item-main"},a.deleted?Vt({class:"cs-path",title:die(a)},_Ee(die(a))):lg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:TTt(a.path)},_Ee(a.path)),tt({class:"cs-item-meta"},a.from?Vt({class:"cs-dim"},`moved from ${a.from}`):null,Vt({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?tt({class:"cs-item-sub"},a.also.length?tt({class:"cs-chips"},Vt({class:"cs-dim"},"also "),a.also.map(h=>Vt({class:"cs-chip"},h.name,Vt({class:"cs-dim"},` ${uie(h.at)}`)))):null,a.blind.map(h=>tt({class:"cs-blind"},h))):null))):TEe("cs-list cs-files"))}#m(s){return s.narration.length?tt({class:"cs-section"},tt({class:"cs-h"},"Narration"),tt({class:"cs-list cs-files"},s.narration.map(a=>tt({class:"cs-item"},a)))):null}#g(s){let{shown:a,earlier:h}=IEe(s);return tt({class:"cs-section"},tt({class:"cs-h"},"Files read",s.read.length?Vt({class:"cs-count"},`${s.read.length}`):null),s.read.length?tt({class:"cs-list cs-files"},h?tt({class:"cs-item cs-dim"},`+${h} earlier`):null,a.map(p=>tt({class:"cs-item"},tt({class:"cs-item-main"},lg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:TTt(p.path)},_Ee(p.path)),p.times>1?tt({class:"cs-item-meta"},Vt({class:"cs-dim"},`\xD7${p.times}`)):null)))):TEe("cs-list cs-files"))}};var gie=class extends iw{children=[];enabled=!1;viewing=null;status=new pie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=ryt((await tb.server.listChildren()).sort((h,p)=>h.mtime-p.mtime));if(this.open&&this.#e.length){let h=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,h.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((h,p)=>{let b=this.children[p];return h.id!==b?.id||h.state!==b.state||h.mtime!==b.mtime||h.tokens!==b.tokens})||s.some(h=>h.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let h=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==h}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(h){console.error("[mirror] openChild failed",h)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?tt({class:"children-wrap"}):tt({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return Ao({class:["pill","children-pill",_F(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},Vt({class:"glyph-img"},"\u{1F916}"),String(a),Vt({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return Ao({class:["pill","glyph","children-pill","viewing","on",_F(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},Vt({class:"glyph-img"},"\u{1F916}"),Vt({class:"children-doc-label",title:GC(s)},GC(s)),ite(()=>{this.closeChild()}))}popup(){let s=this.rows();return tt({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):tt({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.children.length,"agent"))}row(s,a){return tt({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openChild(s.id)}},Vt({class:["children-dot",wEe(s)]}),Vt({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},GC(s)),s.kind?Vt({class:"children-kind"},s.kind):null,s.model?Vt({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,Vt({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?Vt({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):Vt({class:"children-tokens"},s.tokens?BF(s.tokens):""),Vt({class:"children-status-link",onClick:h=>{h.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var _Tt=new Map,MTt=(o,s)=>s+`
2196
2196
 
2197
2197
  ---
2198
2198
 
@@ -2192,7 +2192,7 @@ ${WCt(b)}`};let v=UCt(d.code,{jsxImportSource:p.ts?.jsxImportSource});if(v.error
2192
2192
  `).map(v=>v.replace(/\r$/,""));if(a.length&&a[a.length-1]===""&&a.pop(),s)return a.map(v=>({kind:"add",text:v}));let d=[],p=!1,b=!1;for(let v of a){if(v.startsWith("@@")){b&&d.push({kind:"gap",text:"\u22EF"}),b=!0,p=!0;continue}if(!p){v.startsWith("Binary file")&&d.push({kind:"ctx",text:v});continue}v.startsWith("\\")||(v.startsWith("+")?d.push({kind:"add",text:v.slice(1)}):v.startsWith("-")?d.push({kind:"del",text:v.slice(1)}):d.push({kind:"ctx",text:v.slice(1)}))}return d}function M5n(o,s,a){let d=_5n(o,s),p=o.length>T5n?"txt":a.split(".").pop()??"",b=[],v=[];for(let P of d)(P.kind==="ctx"||P.kind==="del")&&b.push(P.text),(P.kind==="ctx"||P.kind==="add")&&v.push(P.text);let w=uEe(b.join(`
2193
2193
  `),p),S=uEe(v.join(`
2194
2194
  `),p),T=0,D=0,B=[];for(let P of d){if(P.kind==="gap"){B.push('<div class="udiff-gap">\u22EF</div>');continue}let F=P.kind==="del"?w[T++]:(P.kind==="add"||T++,S[D++]);B.push(`<div class="udiff-line${P.kind==="add"?" udiff-add":P.kind==="del"?" udiff-del":""}">${F??""}</div>`)}return{kinds:d.map(P=>P.kind),bodyHtml:B.join("")}}var sie=class extends k4{files=[];repo=!0;root="";viewing;#e=0;#t=!1;#n=()=>document.getElementById(fEe);#r=new ute(this.#n);#s=[];#i=-1;keepOpenSelector=".gitdiff-wrap";filterId="gitdiff-filter";listSelector=".gitdiff-list";onActivate(s){let a=this.rows()[s];a&&this.openDiff(a)}onAttached(){this.refreshFiles(),setInterval(()=>this.refreshFiles(),3e3),setInterval(()=>{this.viewing&&this.refreshDiff()},1500)}rows(){let s=this.filter.trim().toLowerCase();return s?this.files.filter(a=>a.path.toLowerCase().includes(s)):this.files}async refreshFiles(){try{let{repo:s,root:a,files:d}=await tb.server.gitChangedFiles(),p=s!==this.repo||d.length!==this.files.length||d.some((b,v)=>{let w=this.files[v];return b.path!==w?.path||b.status!==w.status||b.add!==w.add||b.del!==w.del||b.binary!==w.binary});this.repo=s,this.root=a,this.files=d,p&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] gitChangedFiles failed",s)}}#o(s,a,d){this.viewing?.path!==s&&(this.#s=[]),this.viewing={path:s,status:a,text:d.text,truncated:!!d.truncated,...M5n(d.text,!!d.untracked,s)},this.#e++,this.update()}async openDiff(s){try{let a=await tb.server.gitDiff(s.path);if(!a.ok){console.error("[mirror] gitDiff failed:",a.error);return}this.#o(s.path,s.status,a),this.#t=!0,this.close()}catch(a){console.error("[mirror] gitDiff failed",a)}}async refreshDiff(){let s=this.viewing;if(s)try{let a=await tb.server.gitDiff(s.path);if(this.viewing!==s||!a.ok||a.text===s.text)return;this.#o(s.path,s.status,a)}catch(a){console.error("[mirror] gitDiff refresh failed",a)}}closeDoc(){this.#r.release(),this.viewing=void 0,this.update()}show(){this.beginOpen(),this.refreshFiles(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.files.length;return!this.repo||s===0&&!this.viewing&&!this.open?bt({class:"gitdiff-wrap"}):bt({class:"gitdiff-wrap pop-center"},this.viewing?this.viewingPill():wu({class:["pill","glyph","gitdiff-pill",this.open?"on":""],"data-tip":`${s} changed file${s===1?"":"s"} \u2014 view a diff`,ariaLabel:`${s} changed file${s===1?"":"s"}`,onClick:a=>{a.stopPropagation(),this.open?this.close():this.show()}},nw("diff"),sn({class:"gitdiff-count"},String(s))),this.open?this.popup():null)}viewingPill(){let s=this.viewing,a=s.kinds.filter(p=>p==="add").length,d=s.kinds.filter(p=>p==="del").length;return wu({class:["pill","glyph","gitdiff-pill","viewing","on"],"data-tip":`${this.files.length} changed file${this.files.length===1?"":"s"} \u2014 switch file`,onClick:p=>{p.stopPropagation(),this.open?this.close():this.show()}},sn({class:["gitdiff-status",`s-${s.status}`]},s.status),sn({class:"gitdiff-doc-path",title:`Open ${s.path}`,onClick:p=>{p.stopPropagation(),tb.server.openFile(`${this.root}/${s.path}`)}},s.path),sn({class:"gitdiff-counts"},sn({class:"count-add"},`+${a}`),sn({class:"count-del"},`\u2212${d}`)),nte(()=>this.closeDoc()))}popup(){let s=this.rows();return bt({class:"servers-pop gitdiff-pop"},s.length===0?this.emptyState("No changes in the working tree."):bt({class:"gitdiff-list",onScroll:()=>this.onListScroll()},s.map((a,d)=>this.row(a,d))),this.filterBox(this.files.length,"file"))}row(s,a){return bt({class:["gitdiff-row",a===this.highlighted?"active":"",this.viewing?.path===s.path?"viewing":""],onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:d=>{d.stopPropagation(),this.openDiff(s)}},sn({class:["gitdiff-status",`s-${s.status}`]},s.status),sn({class:"gitdiff-path",title:s.path},s.path),s.add!==void 0||s.del!==void 0?sn({class:"gitdiff-counts"},sn({class:"count-add"},`+${s.add??0}`),sn({class:"count-del"},`\u2212${s.del??0}`)):s.status==="U"?sn({class:"gitdiff-counts"},sn({class:"count-add"},"new")):sn({class:"gitdiff-counts"},sn({},s.binary?"binary":"\u2014")))}docView(){let s=this.viewing;return bt({class:"diff-doc",onKeyDown:a=>{a.key==="Escape"&&(a.stopPropagation(),this.closeDoc())}},bt({class:"diff-doc-scroll"},bt({class:"diff-doc-body",id:fEe,tabIndex:0,onMounted:a=>a.focus(),onScroll:()=>this.#r.sync()},s.kinds.length===0?bt({class:"diff-doc-empty"},"No changes."):bt({class:"diff-doc-code",key:`diff-code-${this.#e}`,onMounted:a=>{a.innerHTML=s.bodyHtml,this.#c(a),this.#u(a)}},""),s.truncated?bt({class:"diff-doc-trunc"},"Diff truncated \u2014 file too large to show in full."):null),s.kinds.length?this.#r.view(this.#s,{class:"diff-ruler",title:"Jump to a change",label:"Diff scroll position",controls:fEe}):null))}#c(s){if(!this.#t)return;this.#t=!1;let a=s.querySelector(".udiff-add, .udiff-del"),d=this.#n();a&&d&&(d.scrollTop=a.offsetTop-d.clientHeight/3)}#u(s){this.#i!==this.#e&&(this.#i=this.#e,requestAnimationFrame(()=>{this.#f(s),this.update(),this.#r.sync()}))}#f(s){let a=this.viewing,d=this.#n();if(!a||!d?.scrollHeight)return;let p=d.scrollHeight,b=[];for(let v=0;v<a.kinds.length;v++){let w=a.kinds[v];if(w!=="add"&&w!=="del")continue;let S=v;for(;S+1<a.kinds.length&&a.kinds[S+1]===w;)S++;let T=s.children[v],D=s.children[S];T&&D&&b.push({top:T.offsetTop/p,height:(D.offsetTop+D.offsetHeight-T.offsetTop)/p,class:w}),v=S}this.#s=b}};async function hEe(o){try{return await navigator.clipboard.writeText(o),!0}catch{}let s=document.createElement("textarea");s.value=o,s.style.cssText="position:fixed;top:0;left:0;opacity:0",document.body.appendChild(s),s.select();try{return document.execCommand("copy")}catch{return!1}finally{s.remove()}}var oD=class extends mu{done=!1;#e;constructor(s){super(),this.#e=s}setText(s){this.#e=s}flash(){hEe(this.#e),this.done=!0,this.update(),setTimeout(()=>{this.done=!1,this.update()},600)}view(){return wu({class:["overlay-pill","copy",this.done?"done":""],onClick:s=>{s.stopPropagation(),this.flash()}},this.done?"copied":"copy")}};var uTt=".typebulb/paste",aTt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"},GC=o=>o.label||o.kind||"agent",dEe=o=>o.failing&&o.state!=="stopped"?"failing":o.state,pEe=o=>`Open this ${o.kind?`${o.kind} `:""}agent's transcript`;var lTt=8,fTt=30,fdr=3*6e4;var oie=o=>new Date(o).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});var gEe=o=>[o.runs?`${o.runs} run, ${o.failed} failed`:"",bEe(o)].filter(Boolean).join(", ")||"none",bEe=o=>o.lookups?`${o.lookups} ${o.lookups===1?"lookup":"lookups"}`:"";var dTt=o=>o.open.filter(s=>!s.interrupted);var pTt=(o,s)=>o.state==="running"?Math.max(0,s-o.asOf):0,gTt=(o,s)=>o.activeMs+pTt(o,s);function D5n(o,s){let a=o.state==="finished"?dTt(o).filter(d=>d.background):[];return a.length?`finished, background call running ${tf(s-(a[0].at??s))}${a.length>1?` (+${a.length-1} more)`:""}`:o.state}var mEe=(o,s)=>({state:D5n(o,s),active:`${tf(gTt(o,s))} active`,idle:o.idleMs?`${tf(o.idleMs)} idle`:""}),B5n=(o,s)=>{let a=mEe(o,s);return[a.state,a.active,a.idle].filter(Boolean).join(" \xB7 ")},hTt=(o,s)=>o.interrupted?`${o.label}: interrupted, its process has ended`:`${o.label}, ${tf(s-(o.at??s))}${o.background?" (background)":""}`,L5n=(o,s)=>`nothing open, last entry ${tf(s-o.asOf)} ago`;function N5n(o,s){if(!o.open.length)return[`Now: ${L5n(o,s)}`,...o.latest?[`Latest: ${o.latest.label} \xB7 ${lie(o.latest.run)}${o.latest.run.ms!==void 0?` after ${tf(o.latest.run.ms)}`:""}`]:[]];let a=(d,p)=>d.said?[`${p}"${d.said}"`]:[];return o.open.length===1?[`Now: ${hTt(o.open[0],s)}`,...a(o.open[0]," ")]:["Now:",...o.open.flatMap(d=>[` ${hTt(d,s)}`,...a(d," ")])]}function R5n(o,s){let a=o.latest;return`latest: ${a.interrupted?"interrupted":a.open?`running ${tf(s-(a.at??s))}`:`${lie(a)}${a.ms!==void 0?` after ${tf(a.ms)}`:""}`}${o.streak>=2?`, failed ${o.streak} in a row`:""}`}function bTt(o,s){let a=[`Sub-agent "${o.name}" (${o.id}): ${B5n(o,s)}${o.asOf?` \xB7 as of ${oie(o.asOf)}`:""}`,""];a.push(...N5n(o,s));let d=o.commands;a.push(`Commands: ${gEe(d)}`);let{shown:p,more:b}=vEe(d);for(let S of p){let T=aie(S);a.push(` ${S.cmd} \xD7${S.runs}${S.failed?`, ${S.failed} failed`:""}${T?` \xB7 ${T}`:""}`,` ${R5n(S,s)}`);let D=[S.latest.first,S.latest.last].filter(Boolean).map(B=>`"${B}"`).join(" \u2026 ");D&&a.push(` ${D}`)}b&&a.push(` ${yEe(b)}`),cie(d).runs&&a.push(` ${uie(d)}`),o.activeMs&&a.push(`Time: ${O5n(o,s)}`),o.narration.length&&a.push("Narration:",...o.narration.map(S=>` ${S}`)),a.push(`Files written: ${wEe(o)}`);for(let S of o.files){let T=S.also.length?` also ${P5n(S)}`:"";a.push(` ${fie(S)}${S.ignored?" (ignored)":S.committed?" (committed)":""}${T}`,...S.blind.map(D=>` ${D}`))}let{shown:v,earlier:w}=kEe(o);return a.push(`Files read: ${o.read.length||"none"}`,...w?[` +${w} earlier`]:[],...v.map(S=>` ${j5n(S)}`)),a.join(`
2195
- `)}var wEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function AEe(o,s){let a=o.toolMs+(dTt(o).some(d=>!d.background)?pTt(o,s):0);return{tools:a,model:Math.max(0,gTt(o,s)-a)}}var O5n=(o,s)=>{let a=AEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},P5n=o=>o.also.map(s=>`"${s.name}" ${oie(s.at)}`).join(", "),mTt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,vEe=o=>{let s=o.groups.filter(mTt);return{shown:s.slice(0,lTt),more:Math.max(0,s.length-lTt)}},yEe=o=>`+${o} more like these`,cie=o=>{let s=o.groups.filter(a=>!mTt(a));return{runs:s.reduce((a,d)=>a+d.runs-d.open,0),hidden:s.reduce((a,d)=>a+d.hidden,0),ms:s.reduce((a,d)=>a+d.ms,0)}},uie=(o,s=!0)=>{let a=cie(o),d=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${d?`${d}${p} ${b(d)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},aie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var lie=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",fie=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,j5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,kEe=o=>({shown:o.read.slice(-fTt),earlier:Math.max(0,o.read.length-fTt)});var hdr=5*6e4;var F5n=2e3,xEe=(o="cs-list",s="none")=>bt({class:o},bt({class:"cs-item cs-dim"},s)),wTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},EEe=o=>`\u200E${o}\u200E`,hie=class extends mu{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<F5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return bt({class:"messages child-status",key:"child-status"},bt({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return bt({class:"messages child-status",key:"child-status"},this.#f(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#p(s),this.#g(s),bt({class:"child-status-foot"},this.#t?bt({class:"child-status-note err"},this.#t):null,bt({class:"child-status-actions"},lg({onClick:d=>{d.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),lg({onClick:d=>{d.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await hEe(bTt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return lg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:d=>{d.preventDefault(),this.#c(s)}},a)}#f(s,a){let d=AEe(s,a),p=mEe(s,a);return bt({class:"cs-header"},bt({class:"cs-title"},s.name),bt({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},bt({class:"cs-tile"},sn({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),bt({class:"cs-tile"},p.active,s.activeMs?[sn({class:"cs-tile-rule"}),sn({class:"cs-time"},sn(`${tf(d.tools)} tools`),sn(`${tf(d.model)} model`))]:null),p.idle?bt({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?bt({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let d=s.latest,p=[...s.open.map(b=>bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(b.id,b.label),bt({class:"cs-item-meta"},b.interrupted?sn({class:"cs-pill bad"},"interrupted"):sn({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?sn({class:"cs-pill"},"background"):null)),b.said?bt({class:"cs-item-sub cs-mono"},b.said):null)),d?bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(d.id,d.label),bt({class:"cs-item-meta"},this.#h(d.run),d.run.ms!==void 0?sn({class:"cs-dim"},tf(d.run.ms)):null))):null].filter(Boolean);return p.length?bt({class:"cs-section"},bt({class:"cs-h"},"Now"),bt({class:"cs-list"},p)):null}#h(s){let a=lie(s);return sn({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let d=s.commands,{shown:p,more:b}=vEe(d),v=cie(d);return p.length?bt({class:"cs-section"},bt({class:"cs-h"},"Commands",sn({class:"cs-count"},gEe(d))),bt({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?bt({class:"cs-item-sub cs-mono"},S.map((T,D)=>[D?sn({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?bt({class:"cs-more"},yEe(b)):null,v.runs?bt({class:"cs-more"},uie(d)):null):bt({class:"cs-section"},bt({class:"cs-h"},"Commands"),xEe("cs-list",[v.runs?uie(d,!1):"",bEe(d)].filter(Boolean).join(", ")||"none"))}#d(s,a){let d=s.latest,p=d.interrupted?sn({class:"cs-pill bad"},"interrupted"):d.open?sn({class:"cs-pill run"},`running ${tf(a-(d.at??a))}`):this.#h(d);return bt({class:"cs-item-meta"},p,!d.open&&d.ms!==void 0?sn({class:"cs-dim"},tf(d.ms)):null,s.runs>1?sn({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!d.failed)?sn({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?sn({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,aie(s)?sn({class:"cs-pill warn"},aie(s)):null)}#p(s){return bt({class:"cs-section"},bt({class:"cs-h"},"Files written",s.files.length?sn({class:"cs-count"},wEe(s)):null),s.files.length?bt({class:"cs-list cs-files"},s.files.map(a=>bt({class:"cs-item"},bt({class:"cs-item-main"},a.deleted?sn({class:"cs-path",title:fie(a)},EEe(fie(a))):lg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:wTt(a.path)},EEe(a.path)),bt({class:"cs-item-meta"},a.from?sn({class:"cs-dim"},`moved from ${a.from}`):null,sn({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?bt({class:"cs-item-sub"},a.also.length?bt({class:"cs-chips"},sn({class:"cs-dim"},"also "),a.also.map(d=>sn({class:"cs-chip"},d.name,sn({class:"cs-dim"},` ${oie(d.at)}`)))):null,a.blind.map(d=>bt({class:"cs-blind"},d))):null))):xEe("cs-list cs-files"))}#m(s){return s.narration.length?bt({class:"cs-section"},bt({class:"cs-h"},"Narration"),bt({class:"cs-list cs-files"},s.narration.map(a=>bt({class:"cs-item"},a)))):null}#g(s){let{shown:a,earlier:d}=kEe(s);return bt({class:"cs-section"},bt({class:"cs-h"},"Files read",s.read.length?sn({class:"cs-count"},`${s.read.length}`):null),s.read.length?bt({class:"cs-list cs-files"},d?bt({class:"cs-item cs-dim"},`+${d} earlier`):null,a.map(p=>bt({class:"cs-item"},bt({class:"cs-item-main"},lg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:wTt(p.path)},EEe(p.path)),p.times>1?bt({class:"cs-item-meta"},sn({class:"cs-dim"},`\xD7${p.times}`)):null)))):xEe("cs-list cs-files"))}};var die=class extends k4{children=[];enabled=!1;viewing=null;status=new hie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=z6t((await tb.server.listChildren()).sort((d,p)=>d.mtime-p.mtime));if(this.open&&this.#e.length){let d=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,d.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((d,p)=>{let b=this.children[p];return d.id!==b?.id||d.state!==b.state||d.mtime!==b.mtime||d.tokens!==b.tokens})||s.some(d=>d.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let d=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==d}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(d){console.error("[mirror] openChild failed",d)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?bt({class:"children-wrap"}):bt({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return wu({class:["pill","children-pill",_F(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:d=>{d.stopPropagation(),this.open?this.close():this.show()}},sn({class:"glyph-img"},"\u{1F916}"),String(a),sn({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return wu({class:["pill","glyph","children-pill","viewing","on",_F(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:d=>{d.stopPropagation(),this.open?this.close():this.show()}},sn({class:"glyph-img"},"\u{1F916}"),sn({class:"children-doc-label",title:GC(s)},GC(s)),nte(()=>{this.closeChild()}))}popup(){let s=this.rows();return bt({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):bt({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,d)=>this.row(a,d))),this.filterBox(this.children.length,"agent"))}row(s,a){return bt({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:d=>{d.stopPropagation(),this.openChild(s.id)}},sn({class:["children-dot",dEe(s)]}),sn({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},GC(s)),s.kind?sn({class:"children-kind"},s.kind):null,s.model?sn({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,sn({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?sn({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):sn({class:"children-tokens"},s.tokens?BF(s.tokens):""),sn({class:"children-status-link","data-tip":"Where this agent stands: what it is waiting on, its commands, files and hand-backs",onClick:d=>{d.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var ATt=new Map,vTt=(o,s)=>s+`
2195
+ `)}var wEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function AEe(o,s){let a=o.toolMs+(dTt(o).some(d=>!d.background)?pTt(o,s):0);return{tools:a,model:Math.max(0,gTt(o,s)-a)}}var O5n=(o,s)=>{let a=AEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},P5n=o=>o.also.map(s=>`"${s.name}" ${oie(s.at)}`).join(", "),mTt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,vEe=o=>{let s=o.groups.filter(mTt);return{shown:s.slice(0,lTt),more:Math.max(0,s.length-lTt)}},yEe=o=>`+${o} more like these`,cie=o=>{let s=o.groups.filter(a=>!mTt(a));return{runs:s.reduce((a,d)=>a+d.runs-d.open,0),hidden:s.reduce((a,d)=>a+d.hidden,0),ms:s.reduce((a,d)=>a+d.ms,0)}},uie=(o,s=!0)=>{let a=cie(o),d=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${d?`${d}${p} ${b(d)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},aie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var lie=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",fie=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,j5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,kEe=o=>({shown:o.read.slice(-fTt),earlier:Math.max(0,o.read.length-fTt)});var hdr=5*6e4;var F5n=2e3,xEe=(o="cs-list",s="none")=>bt({class:o},bt({class:"cs-item cs-dim"},s)),wTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},EEe=o=>`\u200E${o}\u200E`,hie=class extends mu{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<F5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return bt({class:"messages child-status",key:"child-status"},bt({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return bt({class:"messages child-status",key:"child-status"},this.#f(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#p(s),this.#g(s),bt({class:"child-status-foot"},this.#t?bt({class:"child-status-note err"},this.#t):null,bt({class:"child-status-actions"},lg({onClick:d=>{d.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),lg({onClick:d=>{d.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await hEe(bTt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return lg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:d=>{d.preventDefault(),this.#c(s)}},a)}#f(s,a){let d=AEe(s,a),p=mEe(s,a);return bt({class:"cs-header"},bt({class:"cs-title"},s.name),bt({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},bt({class:"cs-tile"},sn({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),bt({class:"cs-tile"},p.active,s.activeMs?[sn({class:"cs-tile-rule"}),sn({class:"cs-time"},sn(`${tf(d.tools)} tools`),sn(`${tf(d.model)} model`))]:null),p.idle?bt({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?bt({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let d=s.latest,p=[...s.open.map(b=>bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(b.id,b.label),bt({class:"cs-item-meta"},b.interrupted?sn({class:"cs-pill bad"},"interrupted"):sn({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?sn({class:"cs-pill"},"background"):null)),b.said?bt({class:"cs-item-sub cs-mono"},b.said):null)),d?bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(d.id,d.label),bt({class:"cs-item-meta"},this.#h(d.run),d.run.ms!==void 0?sn({class:"cs-dim"},tf(d.run.ms)):null))):null].filter(Boolean);return p.length?bt({class:"cs-section"},bt({class:"cs-h"},"Now"),bt({class:"cs-list"},p)):null}#h(s){let a=lie(s);return sn({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let d=s.commands,{shown:p,more:b}=vEe(d),v=cie(d);return p.length?bt({class:"cs-section"},bt({class:"cs-h"},"Commands",sn({class:"cs-count"},gEe(d))),bt({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return bt({class:"cs-item"},bt({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?bt({class:"cs-item-sub cs-mono"},S.map((T,D)=>[D?sn({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?bt({class:"cs-more"},yEe(b)):null,v.runs?bt({class:"cs-more"},uie(d)):null):bt({class:"cs-section"},bt({class:"cs-h"},"Commands"),xEe("cs-list",[v.runs?uie(d,!1):"",bEe(d)].filter(Boolean).join(", ")||"none"))}#d(s,a){let d=s.latest,p=d.interrupted?sn({class:"cs-pill bad"},"interrupted"):d.open?sn({class:"cs-pill run"},`running ${tf(a-(d.at??a))}`):this.#h(d);return bt({class:"cs-item-meta"},p,!d.open&&d.ms!==void 0?sn({class:"cs-dim"},tf(d.ms)):null,s.runs>1?sn({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!d.failed)?sn({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?sn({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,aie(s)?sn({class:"cs-pill warn"},aie(s)):null)}#p(s){return bt({class:"cs-section"},bt({class:"cs-h"},"Files written",s.files.length?sn({class:"cs-count"},wEe(s)):null),s.files.length?bt({class:"cs-list cs-files"},s.files.map(a=>bt({class:"cs-item"},bt({class:"cs-item-main"},a.deleted?sn({class:"cs-path",title:fie(a)},EEe(fie(a))):lg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:wTt(a.path)},EEe(a.path)),bt({class:"cs-item-meta"},a.from?sn({class:"cs-dim"},`moved from ${a.from}`):null,sn({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?bt({class:"cs-item-sub"},a.also.length?bt({class:"cs-chips"},sn({class:"cs-dim"},"also "),a.also.map(d=>sn({class:"cs-chip"},d.name,sn({class:"cs-dim"},` ${oie(d.at)}`)))):null,a.blind.map(d=>bt({class:"cs-blind"},d))):null))):xEe("cs-list cs-files"))}#m(s){return s.narration.length?bt({class:"cs-section"},bt({class:"cs-h"},"Narration"),bt({class:"cs-list cs-files"},s.narration.map(a=>bt({class:"cs-item"},a)))):null}#g(s){let{shown:a,earlier:d}=kEe(s);return bt({class:"cs-section"},bt({class:"cs-h"},"Files read",s.read.length?sn({class:"cs-count"},`${s.read.length}`):null),s.read.length?bt({class:"cs-list cs-files"},d?bt({class:"cs-item cs-dim"},`+${d} earlier`):null,a.map(p=>bt({class:"cs-item"},bt({class:"cs-item-main"},lg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:wTt(p.path)},EEe(p.path)),p.times>1?bt({class:"cs-item-meta"},sn({class:"cs-dim"},`\xD7${p.times}`)):null)))):xEe("cs-list cs-files"))}};var die=class extends k4{children=[];enabled=!1;viewing=null;status=new hie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=z6t((await tb.server.listChildren()).sort((d,p)=>d.mtime-p.mtime));if(this.open&&this.#e.length){let d=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,d.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((d,p)=>{let b=this.children[p];return d.id!==b?.id||d.state!==b.state||d.mtime!==b.mtime||d.tokens!==b.tokens})||s.some(d=>d.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let d=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==d}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(d){console.error("[mirror] openChild failed",d)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?bt({class:"children-wrap"}):bt({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return wu({class:["pill","children-pill",_F(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:d=>{d.stopPropagation(),this.open?this.close():this.show()}},sn({class:"glyph-img"},"\u{1F916}"),String(a),sn({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return wu({class:["pill","glyph","children-pill","viewing","on",_F(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:d=>{d.stopPropagation(),this.open?this.close():this.show()}},sn({class:"glyph-img"},"\u{1F916}"),sn({class:"children-doc-label",title:GC(s)},GC(s)),nte(()=>{this.closeChild()}))}popup(){let s=this.rows();return bt({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):bt({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,d)=>this.row(a,d))),this.filterBox(this.children.length,"agent"))}row(s,a){return bt({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:d=>{d.stopPropagation(),this.openChild(s.id)}},sn({class:["children-dot",dEe(s)]}),sn({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},GC(s)),s.kind?sn({class:"children-kind"},s.kind):null,s.model?sn({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,sn({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?sn({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):sn({class:"children-tokens"},s.tokens?BF(s.tokens):""),sn({class:"children-status-link",onClick:d=>{d.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var ATt=new Map,vTt=(o,s)=>s+`
2196
2196
 
2197
2197
  ---
2198
2198
 
@@ -2192,7 +2192,7 @@ ${nSt(b)}`};let v=ZCt(h.code,{jsxImportSource:p.ts?.jsxImportSource});if(v.error
2192
2192
  `).map(v=>v.replace(/\r$/,""));if(a.length&&a[a.length-1]===""&&a.pop(),s)return a.map(v=>({kind:"add",text:v}));let h=[],p=!1,b=!1;for(let v of a){if(v.startsWith("@@")){b&&h.push({kind:"gap",text:"\u22EF"}),b=!0,p=!0;continue}if(!p){v.startsWith("Binary file")&&h.push({kind:"ctx",text:v});continue}v.startsWith("\\")||(v.startsWith("+")?h.push({kind:"add",text:v.slice(1)}):v.startsWith("-")?h.push({kind:"del",text:v.slice(1)}):h.push({kind:"ctx",text:v.slice(1)}))}return h}function H5n(o,s,a){let h=$5n(o,s),p=o.length>F5n?"txt":a.split(".").pop()??"",b=[],v=[];for(let P of h)(P.kind==="ctx"||P.kind==="del")&&b.push(P.text),(P.kind==="ctx"||P.kind==="add")&&v.push(P.text);let w=dEe(b.join(`
2193
2193
  `),p),S=dEe(v.join(`
2194
2194
  `),p),T=0,B=0,D=[];for(let P of h){if(P.kind==="gap"){D.push('<div class="udiff-gap">\u22EF</div>');continue}let j=P.kind==="del"?w[T++]:(P.kind==="add"||T++,S[B++]);D.push(`<div class="udiff-line${P.kind==="add"?" udiff-add":P.kind==="del"?" udiff-del":""}">${j??""}</div>`)}return{kinds:h.map(P=>P.kind),bodyHtml:D.join("")}}var uie=class extends x4{files=[];repo=!0;root="";viewing;#e=0;#t=!1;#n=()=>document.getElementById(bEe);#r=new fte(this.#n);#s=[];#i=-1;keepOpenSelector=".gitdiff-wrap";filterId="gitdiff-filter";listSelector=".gitdiff-list";onActivate(s){let a=this.rows()[s];a&&this.openDiff(a)}onAttached(){this.refreshFiles(),setInterval(()=>this.refreshFiles(),3e3),setInterval(()=>{this.viewing&&this.refreshDiff()},1500)}rows(){let s=this.filter.trim().toLowerCase();return s?this.files.filter(a=>a.path.toLowerCase().includes(s)):this.files}async refreshFiles(){try{let{repo:s,root:a,files:h}=await tb.server.gitChangedFiles(),p=s!==this.repo||h.length!==this.files.length||h.some((b,v)=>{let w=this.files[v];return b.path!==w?.path||b.status!==w.status||b.add!==w.add||b.del!==w.del||b.binary!==w.binary});this.repo=s,this.root=a,this.files=h,p&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] gitChangedFiles failed",s)}}#o(s,a,h){this.viewing?.path!==s&&(this.#s=[]),this.viewing={path:s,status:a,text:h.text,truncated:!!h.truncated,...H5n(h.text,!!h.untracked,s)},this.#e++,this.update()}async openDiff(s){try{let a=await tb.server.gitDiff(s.path);if(!a.ok){console.error("[mirror] gitDiff failed:",a.error);return}this.#o(s.path,s.status,a),this.#t=!0,this.close()}catch(a){console.error("[mirror] gitDiff failed",a)}}async refreshDiff(){let s=this.viewing;if(s)try{let a=await tb.server.gitDiff(s.path);if(this.viewing!==s||!a.ok||a.text===s.text)return;this.#o(s.path,s.status,a)}catch(a){console.error("[mirror] gitDiff refresh failed",a)}}closeDoc(){this.#r.release(),this.viewing=void 0,this.update()}show(){this.beginOpen(),this.refreshFiles(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.files.length;return!this.repo||s===0&&!this.viewing&&!this.open?ct({class:"gitdiff-wrap"}):ct({class:"gitdiff-wrap pop-center"},this.viewing?this.viewingPill():Po({class:["pill","glyph","gitdiff-pill",this.open?"on":""],"data-tip":`${s} changed file${s===1?"":"s"} \u2014 view a diff`,ariaLabel:`${s} changed file${s===1?"":"s"}`,onClick:a=>{a.stopPropagation(),this.open?this.close():this.show()}},Z1("diff"),en({class:"gitdiff-count"},String(s))),this.open?this.popup():null)}viewingPill(){let s=this.viewing,a=s.kinds.filter(p=>p==="add").length,h=s.kinds.filter(p=>p==="del").length;return Po({class:["pill","glyph","gitdiff-pill","viewing","on"],"data-tip":`${this.files.length} changed file${this.files.length===1?"":"s"} \u2014 switch file`,onClick:p=>{p.stopPropagation(),this.open?this.close():this.show()}},en({class:["gitdiff-status",`s-${s.status}`]},s.status),en({class:"gitdiff-doc-path",title:`Open ${s.path}`,onClick:p=>{p.stopPropagation(),tb.server.openFile(`${this.root}/${s.path}`)}},s.path),en({class:"gitdiff-counts"},en({class:"count-add"},`+${a}`),en({class:"count-del"},`\u2212${h}`)),ote(()=>this.closeDoc()))}popup(){let s=this.rows();return ct({class:"servers-pop gitdiff-pop"},s.length===0?this.emptyState("No changes in the working tree."):ct({class:"gitdiff-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.files.length,"file"))}row(s,a){return ct({class:["gitdiff-row",a===this.highlighted?"active":"",this.viewing?.path===s.path?"viewing":""],onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openDiff(s)}},en({class:["gitdiff-status",`s-${s.status}`]},s.status),en({class:"gitdiff-path",title:s.path},s.path),s.add!==void 0||s.del!==void 0?en({class:"gitdiff-counts"},en({class:"count-add"},`+${s.add??0}`),en({class:"count-del"},`\u2212${s.del??0}`)):s.status==="U"?en({class:"gitdiff-counts"},en({class:"count-add"},"new")):en({class:"gitdiff-counts"},en({},s.binary?"binary":"\u2014")))}docView(){let s=this.viewing;return ct({class:"diff-doc",onKeyDown:a=>{a.key==="Escape"&&(a.stopPropagation(),this.closeDoc())}},ct({class:"diff-doc-scroll"},ct({class:"diff-doc-body",id:bEe,tabIndex:0,onMounted:a=>a.focus(),onScroll:()=>this.#r.sync()},s.kinds.length===0?ct({class:"diff-doc-empty"},"No changes."):ct({class:"diff-doc-code",key:`diff-code-${this.#e}`,onMounted:a=>{a.innerHTML=s.bodyHtml,this.#c(a),this.#u(a)}},""),s.truncated?ct({class:"diff-doc-trunc"},"Diff truncated \u2014 file too large to show in full."):null),s.kinds.length?this.#r.view(this.#s,{class:"diff-ruler",title:"Jump to a change",label:"Diff scroll position",controls:bEe}):null))}#c(s){if(!this.#t)return;this.#t=!1;let a=s.querySelector(".udiff-add, .udiff-del"),h=this.#n();a&&h&&(h.scrollTop=a.offsetTop-h.clientHeight/3)}#u(s){this.#i!==this.#e&&(this.#i=this.#e,requestAnimationFrame(()=>{this.#h(s),this.update(),this.#r.sync()}))}#h(s){let a=this.viewing,h=this.#n();if(!a||!h?.scrollHeight)return;let p=h.scrollHeight,b=[];for(let v=0;v<a.kinds.length;v++){let w=a.kinds[v];if(w!=="add"&&w!=="del")continue;let S=v;for(;S+1<a.kinds.length&&a.kinds[S+1]===w;)S++;let T=s.children[v],B=s.children[S];T&&B&&b.push({top:T.offsetTop/p,height:(B.offsetTop+B.offsetHeight-T.offsetTop)/p,class:w}),v=S}this.#s=b}};async function mEe(o){try{return await navigator.clipboard.writeText(o),!0}catch{}let s=document.createElement("textarea");s.value=o,s.style.cssText="position:fixed;top:0;left:0;opacity:0",document.body.appendChild(s),s.select();try{return document.execCommand("copy")}catch{return!1}finally{s.remove()}}var lD=class extends Jc{done=!1;#e;constructor(s){super(),this.#e=s}setText(s){this.#e=s}flash(){mEe(this.#e),this.done=!0,this.update(),setTimeout(()=>{this.done=!1,this.update()},600)}view(){return Po({class:["overlay-pill","copy",this.done?"done":""],onClick:s=>{s.stopPropagation(),this.flash()}},this.done?"copied":"copy")}};var gTt=".typebulb/paste",bTt={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"},JC=o=>o.label||o.kind||"agent",wEe=o=>o.failing&&o.state!=="stopped"?"failing":o.state,AEe=o=>`Open this ${o.kind?`${o.kind} `:""}agent's transcript`;var mTt=8,wTt=30,xdr=3*6e4;var aie=o=>new Date(o).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});var vEe=o=>[o.runs?`${o.runs} run, ${o.failed} failed`:"",yEe(o)].filter(Boolean).join(", ")||"none",yEe=o=>o.lookups?`${o.lookups} ${o.lookups===1?"lookup":"lookups"}`:"";var vTt=o=>o.open.filter(s=>!s.interrupted);var yTt=(o,s)=>o.state==="running"?Math.max(0,s-o.asOf):0,kTt=(o,s)=>o.activeMs+yTt(o,s);function q5n(o,s){let a=o.state==="finished"?vTt(o).filter(h=>h.background):[];return a.length?`finished, background call running ${tf(s-(a[0].at??s))}${a.length>1?` (+${a.length-1} more)`:""}`:o.state}var kEe=(o,s)=>({state:q5n(o,s),active:`${tf(kTt(o,s))} active`,idle:o.idleMs?`${tf(o.idleMs)} idle`:""}),Q5n=(o,s)=>{let a=kEe(o,s);return[a.state,a.active,a.idle].filter(Boolean).join(" \xB7 ")},ATt=(o,s)=>o.interrupted?`${o.label}: interrupted, its process has ended`:`${o.label}, ${tf(s-(o.at??s))}${o.background?" (background)":""}`,G5n=(o,s)=>`nothing open, last entry ${tf(s-o.asOf)} ago`;function J5n(o,s){if(!o.open.length)return[`Now: ${G5n(o,s)}`,...o.latest?[`Latest: ${o.latest.label} \xB7 ${die(o.latest.run)}${o.latest.run.ms!==void 0?` after ${tf(o.latest.run.ms)}`:""}`]:[]];let a=(h,p)=>h.said?[`${p}"${h.said}"`]:[];return o.open.length===1?[`Now: ${ATt(o.open[0],s)}`,...a(o.open[0]," ")]:["Now:",...o.open.flatMap(h=>[` ${ATt(h,s)}`,...a(h," ")])]}function U5n(o,s){let a=o.latest;return`latest: ${a.interrupted?"interrupted":a.open?`running ${tf(s-(a.at??s))}`:`${die(a)}${a.ms!==void 0?` after ${tf(a.ms)}`:""}`}${o.streak>=2?`, failed ${o.streak} in a row`:""}`}function xTt(o,s){let a=[`Sub-agent "${o.name}" (${o.id}): ${Q5n(o,s)}${o.asOf?` \xB7 as of ${aie(o.asOf)}`:""}`,""];a.push(...J5n(o,s));let h=o.commands;a.push(`Commands: ${vEe(h)}`);let{shown:p,more:b}=CEe(h);for(let S of p){let T=hie(S);a.push(` ${S.cmd} \xD7${S.runs}${S.failed?`, ${S.failed} failed`:""}${T?` \xB7 ${T}`:""}`,` ${U5n(S,s)}`);let B=[S.latest.first,S.latest.last].filter(Boolean).map(D=>`"${D}"`).join(" \u2026 ");B&&a.push(` ${B}`)}b&&a.push(` ${SEe(b)}`),lie(h).runs&&a.push(` ${fie(h)}`),o.activeMs&&a.push(`Time: ${z5n(o,s)}`),o.narration.length&&a.push("Narration:",...o.narration.map(S=>` ${S}`)),a.push(`Files written: ${xEe(o)}`);for(let S of o.files){let T=S.also.length?` also ${K5n(S)}`:"";a.push(` ${pie(S)}${S.ignored?" (ignored)":S.committed?" (committed)":""}${T}`,...S.blind.map(B=>` ${B}`))}let{shown:v,earlier:w}=IEe(o);return a.push(`Files read: ${o.read.length||"none"}`,...w?[` +${w} earlier`]:[],...v.map(S=>` ${W5n(S)}`)),a.join(`
2195
- `)}var xEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function EEe(o,s){let a=o.toolMs+(vTt(o).some(h=>!h.background)?yTt(o,s):0);return{tools:a,model:Math.max(0,kTt(o,s)-a)}}var z5n=(o,s)=>{let a=EEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},K5n=o=>o.also.map(s=>`"${s.name}" ${aie(s.at)}`).join(", "),ETt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,CEe=o=>{let s=o.groups.filter(ETt);return{shown:s.slice(0,mTt),more:Math.max(0,s.length-mTt)}},SEe=o=>`+${o} more like these`,lie=o=>{let s=o.groups.filter(a=>!ETt(a));return{runs:s.reduce((a,h)=>a+h.runs-h.open,0),hidden:s.reduce((a,h)=>a+h.hidden,0),ms:s.reduce((a,h)=>a+h.ms,0)}},fie=(o,s=!0)=>{let a=lie(o),h=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${h?`${h}${p} ${b(h)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},hie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var die=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",pie=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,W5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,IEe=o=>({shown:o.read.slice(-wTt),earlier:Math.max(0,o.read.length-wTt)});var Edr=5*6e4;var Y5n=2e3,TEe=(o="cs-list",s="none")=>ct({class:o},ct({class:"cs-item cs-dim"},s)),CTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},_Ee=o=>`\u200E${o}\u200E`,gie=class extends Jc{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<Y5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return ct({class:"messages child-status",key:"child-status"},ct({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return ct({class:"messages child-status",key:"child-status"},this.#h(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#b(s),this.#p(s),ct({class:"child-status-foot"},this.#t?ct({class:"child-status-note err"},this.#t):null,ct({class:"child-status-actions"},fg({onClick:h=>{h.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),fg({onClick:h=>{h.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await mEe(xTt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return fg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:h=>{h.preventDefault(),this.#c(s)}},a)}#h(s,a){let h=EEe(s,a),p=kEe(s,a);return ct({class:"cs-header"},ct({class:"cs-title"},s.name),ct({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},ct({class:"cs-tile"},en({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),ct({class:"cs-tile"},p.active,s.activeMs?[en({class:"cs-tile-rule"}),en({class:"cs-time"},en(`${tf(h.tools)} tools`),en(`${tf(h.model)} model`))]:null),p.idle?ct({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?ct({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let h=s.latest,p=[...s.open.map(b=>ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(b.id,b.label),ct({class:"cs-item-meta"},b.interrupted?en({class:"cs-pill bad"},"interrupted"):en({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?en({class:"cs-pill"},"background"):null)),b.said?ct({class:"cs-item-sub cs-mono"},b.said):null)),h?ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(h.id,h.label),ct({class:"cs-item-meta"},this.#f(h.run),h.run.ms!==void 0?en({class:"cs-dim"},tf(h.run.ms)):null))):null].filter(Boolean);return p.length?ct({class:"cs-section"},ct({class:"cs-h"},"Now"),ct({class:"cs-list"},p)):null}#f(s){let a=die(s);return en({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let h=s.commands,{shown:p,more:b}=CEe(h),v=lie(h);return p.length?ct({class:"cs-section"},ct({class:"cs-h"},"Commands",en({class:"cs-count"},vEe(h))),ct({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?ct({class:"cs-item-sub cs-mono"},S.map((T,B)=>[B?en({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?ct({class:"cs-more"},SEe(b)):null,v.runs?ct({class:"cs-more"},fie(h)):null):ct({class:"cs-section"},ct({class:"cs-h"},"Commands"),TEe("cs-list",[v.runs?fie(h,!1):"",yEe(h)].filter(Boolean).join(", ")||"none"))}#d(s,a){let h=s.latest,p=h.interrupted?en({class:"cs-pill bad"},"interrupted"):h.open?en({class:"cs-pill run"},`running ${tf(a-(h.at??a))}`):this.#f(h);return ct({class:"cs-item-meta"},p,!h.open&&h.ms!==void 0?en({class:"cs-dim"},tf(h.ms)):null,s.runs>1?en({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!h.failed)?en({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?en({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,hie(s)?en({class:"cs-pill warn"},hie(s)):null)}#b(s){return ct({class:"cs-section"},ct({class:"cs-h"},"Files written",s.files.length?en({class:"cs-count"},xEe(s)):null),s.files.length?ct({class:"cs-list cs-files"},s.files.map(a=>ct({class:"cs-item"},ct({class:"cs-item-main"},a.deleted?en({class:"cs-path",title:pie(a)},_Ee(pie(a))):fg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:CTt(a.path)},_Ee(a.path)),ct({class:"cs-item-meta"},a.from?en({class:"cs-dim"},`moved from ${a.from}`):null,en({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?ct({class:"cs-item-sub"},a.also.length?ct({class:"cs-chips"},en({class:"cs-dim"},"also "),a.also.map(h=>en({class:"cs-chip"},h.name,en({class:"cs-dim"},` ${aie(h.at)}`)))):null,a.blind.map(h=>ct({class:"cs-blind"},h))):null))):TEe("cs-list cs-files"))}#m(s){return s.narration.length?ct({class:"cs-section"},ct({class:"cs-h"},"Narration"),ct({class:"cs-list cs-files"},s.narration.map(a=>ct({class:"cs-item"},a)))):null}#p(s){let{shown:a,earlier:h}=IEe(s);return ct({class:"cs-section"},ct({class:"cs-h"},"Files read",s.read.length?en({class:"cs-count"},`${s.read.length}`):null),s.read.length?ct({class:"cs-list cs-files"},h?ct({class:"cs-item cs-dim"},`+${h} earlier`):null,a.map(p=>ct({class:"cs-item"},ct({class:"cs-item-main"},fg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:CTt(p.path)},_Ee(p.path)),p.times>1?ct({class:"cs-item-meta"},en({class:"cs-dim"},`\xD7${p.times}`)):null)))):TEe("cs-list cs-files"))}};var bie=class extends x4{children=[];enabled=!1;viewing=null;status=new gie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=eyt((await tb.server.listChildren()).sort((h,p)=>h.mtime-p.mtime));if(this.open&&this.#e.length){let h=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,h.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((h,p)=>{let b=this.children[p];return h.id!==b?.id||h.state!==b.state||h.mtime!==b.mtime||h.tokens!==b.tokens})||s.some(h=>h.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let h=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==h}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(h){console.error("[mirror] openChild failed",h)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?ct({class:"children-wrap"}):ct({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return Po({class:["pill","children-pill",NF(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},en({class:"glyph-img"},"\u{1F916}"),String(a),en({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return Po({class:["pill","glyph","children-pill","viewing","on",NF(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},en({class:"glyph-img"},"\u{1F916}"),en({class:"children-doc-label",title:JC(s)},JC(s)),ote(()=>{this.closeChild()}))}popup(){let s=this.rows();return ct({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):ct({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.children.length,"agent"))}row(s,a){return ct({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openChild(s.id)}},en({class:["children-dot",wEe(s)]}),en({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},JC(s)),s.kind?en({class:"children-kind"},s.kind):null,s.model?en({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,en({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?en({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):en({class:"children-tokens"},s.tokens?AC(s.tokens):""),en({class:"children-status-link","data-tip":"Where this agent stands: what it is waiting on, its commands, files and hand-backs",onClick:h=>{h.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var STt=new Map,ITt=(o,s)=>s+`
2195
+ `)}var xEe=o=>{let s=o.files.filter(a=>!a.committed&&!a.ignored).length;return o.files.length?`${o.files.length} (${s} uncommitted)`:"none"};function EEe(o,s){let a=o.toolMs+(vTt(o).some(h=>!h.background)?yTt(o,s):0);return{tools:a,model:Math.max(0,kTt(o,s)-a)}}var z5n=(o,s)=>{let a=EEe(o,s);return`${tf(a.tools)} in tools, ${tf(a.model)} in the model`},K5n=o=>o.also.map(s=>`"${s.name}" ${aie(s.at)}`).join(", "),ETt=o=>o.failed>0||!!o.long||o.runs>=3||o.tags.length>0,CEe=o=>{let s=o.groups.filter(ETt);return{shown:s.slice(0,mTt),more:Math.max(0,s.length-mTt)}},SEe=o=>`+${o} more like these`,lie=o=>{let s=o.groups.filter(a=>!ETt(a));return{runs:s.reduce((a,h)=>a+h.runs-h.open,0),hidden:s.reduce((a,h)=>a+h.hidden,0),ms:s.reduce((a,h)=>a+h.ms,0)}},fie=(o,s=!0)=>{let a=lie(o),h=a.runs-a.hidden,p=s?" other":"",b=S=>S===1?"run":"runs",v=`with ${a.hidden===1?"its":"their"} exit hidden by a pipe`;return`${h?`${h}${p} ${b(h)} passed${a.hidden?`, ${a.hidden} ${v}`:""}`:`${a.hidden}${p} ${b(a.hidden)} ${v}`}, ${tf(a.ms)} in all`},hie=o=>[...o.tags,o.long].filter(Boolean).join(", ");var die=o=>o.hidden?"exit hidden":o.outcome&&o.outcome!=="completed"&&o.outcome!=="failed"&&o.exit===void 0?o.outcome:o.exit!==void 0?`exit ${o.exit}`:o.failed?"error":"ok",pie=o=>o.deleted?`${o.path} (deleted)`:o.from?`${o.path} (moved from ${o.from})`:o.path,W5n=o=>o.times>1?`${o.path} \xD7${o.times}`:o.path,IEe=o=>({shown:o.read.slice(-wTt),earlier:Math.max(0,o.read.length-wTt)});var Edr=5*6e4;var Y5n=2e3,TEe=(o="cs-list",s="none")=>ct({class:o},ct({class:"cs-item cs-dim"},s)),CTt=o=>s=>{s.preventDefault(),tb.server.openFile(o)},_Ee=o=>`\u200E${o}\u200E`,gie=class extends Jc{open=!1;#e=null;#t="";#n="";#r=!1;#s=0;#i;bind(s){this.#i=s}toggle(){this.open=!this.open,this.sync(),this.#i?.onChange()}show(s){this.open=s,this.#e=null,this.#t="",this.#s=0,this.sync()}async sync(){let s=this.#i?.id();if(!(!this.open||!s||this.#r||Date.now()-this.#s<Y5n)){this.#r=!0;try{let a=await tb.server.childStatus(s);s===this.#i?.id()&&(a?.ok?(this.#e=a.report,this.#t=""):this.#t=a?.error??"could not read its status")}catch{this.#t="could not read its status"}this.#r=!1,this.#s=Date.now(),this.#i?.onChange()}}view(){let s=this.#e;if(!s)return ct({class:"messages child-status",key:"child-status"},ct({class:"child-status-pending"},this.#t||"Loading\u2026"));let a=Date.now();return ct({class:"messages child-status",key:"child-status"},this.#h(s,a),this.#l(s,a),this.#a(s,a),this.#m(s),this.#b(s),this.#p(s),ct({class:"child-status-foot"},this.#t?ct({class:"child-status-note err"},this.#t):null,ct({class:"child-status-actions"},fg({onClick:h=>{h.preventDefault(),this.#o(s)}},this.#n||"Copy Status"),fg({onClick:h=>{h.preventDefault(),this.toggle()}},"Raw Transcript"))))}async#o(s){this.#n=await mEe(xTt(s,Date.now()))?"Copied":"Copy failed",setTimeout(()=>{this.#n="",this.#i?.onChange()},1500),this.#i?.onChange()}#c(s){this.open=!1,this.#i?.reveal(s)}#u(s,a){return fg({class:"cs-mono cs-link",title:"Show in the transcript",onClick:h=>{h.preventDefault(),this.#c(s)}},a)}#h(s,a){let h=EEe(s,a),p=kEe(s,a);return ct({class:"cs-header"},ct({class:"cs-title"},s.name),ct({class:["cs-subtitle",s.state==="failing"?"cs-bad":""]},ct({class:"cs-tile"},en({class:["children-dot",s.state==="finished"?"done":s.state]}),p.state),ct({class:"cs-tile"},p.active,s.activeMs?[en({class:"cs-tile-rule"}),en({class:"cs-time"},en(`${tf(h.tools)} tools`),en(`${tf(h.model)} model`))]:null),p.idle?ct({class:"cs-tile",title:"Time it sat finished, waiting for a message to wake it. Not counted in active time."},p.idle):null,s.asOf?ct({class:"cs-tile"},`last entry ${tf(a-s.asOf)} ago`):null))}#l(s,a){let h=s.latest,p=[...s.open.map(b=>ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(b.id,b.label),ct({class:"cs-item-meta"},b.interrupted?en({class:"cs-pill bad"},"interrupted"):en({class:"cs-pill run"},`running ${tf(a-(b.at??a))}`),b.background&&!b.interrupted?en({class:"cs-pill"},"background"):null)),b.said?ct({class:"cs-item-sub cs-mono"},b.said):null)),h?ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(h.id,h.label),ct({class:"cs-item-meta"},this.#f(h.run),h.run.ms!==void 0?en({class:"cs-dim"},tf(h.run.ms)):null))):null].filter(Boolean);return p.length?ct({class:"cs-section"},ct({class:"cs-h"},"Now"),ct({class:"cs-list"},p)):null}#f(s){let a=die(s);return en({class:["cs-pill",s.failed?"bad":!s.hidden&&(a==="ok"||a.startsWith("exit"))?"ok":""]},a)}#a(s,a){let h=s.commands,{shown:p,more:b}=CEe(h),v=lie(h);return p.length?ct({class:"cs-section"},ct({class:"cs-h"},"Commands",en({class:"cs-count"},vEe(h))),ct({class:"cs-list"},p.map(w=>{let S=[w.latest.first,w.latest.last].filter(Boolean);return ct({class:"cs-item"},ct({class:"cs-item-main"},this.#u(w.latest.id,w.cmd),this.#d(w,a)),S.length?ct({class:"cs-item-sub cs-mono"},S.map((T,B)=>[B?en({class:"cs-dim"}," \u2026 "):null,T])):null)})),b?ct({class:"cs-more"},SEe(b)):null,v.runs?ct({class:"cs-more"},fie(h)):null):ct({class:"cs-section"},ct({class:"cs-h"},"Commands"),TEe("cs-list",[v.runs?fie(h,!1):"",yEe(h)].filter(Boolean).join(", ")||"none"))}#d(s,a){let h=s.latest,p=h.interrupted?en({class:"cs-pill bad"},"interrupted"):h.open?en({class:"cs-pill run"},`running ${tf(a-(h.at??a))}`):this.#f(h);return ct({class:"cs-item-meta"},p,!h.open&&h.ms!==void 0?en({class:"cs-dim"},tf(h.ms)):null,s.runs>1?en({class:"cs-dim"},`\xD7${s.runs}`):null,s.failed&&(s.runs>1||!h.failed)?en({class:"cs-bad"},`${s.failed} failed`):null,s.streak>=2?en({class:"cs-pill bad"},`failed ${s.streak} in a row`):null,hie(s)?en({class:"cs-pill warn"},hie(s)):null)}#b(s){return ct({class:"cs-section"},ct({class:"cs-h"},"Files written",s.files.length?en({class:"cs-count"},xEe(s)):null),s.files.length?ct({class:"cs-list cs-files"},s.files.map(a=>ct({class:"cs-item"},ct({class:"cs-item-main"},a.deleted?en({class:"cs-path",title:pie(a)},_Ee(pie(a))):fg({class:"cs-path cs-link",title:`Open ${a.path}`,onClick:CTt(a.path)},_Ee(a.path)),ct({class:"cs-item-meta"},a.from?en({class:"cs-dim"},`moved from ${a.from}`):null,en({class:["cs-pill",a.committed||a.ignored?"":"run"]},a.ignored?"ignored":a.committed?"committed":"uncommitted"))),a.also.length||a.blind.length?ct({class:"cs-item-sub"},a.also.length?ct({class:"cs-chips"},en({class:"cs-dim"},"also "),a.also.map(h=>en({class:"cs-chip"},h.name,en({class:"cs-dim"},` ${aie(h.at)}`)))):null,a.blind.map(h=>ct({class:"cs-blind"},h))):null))):TEe("cs-list cs-files"))}#m(s){return s.narration.length?ct({class:"cs-section"},ct({class:"cs-h"},"Narration"),ct({class:"cs-list cs-files"},s.narration.map(a=>ct({class:"cs-item"},a)))):null}#p(s){let{shown:a,earlier:h}=IEe(s);return ct({class:"cs-section"},ct({class:"cs-h"},"Files read",s.read.length?en({class:"cs-count"},`${s.read.length}`):null),s.read.length?ct({class:"cs-list cs-files"},h?ct({class:"cs-item cs-dim"},`+${h} earlier`):null,a.map(p=>ct({class:"cs-item"},ct({class:"cs-item-main"},fg({class:"cs-path cs-link",title:`Open ${p.path}`,onClick:CTt(p.path)},_Ee(p.path)),p.times>1?ct({class:"cs-item-meta"},en({class:"cs-dim"},`\xD7${p.times}`)):null)))):TEe("cs-list cs-files"))}};var bie=class extends x4{children=[];enabled=!1;viewing=null;status=new gie;#e=[];#t=null;#n=0;get swaps(){return this.#n}keepOpenSelector=".children-wrap";filterId="children-filter";listSelector=".children-list";onActivate(s){let a=this.rows()[s];a&&this.openChild(a.id)}onAttached(){setInterval(()=>{this.refresh()},3e3)}rows(){let s=this.filter.trim().toLowerCase();return s?this.children.filter(a=>[a.kind,a.label].filter(Boolean).join(" ").toLowerCase().includes(s)):this.children}get running(){return this.children.filter(s=>s.state==="running").length}async refresh(){if(this.enabled)try{let s=eyt((await tb.server.listChildren()).sort((h,p)=>h.mtime-p.mtime));if(this.open&&this.#e.length){let h=new Map(this.#e.map((p,b)=>[p,b]));s=s.map((p,b)=>[p,h.get(p.id)??this.#e.length+b]).sort((p,b)=>p[1]-b[1]).map(([p])=>p)}let a=s.length!==this.children.length||s.some((h,p)=>{let b=this.children[p];return h.id!==b?.id||h.state!==b.state||h.mtime!==b.mtime||h.tokens!==b.tokens})||s.some(h=>h.state==="running");this.children=s,this.#r(),a&&(this.update(),this.keepBottom())}catch(s){console.error("[mirror] listChildren failed",s)}}syncFromPoll(s,a){if(a!==this.#n)return!1;let h=this.viewing?.id??null;return this.#t=s,this.#r(),s&&!this.viewing&&this.refresh(),(this.viewing?.id??null)!==h}reset(){this.children=[],this.refresh()}#r(){this.viewing=this.#t?this.children.find(s=>s.id===this.#t)??null:null}async openChild(s,a=!1){this.close(),this.parent.messageList.stickToBottomNextRender(),this.#n++;try{await tb.server.openChild(s),this.#n++,this.#t=s,this.#r(),this.status.show(a),this.update()}catch(h){console.error("[mirror] openChild failed",h)}this.refresh()}async closeChild(){this.parent.messageList.stickToBottomNextRender(),this.status.open=!1,this.#n++;try{await tb.server.closeChild(),this.#n++,this.#t=null,this.#r(),this.update()}catch(s){console.error("[mirror] closeChild failed",s)}}show(){this.beginOpen(),this.#e=this.children.map(s=>s.id),this.refresh(),this.refreshList(),this.armClose(),this.focusFilter()}view(){let s=this.children.length;return!this.enabled||s===0&&!this.viewing&&!this.open?ct({class:"children-wrap"}):ct({class:"children-wrap pop-center"},this.viewing?this.viewingPill():this.chip(s),this.open?this.popup():null)}chip(s){let a=this.running;return Po({class:["pill","children-pill",NF(a>0),this.open?"on":""],"data-tip":a?`${a} of ${s} agent${s===1?"":"s"} still working \u2014 open one`:`${s} agent${s===1?"":"s"} this session spawned \u2014 open one`,ariaLabel:a?`Agents (${a} of ${s} running)`:`Agents (${s})`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},en({class:"glyph-img"},"\u{1F916}"),String(a),en({class:"glyph-img"},"\u{1F916}"))}viewingPill(){let s=this.viewing,a=this.children.length;return Po({class:["pill","glyph","children-pill","viewing","on",NF(s.state==="running")],"data-tip":`${a} agent${a===1?"":"s"} \u2014 switch`,onClick:h=>{h.stopPropagation(),this.open?this.close():this.show()}},en({class:"glyph-img"},"\u{1F916}"),en({class:"children-doc-label",title:JC(s)},JC(s)),ote(()=>{this.closeChild()}))}popup(){let s=this.rows();return ct({class:["servers-pop","children-pop"]},s.length===0?this.emptyState("No agents in this session yet."):ct({class:"children-list",onScroll:()=>this.onListScroll()},s.map((a,h)=>this.row(a,h))),this.filterBox(this.children.length,"agent"))}row(s,a){return ct({class:["children-row",a===this.highlighted?"active":"",this.viewing?.id===s.id?"viewing":""],style:s.depth>1?{paddingLeft:`${(s.depth-1)*16+10}px`}:void 0,onMouseEnter:()=>{this.highlighted!==a&&(this.highlighted=a,this.update())},onClick:h=>{h.stopPropagation(),this.openChild(s.id)}},en({class:["children-dot",wEe(s)]}),en({class:["children-label",s.state==="running"?"shimmer-text shimmer-slow":""]},JC(s)),s.kind?en({class:"children-kind"},s.kind):null,s.model?en({class:"children-model"},s.effort?`${s.model} \xB7 ${s.effort}`:s.model):null,en({class:"children-time"},s.started?tf((s.state==="running"?Date.now():s.mtime)-s.started):""),s.failing?en({class:"children-tokens failing",title:"Its latest reply is an API error, not the model's"},"error"):en({class:"children-tokens"},s.tokens?AC(s.tokens):""),en({class:"children-status-link",onClick:h=>{h.stopPropagation(),this.openChild(s.id,!0)}},"status"))}};var STt=new Map,ITt=(o,s)=>s+`
2196
2196
 
2197
2197
  ---
2198
2198
 
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 OO,Ds,ld,IO,MO,FO,Zo,ib,cd,ar,qO,ab,ud=S(()=>{"use strict";Rs();Ho();Ko();sd();eb();OO=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<node_repl_review_evidence>","# AGENTS.md instructions for "];Ds=t=>!!t&&typeof t=="object"&&!Array.isArray(t),ld=t=>t==="shell_command"||t==="exec_command",IO=new Set(["max_output_tokens","yield_time_ms","timeout_ms"]);MO={n:`
327
327
  `,t:" ",r:"\r",b:"\b",f:"\f",v:"\v",0:"\0"};FO=t=>t?t.replace(/\r?\n$/,"").split(`
328
328
  `).length:0;Zo=t=>{let e=CO(t);return process.platform==="win32"?e.toLowerCase():e},ib=12e4,cd=t=>t.slice(-36),ar=class t extends qt{constructor(n=ad(nb(),".codex","sessions")){super();this.root=n}displayName="Codex Mirror";#t=0;#o;#e=!1;#s;#u=0;#n=new Map;#c=new Map;#a=new Map;#d=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 od()).includes(cd(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 od()).includes(cd(n)))throw new Error("the Codex session is not loaded by its app server now");await Zy(cd(n),r,s)}detectsInstalled(){return TO(ad(nb(),".codex"))}sessionsDir(n){return this.root}listSessionFiles(n){let r=Zo(n),s=[];for(let i of this.#f()){let o=0,a=0;try{let f=Qo(i);if(!f.isFile())continue;o=f.size,a=f.mtimeMs}catch{continue}let l=this.#n.get(i);if(l===void 0){if(l=ob(i),l===void 0)continue;this.#n.set(i,l)}if(l.subagent||Zo(l.cwd)!==r)continue;let c=tb(i,".jsonl");this.#a.set(c,i),s.push({sessionId:c,file:i,mtime:this.#r(i,o,a)})}return s}listChildren(n,r){let s=Zo(n),i=new Map,o;for(let c of this.#f()){let f=0,d=0,u;try{let b=Qo(c);if(!b.isFile())continue;f=b.size,d=b.mtimeMs,u=b.birthtimeMs||void 0}catch{continue}let p=this.#n.get(c);if(p===void 0||p.modelPending){if(p=ob(c),p===void 0)continue;this.#n.set(c,p)}if(tb(c,".jsonl")===r&&(o=p.id),!p.spawn||Zo(p.cwd)!==s)continue;let{running:h,tokens:m,turn:g}=this.#i(c,f,d);i.set(p.spawn.id,{file:c,mtime:this.#r(c,f,d),started:u,running:h,tokens:m,spawn:p.spawn,turn:g??p.turn})}if(!o)return[];let a=(c,f=new Set)=>{if(c.parent===o)return!0;if(f.has(c.id))return!1;f.add(c.id);let d=i.get(c.parent);return d?a(d.spawn,f):!1},l=[];for(let{file:c,mtime:f,started:d,running:u,tokens:p,spawn:h,turn:m}of i.values())a(h)&&l.push({id:h.id,file:c,mtime:f,started:d,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:u});return l}sessionsWorking(n){let r=new Set,s=Date.now();for(let{sessionId:i,file:o,mtime:a}of this.listSessionFiles(n)){if(s-a>=ib)continue;let l;try{let c=Qo(o);l=this.#i(o,c.size,c.mtimeMs)}catch{continue}l.running&&r.add(i)}return r}#r(n,r,s){return Math.max(s,this.#i(n,r,s).ms??0)}#i(n,r,s){let i=this.#c.get(n);if(i&&i.size===r&&i.mtime===s)return i;let o=JO(n),a={size:r,mtime:s,...o,turn:o.turn??i?.turn};return this.#c.set(n,a),a}#f(){let n=[],r=s=>{try{return AO(s).map(i=>ad(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.#l(n),n.ord=String(this.#t++),n.parent=this.#o,this.#o=n.ord),n.ord}#l(n){let r=n.payload;if(n.type==="session_meta"){if(++this.#u===1){let s=typeof r?.source=="object"?r.source?.subagent?.thread_spawn:void 0;this.#s=s?.agent_path,this.#e=!!s}}else this.#u=0,this.#e&&r?.type==="agent_message"&&r.recipient===this.#s&&(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=or(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=or(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=or(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"?RO(i.name??"",i.input):{name:i.name??"",input:UO(i.arguments)};return l&&this.#d.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.#d.get(a);return this.#d.delete(a),s.push({type:"tool_result",id:a,...BO(_O(i.output),l)}),{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:fb(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.#a.get(n);if(!r)return;let s;try{let i=Qo(r);s=this.#r(r,i.size,i.mtimeMs)}catch{return}return Date.now()-s<ib}readPreview(n){for(let r of(sr(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"?or(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"?"":or(n.payload.content,r==="user").replace(/\s+/g," ").trim()}},qO=[64*1024,1024*1024];ab=512*1024});import{realpathSync as KO}from"fs";import{createHash as HO}from"crypto";import{join as ta,resolve as zO}from"path";import{homedir as YO}from"os";function Re(){let t=process.env.TYPEBULB_SERVERS_DIR;return t?ta(t,".."):ta(YO(),".typebulb")}function gt(){pb||(pb=!0,console.error(`${Re()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function yt(){return process.env.TYPEBULB_SERVERS_DIR||ta(Re(),"servers")}function hb(t){let e=se(t),n=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return ta(Re(),"canvas",`${n}-${Bs(t)}.png`)}function Bs(t){return HO("sha1").update(se(t)).digest("hex").slice(0,8)}function se(t){let e=zO(t),n=e;try{n=KO.native(e)}catch{}return(process.platform==="win32"?n.toLowerCase():n).replace(/\\/g,"/")}function mb(t,e){let n=se(t),r=se(e);return n.startsWith(r.endsWith("/")?r:r+"/")?!n.includes("/node_modules/"):!1}var pb,je=S(()=>{"use strict";pb=!1});import*as bb from"net";import{mkdir as VO,readFile as GO,writeFile as wb}from"fs/promises";import{existsSync as XO}from"fs";import{join as vb}from"path";function xb(){return vb(Re(),"blocks")}function dd(t){return vb(xb(),`${t}.json`)}function ra(t){return new Promise(e=>{let n=bb.createServer();n.once("error",()=>e(!1)),n.listen(t,"127.0.0.1",()=>n.close(()=>e(!0)))})}async function tP(t){for(let e=t;e<65535;e++)if(await ra(e))return e;throw new Error(`No free port found above ${t}`)}async function fd(t){let{listBulbServers:e}=await Promise.resolve().then(()=>(Ie(),Eb)),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 sa(t){try{let e=JSON.parse(await GO(dd(t),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function ia(t,e){try{return await wb(dd(t),JSON.stringify(e,null,2)),!0}catch{return gt(),!1}}async function nP(t){let e=se(t);try{await VO(xb(),{recursive:!0})}catch{return}let n=[];for(let o=0;o<kb;o++)n.push(Sb+o*gn);let r=await Promise.all(n.map(async o=>({base:o,block:await sa(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 wb(dd(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await sa(o))?.cwd===e)return o;l.code!=="EEXIST"&&gt();continue}if(!XO(a.cwd))return await ia(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>gb(o.block)-gb(a.block))[0];if(i)return await ia(i.base,s)?i.base:void 0}function gb(t){return Object.values(t.slots).reduce((e,n)=>Math.max(e,n.usedAt??0),0)}async function rP(t,e){let n=await sa(t)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=n.mirrors[e.agent];if(i!==void 0)return i;let o=yb(n),a=o.has(0)?ZO:0;for(;a>na&&o.has(a);)a--;return n.mirrors[e.agent]=a,await ia(t,n),a}let r=se(e.file),s=n.slots[r]?.offset;if(s===void 0){let i=yb(n);for(s=na;s<gn&&i.has(s);)s++;if(s>=gn){let o=Object.entries(n.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:na,o&&delete n.slots[o[0]]}}return n.slots[r]={offset:s,usedAt:Date.now()},await ia(t,n),s}function yb(t){return new Set([...Object.values(t.mirrors),...Object.values(t.slots).map(e=>e.offset)])}async function lr(t,e){let n=await nP(e);return n===void 0?void 0:n+await rP(n,t)}async function yn(t){let e=se(t);for(let n=0;n<kb;n++){let r=await sa(Sb+n*gn);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function oa(t){if(t.explicit!==void 0)return await ra(t.explicit)||await fd(t.explicit),t.target.kind==="bulb"&&await lr(t.target,t.cwd),{port:t.explicit};let e=await lr(t.target,t.cwd);if(e!==void 0){let r=e-e%gn,s=Date.now()+eP;do{if(await ra(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=na;i<gn;i++){let o=r+i;if(o!==e&&await ra(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await tP(QO),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Sb,gn,kb,QO,na,ZO,eP,bn=S(()=>{"use strict";je();Sb=20100,gn=100,kb=19,QO=23e3,na=1,ZO=gn-1,eP=3e3});var Ce,aa=S(()=>{"use strict";Ce="0.62.7"});var Eb={};Li(Eb,{agentViewerCommand:()=>Nb,bulbServerCommand:()=>$b,clearServerLog:()=>yd,findProjectViewer:()=>ua,isAlive:()=>Wt,isMirror:()=>ye,isProjectBulb:()=>kd,isProjectMirror:()=>dr,launchAgentViewer:()=>Us,launchBulbServer:()=>Sn,listBulbServers:()=>G,probePageCount:()=>Ed,readServerLog:()=>Qe,readWaitCursor:()=>ca,recordDenial:()=>Sd,registerServer:()=>vd,relayOpen:()=>xd,runMarker:()=>bd,serverLogPath:()=>ur,serversForBulb:()=>vn,sliceRunLog:()=>wd,startServerLog:()=>Fs,stopBulbServer:()=>cr,stopServer:()=>bt,stopServersForBulb:()=>da,typebulbBinPath:()=>fr,unregisterServer:()=>wn,writeWaitCursor:()=>js});import{spawn as Ab}from"child_process";import{readdir as sP,readFile as Ob,writeFile as Pb,unlink as pd,mkdir as iP}from"fs/promises";import{mkdirSync as _b,writeFileSync as la,appendFileSync as oP,readFileSync as hd}from"fs";import*as $e from"path";import{fileURLToPath as aP}from"url";function md(t){return $e.join(yt(),`${t}.json`)}function ur(t){return $e.join(yt(),`${t}.log`)}function gd(t){return $e.join(yt(),`${t}.wait.json`)}function Rb(t){try{let e=JSON.parse(hd(gd(t),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function ca(t,e=""){let n=Rb(t)[e];return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function js(t,e,n=""){try{_b(yt(),{recursive:!0});let r=Rb(t);r[n]=e,la(gd(t),JSON.stringify({cursors:r}))}catch{}}function Fs(t){let e=ur(t);try{_b(yt(),{recursive:!0}),la(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 l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(oP(e,l),s+=l.length,s>2*Tb){let c=hd(e),f=c.subarray(Math.max(0,c.length-Tb));la(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),n(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=n,process.stderr.write=r}}function yd(t){try{la(ur(t),"")}catch{}}function Qe(t,e=0){try{let n=hd(ur(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 bd(t){return`\u2500\u2500 run ${t} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function cP(t){let e=lP.exec(t);return e?Number(e[1]):void 0}function wd(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"?or(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"?"":or(n.payload.content,r==="user").replace(/\s+/g," ").trim()}},qO=[64*1024,1024*1024];ab=512*1024});import{realpathSync as KO}from"fs";import{createHash as HO}from"crypto";import{join as ta,resolve as zO}from"path";import{homedir as YO}from"os";function Re(){let t=process.env.TYPEBULB_SERVERS_DIR;return t?ta(t,".."):ta(YO(),".typebulb")}function gt(){pb||(pb=!0,console.error(`${Re()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function yt(){return process.env.TYPEBULB_SERVERS_DIR||ta(Re(),"servers")}function hb(t){let e=se(t),n=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return ta(Re(),"canvas",`${n}-${Bs(t)}.png`)}function Bs(t){return HO("sha1").update(se(t)).digest("hex").slice(0,8)}function se(t){let e=zO(t),n=e;try{n=KO.native(e)}catch{}return(process.platform==="win32"?n.toLowerCase():n).replace(/\\/g,"/")}function mb(t,e){let n=se(t),r=se(e);return n.startsWith(r.endsWith("/")?r:r+"/")?!n.includes("/node_modules/"):!1}var pb,je=S(()=>{"use strict";pb=!1});import*as bb from"net";import{mkdir as VO,readFile as GO,writeFile as wb}from"fs/promises";import{existsSync as XO}from"fs";import{join as vb}from"path";function xb(){return vb(Re(),"blocks")}function dd(t){return vb(xb(),`${t}.json`)}function ra(t){return new Promise(e=>{let n=bb.createServer();n.once("error",()=>e(!1)),n.listen(t,"127.0.0.1",()=>n.close(()=>e(!0)))})}async function tP(t){for(let e=t;e<65535;e++)if(await ra(e))return e;throw new Error(`No free port found above ${t}`)}async function fd(t){let{listBulbServers:e}=await Promise.resolve().then(()=>(Ie(),Eb)),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 sa(t){try{let e=JSON.parse(await GO(dd(t),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function ia(t,e){try{return await wb(dd(t),JSON.stringify(e,null,2)),!0}catch{return gt(),!1}}async function nP(t){let e=se(t);try{await VO(xb(),{recursive:!0})}catch{return}let n=[];for(let o=0;o<kb;o++)n.push(Sb+o*gn);let r=await Promise.all(n.map(async o=>({base:o,block:await sa(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 wb(dd(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await sa(o))?.cwd===e)return o;l.code!=="EEXIST"&&gt();continue}if(!XO(a.cwd))return await ia(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>gb(o.block)-gb(a.block))[0];if(i)return await ia(i.base,s)?i.base:void 0}function gb(t){return Object.values(t.slots).reduce((e,n)=>Math.max(e,n.usedAt??0),0)}async function rP(t,e){let n=await sa(t)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=n.mirrors[e.agent];if(i!==void 0)return i;let o=yb(n),a=o.has(0)?ZO:0;for(;a>na&&o.has(a);)a--;return n.mirrors[e.agent]=a,await ia(t,n),a}let r=se(e.file),s=n.slots[r]?.offset;if(s===void 0){let i=yb(n);for(s=na;s<gn&&i.has(s);)s++;if(s>=gn){let o=Object.entries(n.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:na,o&&delete n.slots[o[0]]}}return n.slots[r]={offset:s,usedAt:Date.now()},await ia(t,n),s}function yb(t){return new Set([...Object.values(t.mirrors),...Object.values(t.slots).map(e=>e.offset)])}async function lr(t,e){let n=await nP(e);return n===void 0?void 0:n+await rP(n,t)}async function yn(t){let e=se(t);for(let n=0;n<kb;n++){let r=await sa(Sb+n*gn);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function oa(t){if(t.explicit!==void 0)return await ra(t.explicit)||await fd(t.explicit),t.target.kind==="bulb"&&await lr(t.target,t.cwd),{port:t.explicit};let e=await lr(t.target,t.cwd);if(e!==void 0){let r=e-e%gn,s=Date.now()+eP;do{if(await ra(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=na;i<gn;i++){let o=r+i;if(o!==e&&await ra(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await tP(QO),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Sb,gn,kb,QO,na,ZO,eP,bn=S(()=>{"use strict";je();Sb=20100,gn=100,kb=19,QO=23e3,na=1,ZO=gn-1,eP=3e3});var Ce,aa=S(()=>{"use strict";Ce="0.62.8"});var Eb={};Li(Eb,{agentViewerCommand:()=>Nb,bulbServerCommand:()=>$b,clearServerLog:()=>yd,findProjectViewer:()=>ua,isAlive:()=>Wt,isMirror:()=>ye,isProjectBulb:()=>kd,isProjectMirror:()=>dr,launchAgentViewer:()=>Us,launchBulbServer:()=>Sn,listBulbServers:()=>G,probePageCount:()=>Ed,readServerLog:()=>Qe,readWaitCursor:()=>ca,recordDenial:()=>Sd,registerServer:()=>vd,relayOpen:()=>xd,runMarker:()=>bd,serverLogPath:()=>ur,serversForBulb:()=>vn,sliceRunLog:()=>wd,startServerLog:()=>Fs,stopBulbServer:()=>cr,stopServer:()=>bt,stopServersForBulb:()=>da,typebulbBinPath:()=>fr,unregisterServer:()=>wn,writeWaitCursor:()=>js});import{spawn as Ab}from"child_process";import{readdir as sP,readFile as Ob,writeFile as Pb,unlink as pd,mkdir as iP}from"fs/promises";import{mkdirSync as _b,writeFileSync as la,appendFileSync as oP,readFileSync as hd}from"fs";import*as $e from"path";import{fileURLToPath as aP}from"url";function md(t){return $e.join(yt(),`${t}.json`)}function ur(t){return $e.join(yt(),`${t}.log`)}function gd(t){return $e.join(yt(),`${t}.wait.json`)}function Rb(t){try{let e=JSON.parse(hd(gd(t),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function ca(t,e=""){let n=Rb(t)[e];return typeof n=="number"&&Number.isFinite(n)&&n>=0?n:void 0}function js(t,e,n=""){try{_b(yt(),{recursive:!0});let r=Rb(t);r[n]=e,la(gd(t),JSON.stringify({cursors:r}))}catch{}}function Fs(t){let e=ur(t);try{_b(yt(),{recursive:!0}),la(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 l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(oP(e,l),s+=l.length,s>2*Tb){let c=hd(e),f=c.subarray(Math.max(0,c.length-Tb));la(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),n(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=n,process.stderr.write=r}}function yd(t){try{la(ur(t),"")}catch{}}function Qe(t,e=0){try{let n=hd(ur(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 bd(t){return`\u2500\u2500 run ${t} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function cP(t){let e=lP.exec(t);return e?Number(e[1]):void 0}function wd(t,e){let n=t.split(`
330
330
  `),r=[];if(n.forEach((o,a)=>{let l=cP(o);l!==void 0&&r.push({id:l,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 Wt(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function vd(t){try{await iP(yt(),{recursive:!0}),await Pb(md(t.pid),JSON.stringify({version:Ce,...t}))}catch{gt()}}async function Sd(t,e){let n=md(t);try{let r=JSON.parse(await Ob(n,"utf8"));if(r.denied===e)return;r.denied=e,await Pb(n,JSON.stringify(r))}catch{}}async function wn(t){await pd(md(t)).catch(()=>{}),await pd(ur(t)).catch(()=>{}),await pd(gd(t)).catch(()=>{})}function ye(t){return t.agent!=null}function dr(t,e){return ye(t)&&t.cwd!=null&&se(t.cwd)===se(e)}function kd(t,e){return!ye(t)&&mb(t.file,e)}async function G(t){let e;try{e=await sP(yt())}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 Ob($e.join(yt(),s),"utf8"))}catch{await wn(i);return}o&&typeof o.pid=="number"&&Wt(o.pid)?n.push(o):await wn(i)})),(t?n.filter(s=>kd(s,t)):n).sort((s,i)=>s.startedAt-i.startedAt)}async function ua(t,e){return(await G()).find(n=>dr(n,t)&&(e?n.agent===e:!0))}async function xd(t,e){let n=new URL(t).port,r=(await G()).filter(a=>String(a.port)!==n),s=r.filter(a=>dr(a,e)),i=r.filter(a=>kd(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:t}),signal:AbortSignal.timeout(2e3)});if(!l.ok)continue;let{opened:c,pages:f}=await l.json();if(c)return{where:"editor",via:a.agent?"the agent mirror":`${$e.basename(a.file)}'s page`};ye(a)&&(o+=f??0)}catch{}return o>0?{where:"external"}:void 0}async function cr(t){try{process.kill(t,"SIGTERM")}catch{}await wn(t)}async function Ed(t){try{let e=await fetch(`${t.url}/__pages`,{signal:AbortSignal.timeout(uP)});if(!e.ok)return;let{pages:n}=await e.json();return typeof n=="number"?n:void 0}catch{return}}async function bt(t,e=ye(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(Cb)});if(!n.ok)throw new Error(`/__stop ${n.status}`);let{closed:r=0,stuck:s=0}=await n.json(),i=Date.now()+Cb;for(;Wt(t.pid)&&Date.now()<i;)await Ib(100);return Wt(t.pid)?(await cr(t.pid),"killed"):(await wn(t.pid),{closed:r,stuck:s})}catch{return await cr(t.pid),"killed"}}function vn(t,e){let n=se(e);return t.filter(r=>!ye(r)&&r.pid!==process.pid&&se(r.file)===n)}async function da(t,e){let n=vn(await G(),t);for(let r of n)await bt(r,e!==void 0&&r.port===e?"keep":"close");return n}function dP(t,e,n){(process.platform==="win32"?Ab("cmd",["/c","start","","/b",t,...e],{cwd:n,stdio:"ignore",windowsHide:!0}):Ab(t,e,{cwd:n,detached:!0,stdio:"ignore"})).unref()}function fr(){return $e.join($e.dirname(aP(import.meta.url)),"index.js")}function $b(t,e={}){return{command:process.execPath,args:[fr(),...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 Nb(t){return{command:process.execPath,args:[fr(),`agent:${t}`,"--no-open"]}}async function Lb(t,e,n,r){let s=await t();if(s)return s;dP(e.command,e.args,n);let i=Date.now()+2e4;for(;Date.now()<i;){await Ib(150);let o=await t();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function Sn(t,e={}){let n=e.cwd??process.cwd(),r=$e.resolve(n,t),s=await lr({kind:"bulb",file:r},n),[i]=await da(r,s),o={...e,mode:e.mode??i?.mode};return Lb(async()=>vn(await G(),r)[0],$b(t,o),n,$e.basename(t))}async function Us(t,e=process.cwd()){return Lb(()=>ua(e,t),Nb(t),e,`the ${t} mirror`)}var Tb,lP,Cb,uP,Ib,Ie=S(()=>{"use strict";je();bn();aa();Tb=1e6;lP=/^── run (\d+) ── /;Cb=6e3,uP=500;Ib=t=>new Promise(e=>setTimeout(e,t))});function pr(t){return{...Qp(t),server:t.files.get("server.ts")??""}}function fa(t){return!!t.server&&!t.code}var qs=S(()=>{"use strict";te();te()});function pa(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 Ad(t){return nr(pa(t)??"bulb")||"bulb"}var Td=S(()=>{"use strict";te()});import{readdirSync as fP,readFileSync as pP,statSync as hP}from"fs";import{join as Mb,basename as mP}from"path";function Bb(t,e,n){if(e>8)return n;let r;try{r=fP(t,{withFileTypes:!0})}catch{return n}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Bb(Mb(t,s.name),e+1,n)}else s.isFile()&&s.name.endsWith(".bulb.md")&&n.push(Mb(t,s.name));return n}function gP(t,e){let n,r=!1;try{let s=pP(t,"utf8");n=pa(s.slice(0,1024));let i=Ve(s);r=!!i&&fa(pr(i))}catch{}return{mtime:e,name:n??mP(t).replace(/\.bulb\.md$/,""),serverOnly:r}}function ha(t){let e=new Map,n=Bb(t,0,[]).map(r=>{let s=0;try{s=hP(r).mtimeMs}catch{}let i=s?Db.get(r):void 0,o=i?.mtime===s?i:gP(r,s);return s&&e.set(r,o),{path:r,...o}});return Db=e,n}var Db,jb=S(()=>{"use strict";te();qs();Td();Db=new Map});function hr(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 ma=S(()=>{"use strict"});import{readFile as yP}from"fs/promises";async function Cd(t){try{let e=Ve(await yP(t,"utf-8"));return e?hr(pr(e)):void 0}catch{return}}var Fb=S(()=>{"use strict";qs();ma()});function Od(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]!==`
@@ -2186,7 +2186,8 @@ Usage:
2186
2186
  background call left running, a failure streak),
2187
2187
  then print it and exit.
2188
2188
  Run it in the background; the exit is your
2189
- wake-up. Run it again after handling it.
2189
+ wake-up. Run it again after handling it:
2190
+ what came up meanwhile fires at once.
2190
2191
  Both take --slow (below).
2191
2192
 
2192
2193
  Options:
@@ -2538,7 +2539,7 @@ declare const tb: {${z1}${FS}${JS}${WS}${US}${qS}
2538
2539
  `):T)}catch(O){console.error(`Not delivered: ${O instanceof Error?O.message:O}`),process.exit(4)}console.error(`accepted ${new Date().toISOString()}`)}$&&process.exit(3),i||js(n.pid,d,l),process.exit(E)}async function PN(){let t=st(),e=t?qr()[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 yk(t,e){if(e==="killed")return` \u2014 forced (${pk(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 bk(t){if(!t){await Cp(await G(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Bl(await G(),t,"stop",process.cwd(),st()),n=await bt(e);console.log(`Stopped ${sn(e)} (pid ${e.pid}, ${e.url}).${yk(e,n)}`)}async function wk(t){let e=await Tp(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=>bt(s)));console.log(`Stopped ${e.length} ${n}${e.length===1?"":"s"}:`),e.forEach((s,i)=>console.log(` ${s.url} pid ${s.pid} ${sn(s)}${yk(s,r[i])}`))}async function Tp(t){let e=process.cwd(),n=t==="agent"?st():void 0;return t==="global"?await G():t==="bulbs"?await G(e):(await G()).filter(r=>dr(r,e)&&(!n||r.agent===n))}async function vk(t,e){let n=process.cwd(),r=t?[Bl(await G(),t,"restart",n,st())]:e?await Tp(e):[...await G(n),...await Tp("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${Ce}:`);for(let s of r){let i=s.version?`v${s.version}`:"unknown version";try{let o=ye(s)?(await bt(s,"keep"),await Us(s.agent,s.cwd??n)):await Sn(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} ${sn(s)} ${i} \u2192 v${Ce}`)}catch(o){console.log(` ${s.url} ${sn(s)} failed: ${o instanceof Error?o.message:o}`),process.exitCode=1}}}Ie();je();bn();import*as jl from"path";import*as Sk from"http";import{mkdir as _N,writeFile as RN}from"fs/promises";async function Kr(){let t=[];for await(let e of process.stdin)t.push(e);return Buffer.concat(t).toString("utf-8")}function Ci(t){return(t.charCodeAt(0)===65279?t.slice(1):t).replace(/\r\n/g,`
2539
2540
  `).trimEnd()}function IN(t,e){return new Promise((n,r)=>{let s=new URL(t),i=Sk.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",l=>{a+=l}),o.on("end",()=>n({status:o.statusCode??0,text:a}))});i.setTimeout(0),i.on("error",r),i.end(e)})}var $N=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=Ci(await Kr()));let r=e!==void 0&&e.startsWith("tb:");r&&n<=0&&(n=mp);let s=e!==void 0&&/^tb:(click|set)( |$)/.test(e),i=jl.resolve(t),o=vn(await G(),i)[0];if(!o){let h=(await yn(process.cwd()))(i);console.error(h?`No running server for '${t}' \u2014 it last ran ${$N(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 IN(`${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{}}},l={},c=Date.now();try{l=await a(n)}catch(h){console.error(`send failed: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let f=l.clients??0,d=`${f} page${f===1?"":"s"}`;if(l.refused&&(console.error(`Actuation needs exactly one connected page; ${d} are open on ${o.url} \u2014 the reset is \`typebulb stop ${t}\` then relaunch.`),process.exit(1)),f===0){let h=l.droppedMsAgo,m=l.opening==="none"?" and no agent mirror page is open to open one through":"",g=l.opening==="unreached"?` \u2014 the page was opened ${l.via?`in VS Code via ${l.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 "${it.connected}"`;console.error(`No page connected after ${((Date.now()-c)/1e3).toFixed(1)}s, so nothing was delivered${g}`),process.exit(1)}l.opening==="editor"?console.error(`Opened in VS Code via ${l.via}.`):l.opening==="external"&&console.error("Opened in your browser, where the agent mirror is."),console.error(`Sent to ${d}.`);let u=l.results??[],p=l.errors??[];for(let h of p)console.error(`handler error: ${h}`);if(p.length&&process.exit(1),u.length>1&&(console.error(`${u.length} replies from ${d} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),u.length===1){if(e!==void 0&&/^tb:png( |$)/.test(e)){let m={};try{m=JSON.parse(u[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=hb(i);await _N(jl.dirname(g),{recursive:!0}),await RN(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(u[0])}catch{h=void 0}console.log(typeof h=="string"?h:u[0])}else l.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)`))}Ga();kf();te();import*as xk from"fs/promises";async function Ek(t,e){let n=await xk.readFile(t,"utf-8"),r=Wn(n),s=de[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(`
2540
2541
  `)?i:i+`
2541
- `)}te();import*as Oi from"fs/promises";async function Ck(t,e){let n=await Oi.readFile(t,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await Kr():await Oi.readFile(o,"utf-8")}catch(l){Tk(`Cannot read ${i}'s source: ${l instanceof Error?l.message:String(l)}`)}r.push({kind:i,content:Ci(a),label:o==="-"?"stdin":o})}let s;try{s=NN(n,r)}catch(i){Tk(`${t}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${de[i].path}: already up to date`);if(s.written.length){await Oi.writeFile(t,s.text);for(let i of s.written)console.log(i.action==="removed"?`${de[i.kind].path}: removed (${i.label} is empty)`:`${de[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function NN(t,e){let n=Wn(t),r=t,s=[],i=[];for(let{kind:o,content:a,label:l}of e){let c=de[o].path,f=n.files.get(c);if(!a){if(f===void 0){i.push(o);continue}r=Ak(rh(r,o),r,c),s.push({kind:o,action:"removed",chars:0,label:l});continue}if(f!==void 0&&Ci(f)===a){i.push(o);continue}r=Ak(zr(r,o,a),r,c),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:l})}return{text:r,written:s,upToDate:i}}function Ak(t,e,n){if(t===e)throw new Error(`the **${n}** block's fence is unterminated; refusing to rewrite inside it`);return t}function Tk(t){console.error(t),process.exit(1)}et();gl();dl();Mr();function Op(){let t=qr(),e=st();return{caller:e,adapters:(e?[e]:Object.keys(t)).map(n=>t[n]()).filter(n=>n.listChildren)}}async function Pk(t,e,n){be(e);let{caller:r,adapters:s}=Op();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:l}=gi(o,process.cwd());if(!t){let c=a?ml(o,l,a):hl(o,l).next().value;if(!c?.children.length){if(a){en(a,n),console.log("No sub-agents in this session yet.");return}continue}en(a??c.sessionId,n);let{reports:f,files:d}=await Dn(o,l,c);console.log(Uv(c.sessionId,f,d,Date.now()));return}for(let c of hl(o,l)){i??=c;let f=Hv(c,t);if(f.length){if(f.length>1){console.error(`Several agents match "${t}"; name one by its id:`);for(let d of f)console.error(` ${Ok(d)}`);process.exitCode=1;return}en(a??c.sessionId,n),console.log(Dv((await Dn(o,l,c,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(` ${Ok(o)}`);process.exitCode=1}var Ok=t=>`${t.id} ${ol(t).padEnd(7)} ${Tt(t)}`;et();je();Ie();gl();dl();import{mkdirSync as LN,readFileSync as _p,writeFileSync as Ik,rmSync as _k}from"fs";import{join as Ul}from"path";var MN=1e4,DN=720*6e4,Rk="typebulb_babysit";async function $k(t,e){be(t);let{caller:n,adapters:r}=Op(),s=r.map(p=>({adapter:p,...(p.wake?gi:Kv)(p,process.cwd())})).find(p=>p.sessionId);if(!s?.sessionId)return Pp(r.length?r.some(p=>p.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.":`Babysitting sub-agents isn't supported for ${n} sessions.`);let{adapter:i,sessionId:o,cwd:a}=s;if(en(o,e),i.wake){let p=await i.wakeRoute(o);if(p.error)return Pp(`Can't babysit: ${p.error}.`)}let l=Ul(Re(),"babysit"),c=Ul(l,`${o}.json`);if(!BN(Ul(l,`${o}.lock`)))return Pp("A babysit is already watching this session.");let f=[];try{f=JSON.parse(_p(c,"utf8"))}catch{}let d=p=>{try{Ik(c,JSON.stringify(p))}catch{}};console.error(`Babysitting the sub-agents of session ${o}: this exits with a line when one needs attention.`);let u=Date.now()+DN;for(;Date.now()<u;){i.sessionEnded?.(o,a)&&Fl(3,"The session this babysits has ended.");let{reports:p}=await Dn(i,a,ml(i,a,o)),h=qv(p,Date.now(),!!i.sessionsWorking?.(a)?.has(o),en(o)),m=[...h].filter(([g])=>!f.includes(g));if(!m.length)f=[...h.keys()],d(f);else{let g=m.map(([,b])=>b).join(`
2542
+ `)}te();import*as Oi from"fs/promises";async function Ck(t,e){let n=await Oi.readFile(t,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await Kr():await Oi.readFile(o,"utf-8")}catch(l){Tk(`Cannot read ${i}'s source: ${l instanceof Error?l.message:String(l)}`)}r.push({kind:i,content:Ci(a),label:o==="-"?"stdin":o})}let s;try{s=NN(n,r)}catch(i){Tk(`${t}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${de[i].path}: already up to date`);if(s.written.length){await Oi.writeFile(t,s.text);for(let i of s.written)console.log(i.action==="removed"?`${de[i.kind].path}: removed (${i.label} is empty)`:`${de[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function NN(t,e){let n=Wn(t),r=t,s=[],i=[];for(let{kind:o,content:a,label:l}of e){let c=de[o].path,f=n.files.get(c);if(!a){if(f===void 0){i.push(o);continue}r=Ak(rh(r,o),r,c),s.push({kind:o,action:"removed",chars:0,label:l});continue}if(f!==void 0&&Ci(f)===a){i.push(o);continue}r=Ak(zr(r,o,a),r,c),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:l})}return{text:r,written:s,upToDate:i}}function Ak(t,e,n){if(t===e)throw new Error(`the **${n}** block's fence is unterminated; refusing to rewrite inside it`);return t}function Tk(t){console.error(t),process.exit(1)}et();gl();dl();Mr();function Op(){let t=qr(),e=st();return{caller:e,adapters:(e?[e]:Object.keys(t)).map(n=>t[n]()).filter(n=>n.listChildren)}}async function Pk(t,e,n){be(e);let{caller:r,adapters:s}=Op();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:l}=gi(o,process.cwd());if(!t){let c=a?ml(o,l,a):hl(o,l).next().value;if(!c?.children.length){if(a){en(a,n),console.log("No sub-agents in this session yet.");return}continue}en(a??c.sessionId,n);let{reports:f,files:d}=await Dn(o,l,c);console.log(Uv(c.sessionId,f,d,Date.now()));return}for(let c of hl(o,l)){i??=c;let f=Hv(c,t);if(f.length){if(f.length>1){console.error(`Several agents match "${t}"; name one by its id:`);for(let d of f)console.error(` ${Ok(d)}`);process.exitCode=1;return}en(a??c.sessionId,n),console.log(Dv((await Dn(o,l,c,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(` ${Ok(o)}`);process.exitCode=1}var Ok=t=>`${t.id} ${ol(t).padEnd(7)} ${Tt(t)}`;et();je();Ie();gl();dl();import{mkdirSync as LN,readFileSync as _p,writeFileSync as Ik,rmSync as _k}from"fs";import{join as Ul}from"path";var MN=1e4,DN=720*6e4,Rk="typebulb_babysit";async function $k(t,e){be(t);let{caller:n,adapters:r}=Op(),s=r.map(p=>({adapter:p,...(p.wake?gi:Kv)(p,process.cwd())})).find(p=>p.sessionId);if(!s?.sessionId)return Pp(r.length?r.some(p=>p.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.":`Babysitting sub-agents isn't supported for ${n} sessions.`);let{adapter:i,sessionId:o,cwd:a}=s;if(en(o,e),i.wake){let p=await i.wakeRoute(o);if(p.error)return Pp(`Can't babysit: ${p.error}.`)}let l=Ul(Re(),"babysit"),c=Ul(l,`${o}.json`);if(!BN(Ul(l,`${o}.lock`)))return Pp("A babysit is already watching this session.");let f=[];try{f=JSON.parse(_p(c,"utf8"))}catch{}let d=p=>{try{Ik(c,JSON.stringify(p))}catch{}};console.error(`Babysitting the sub-agents of session ${o}: this exits with a line when one needs attention; run it again after handling that.`);let u=Date.now()+DN;for(;Date.now()<u;){i.sessionEnded?.(o,a)&&Fl(3,"The session this babysits has ended.");let{reports:p}=await Dn(i,a,ml(i,a,o)),h=qv(p,Date.now(),!!i.sessionsWorking?.(a)?.has(o),en(o)),m=[...h].filter(([g])=>!f.includes(g));if(!m.length)f=[...h.keys()],d(f);else{let g=m.map(([,b])=>b).join(`
2542
2543
  `);if(i.wake){console.error(`detected ${new Date().toISOString()}`);try{await i.wake(o,Rk,g)}catch(b){d([...h.keys()].filter(C=>!m.some(([T])=>T===C))),console.log(g),Fl(4,`Not delivered: ${b instanceof Error?b.message:b}`)}console.error(`accepted ${new Date().toISOString()}`)}d([...h.keys()]),console.log(g),Fl(0)}await new Promise(g=>setTimeout(g,MN))}i.wake&&await i.wake(o,Rk,"typebulb babysit stopped after 12 hours with nothing to report; run it again to keep watching.").catch(()=>{}),Fl(2,"Nothing needed attention; gave up.")}function Pp(t){console.error(t),process.exitCode=1}function Fl(t,e){e&&console.error(e),process.exit(t)}function BN(t){try{LN(Ul(t,".."),{recursive:!0})}catch{}for(let e=0;e<2;e++)try{return Ik(t,String(process.pid),{flag:"wx"}),process.on("exit",()=>{try{Number(_p(t,"utf8"))===process.pid&&_k(t)}catch{}}),!0}catch(n){if(n.code!=="EEXIST")return!0;let r=0;try{r=Number(_p(t,"utf8"))}catch{}if(r&&r!==process.pid&&Wt(r))return!1;try{_k(t)}catch{}}return!1}et();At();te();ma();import*as an from"fs/promises";import*as qn from"path";import{EventEmitter as oL}from"events";Kt();te();import{Hono as WN}from"hono";import{serve as KN}from"@hono/node-server";import{streamSSE as HN}from"hono/streaming";import*as $p from"fs/promises";import zN from"open";Tr();ii();Ar();import*as Rp from"fs/promises";import*as Pi from"path";var ql=class{async get(e){let n=tt(e),r=Pi.join(si,n+".bin"),s=Pi.join(si,n+".json");try{let[i,o]=await Promise.all([Rp.readFile(r),Rp.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,n){await ne();let r=tt(e),s=Pi.join(si,r+".bin"),i=Pi.join(si,r+".json"),o={url:e,contentType:n.contentType,cacheControl:n.cacheControl};await Promise.all([Fe(s,n.body),Fe(i,JSON.stringify(o))])}};var Nk=`
2543
2544
  const CSS = '\\n' +
2544
2545
  /* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typebulb",
3
- "version": "0.62.7",
3
+ "version": "0.62.8",
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",