typebulb 0.49.3 → 0.51.0
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 +21 -12
- package/SKILL.md +23 -14
- package/dist/agents/claude/client.js +196 -168
- package/dist/agents/codex/client.js +196 -168
- package/dist/agents/pi/client.js +197 -169
- package/dist/ai/aiProvider.d.ts +5 -1
- package/dist/ai/aiProvider.d.ts.map +1 -1
- package/dist/ai/aiProvider.js.map +1 -1
- package/dist/ai/aiProviders.d.ts +4 -1
- package/dist/ai/aiProviders.d.ts.map +1 -1
- package/dist/ai/aiProviders.js +1 -2
- package/dist/ai/aiProviders.js.map +1 -1
- package/dist/ai/protocol.d.ts +5 -3
- package/dist/ai/protocol.d.ts.map +1 -1
- package/dist/ai/protocol.js +2 -2
- package/dist/ai/protocol.js.map +1 -1
- package/dist/ai/providers/anthropic.d.ts.map +1 -1
- package/dist/ai/providers/anthropic.js +9 -6
- package/dist/ai/providers/anthropic.js.map +1 -1
- package/dist/ai/providers/gemini.d.ts +3 -2
- package/dist/ai/providers/gemini.d.ts.map +1 -1
- package/dist/ai/providers/gemini.js +13 -6
- package/dist/ai/providers/gemini.js.map +1 -1
- package/dist/ai/providers/openAI.d.ts +2 -1
- package/dist/ai/providers/openAI.d.ts.map +1 -1
- package/dist/ai/providers/openAI.js +6 -3
- package/dist/ai/providers/openAI.js.map +1 -1
- package/dist/ai/providers/openRouter.d.ts +2 -1
- package/dist/ai/providers/openRouter.d.ts.map +1 -1
- package/dist/ai/providers/openRouter.js +16 -3
- package/dist/ai/providers/openRouter.js.map +1 -1
- package/dist/dts/tbTypings.js +4 -4
- package/dist/index.js +67 -37
- package/dist/render.js +114 -86
- package/dist/resolver/packageRef.d.ts.map +1 -1
- package/dist/resolver/packageRef.js +3 -2
- package/dist/resolver/packageRef.js.map +1 -1
- package/dist/servers.js +27 -9
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);
|
|
3
|
-
var Kw=Object.create;var xa=Object.defineProperty;var Hw=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var Yw=Object.getPrototypeOf,Vw=Object.prototype.hasOwnProperty;var Cs=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var v=(n,e)=>()=>(n&&(e=n(n=0)),e);var O=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ea=(n,e)=>{for(var t in e)xa(n,t,{get:e[t],enumerable:!0})},zw=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ww(e))!Vw.call(n,s)&&s!==t&&xa(n,s,{get:()=>e[s],enumerable:!(r=Hw(e,s))||r.enumerable});return n};var Gw=(n,e,t)=>(t=n!=null?Kw(Yw(n)):{},zw(e||!n||!n.__esModule?xa(t,"default",{value:n,enumerable:!0}):t,n));import*as Ud from"fs/promises";import{existsSync as pn,readFileSync as Xw}from"fs";import*as re from"path";import{pathToFileURL as Qw}from"url";import{resolve as Ta}from"resolve.exports";import{init as qd,parse as Jd}from"es-module-lexer";function Kd(n,e){let t=re.join(n,"package.json");try{return JSON.parse(Xw(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}function Hd(n){let e=n.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${n}')`);let t=n.slice(0,e).trim(),r=n.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${n}')`);if(!r)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:re.resolve(r)}}async function Wd(n){let{name:e,dir:t}=n;if(!pn(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let r=Kd(t,e),s=Zw(r,e),i=re.resolve(t,s);if(!pn(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=re.dirname(i),a=`/local/${e}/${re.basename(i)}`,l=ev(r,t);return await tv(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:l}}function Zw(n,e){if(n.exports!==void 0){let r;try{r=Ta(n,".",{browser:!0,conditions:Aa})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Aa.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Oa(r);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Aa.join(", ")}); too complex to override.`);return s}let t=n.module??n.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function ev(n,e){if(n.exports!==void 0)try{let r=Ta(n,".",{conditions:["types"]}),s=Oa(r);if(s){let i=re.resolve(e,s);if(pn(i))return i}}catch{}let t=n.types??n.typings;if(t){let r=re.resolve(e,t);if(pn(r))return r}}function Oa(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.find(e=>typeof e=="string")}async function tv(n,e,t){await qd;let r=re.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await Ud.readFile(o,"utf8")}catch{continue}let l,c;try{[l,,,c]=Jd(a,o)}catch{continue}if(o===e&&!c)throw new Error(`override package '${n}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of l){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=nv(o,u,r);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${n} externalizes '${u}'`)}}}}function nv(n,e,t){let r=e.replace(/[?#].*$/,""),s=re.resolve(re.dirname(n),r),i=[s,s+".js",s+".mjs",re.join(s,"index.js"),re.join(s,"index.mjs")];for(let o of i)if(re.normalize(o).startsWith(t)&&pn(o))return o}function rv(n,e,t){let r=Kd(n,e),s;if(r.exports!==void 0)try{s=Oa(Ta(r,t,{conditions:Fd}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Fd.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=r.main??r.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=re.resolve(n,s);if(!pn(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Qw(i).href}async function Yd(n,e){await qd;let t;try{[t]=Jd(n)}catch{return n}let r="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),l=rv(e.dir,e.name,a);r+=n.slice(s,i.s)+l,s=i.e}return r+n.slice(s)}var Aa,Fd,Rs=v(()=>{Aa=["browser","import","default"],Fd=["node","import","default"]});function Vd(n){return _e.find(e=>le[e].path===n)}function Gd(n){return!!n?.startsWith("typebulb")}var le,_e,zd,_s=v(()=>{le={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"}},_e=["code","css","html","data","infer","insight","config","notes"];zd="typebulb/v1"});function Pa(n){return/[:\n"']/.test(n)||n.startsWith(" ")||n.endsWith(" ")?`"${n.replace(/"/g,'\\"')}"`:n}function Ca(n){return n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\"/g,'"'):n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}var Ns=v(()=>{});function ue(n){try{let e=n.split(`
|
|
3
|
+
var Kw=Object.create;var xa=Object.defineProperty;var Hw=Object.getOwnPropertyDescriptor;var Ww=Object.getOwnPropertyNames;var Yw=Object.getPrototypeOf,Vw=Object.prototype.hasOwnProperty;var Cs=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var v=(n,e)=>()=>(n&&(e=n(n=0)),e);var O=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ea=(n,e)=>{for(var t in e)xa(n,t,{get:e[t],enumerable:!0})},zw=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ww(e))!Vw.call(n,s)&&s!==t&&xa(n,s,{get:()=>e[s],enumerable:!(r=Hw(e,s))||r.enumerable});return n};var Gw=(n,e,t)=>(t=n!=null?Kw(Yw(n)):{},zw(e||!n||!n.__esModule?xa(t,"default",{value:n,enumerable:!0}):t,n));import*as Ud from"fs/promises";import{existsSync as pn,readFileSync as Xw}from"fs";import*as re from"path";import{pathToFileURL as Qw}from"url";import{resolve as Ta}from"resolve.exports";import{init as qd,parse as Jd}from"es-module-lexer";function Kd(n,e){let t=re.join(n,"package.json");try{return JSON.parse(Xw(t,"utf8"))}catch{throw new Error(`--replace package '${e}' has no readable package.json at ${t}`)}}function Hd(n){let e=n.indexOf("=");if(e===-1)throw new Error(`--replace must be <name>=<path> (got '${n}')`);let t=n.slice(0,e).trim(),r=n.slice(e+1).trim();if(!t)throw new Error(`--replace missing package name (got '${n}')`);if(!r)throw new Error(`--replace missing path for '${t}'`);if(t.startsWith("@"))throw new Error(`--replace does not support scoped names yet; '${t}' is scoped`);return{name:t,dir:re.resolve(r)}}async function Wd(n){let{name:e,dir:t}=n;if(!pn(t))throw new Error(`--replace path for '${e}' does not exist: ${t}`);let r=Kd(t,e),s=Zw(r,e),i=re.resolve(t,s);if(!pn(i))throw new Error(`--replace package '${e}' entry not found on disk: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);let o=re.dirname(i),a=`/local/${e}/${re.basename(i)}`,l=ev(r,t);return await tv(e,i,o),{name:e,dir:t,entryAbs:i,serveDir:o,entryUrl:a,typesAbs:l}}function Zw(n,e){if(n.exports!==void 0){let r;try{r=Ta(n,".",{browser:!0,conditions:Aa})}catch(i){throw new Error(`--replace package '${e}' "exports" does not resolve a browser entry (conditions: ${Aa.join(", ")}): ${i instanceof Error?i.message:i}`)}let s=Oa(r);if(!s)throw new Error(`--replace package '${e}' "exports" did not resolve "." to a single file (conditions: ${Aa.join(", ")}); too complex to override.`);return s}let t=n.module??n.main;if(!t)throw new Error(`--replace package '${e}' has no "exports", "module", or "main" entry to resolve.`);return t}function ev(n,e){if(n.exports!==void 0)try{let r=Ta(n,".",{conditions:["types"]}),s=Oa(r);if(s){let i=re.resolve(e,s);if(pn(i))return i}}catch{}let t=n.types??n.typings;if(t){let r=re.resolve(e,t);if(pn(r))return r}}function Oa(n){if(typeof n=="string")return n;if(Array.isArray(n))return n.find(e=>typeof e=="string")}async function tv(n,e,t){await qd;let r=re.normalize(t),s=new Set,i=[e];for(;i.length;){let o=i.shift();if(s.has(o))continue;s.add(o);let a;try{a=await Ud.readFile(o,"utf8")}catch{continue}let l,c;try{[l,,,c]=Jd(a,o)}catch{continue}if(o===e&&!c)throw new Error(`override package '${n}' entry is not an ES module (no import/export syntax); CommonJS or non-module entries aren't supported (esm.sh would have to transform it).`);for(let d of l){if(d.d===-2)continue;let u=d.n;if(u&&!u.startsWith("node:")){if(u.startsWith("./")||u.startsWith("../")||u.startsWith("/")){let f=nv(o,u,r);f&&!s.has(f)&&i.push(f);continue}throw new Error(`override package must ship self-contained (bundle its dependencies); ${n} externalizes '${u}'`)}}}}function nv(n,e,t){let r=e.replace(/[?#].*$/,""),s=re.resolve(re.dirname(n),r),i=[s,s+".js",s+".mjs",re.join(s,"index.js"),re.join(s,"index.mjs")];for(let o of i)if(re.normalize(o).startsWith(t)&&pn(o))return o}function rv(n,e,t){let r=Kd(n,e),s;if(r.exports!==void 0)try{s=Oa(Ta(r,t,{conditions:Fd}))}catch(o){throw new Error(`--replace package '${e}' "exports" does not resolve a node entry for '${t}' (conditions: ${Fd.join(", ")}): ${o instanceof Error?o.message:o}`)}else t==="."&&(s=r.main??r.module);if(!s)throw new Error(`--replace package '${e}' has no node export for '${t}'.`);let i=re.resolve(n,s);if(!pn(i))throw new Error(`--replace package '${e}' built file not found: ${i} \u2014 did you build it (e.g. \`pnpm run build\`)?`);return Qw(i).href}async function Yd(n,e){await qd;let t;try{[t]=Jd(n)}catch{return n}let r="",s=0;for(let i of t){if(i.d!==-1)continue;let o=i.n;if(!o||o!==e.name&&!o.startsWith(e.name+"/"))continue;let a=o===e.name?".":"."+o.slice(e.name.length),l=rv(e.dir,e.name,a);r+=n.slice(s,i.s)+l,s=i.e}return r+n.slice(s)}var Aa,Fd,Rs=v(()=>{"use strict";Aa=["browser","import","default"],Fd=["node","import","default"]});function Vd(n){return _e.find(e=>le[e].path===n)}function Gd(n){return!!n?.startsWith("typebulb")}var le,_e,zd,_s=v(()=>{le={code:{path:"code.tsx",language:"typescript"},css:{path:"styles.css",language:"css"},html:{path:"index.html",language:"html"},config:{path:"config.json",language:"json"},notes:{path:"notes.md",language:"markdown"},data:{path:"data.txt",language:"text"},infer:{path:"infer.md",language:"markdown"},insight:{path:"insight.json",language:"json"}},_e=["code","css","html","data","infer","insight","config","notes"];zd="typebulb/v1"});function Pa(n){return/[:\n"']/.test(n)||n.startsWith(" ")||n.endsWith(" ")?`"${n.replace(/"/g,'\\"')}"`:n}function Ca(n){return n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1).replace(/\\"/g,'"'):n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1):n}var Ns=v(()=>{});function ue(n){try{let e=n.split(`
|
|
4
4
|
`),t=0;if(e[t]?.trim()!=="---")return null;t++;let r=[];for(;t<e.length&&e[t]?.trim()!=="---";)r.push(e[t]),t++;if(e[t]?.trim()!=="---")return null;t++;let s=av(r);if(!s)return null;let i=new Map,o=new Map,a=[],l=t;for(;t<e.length;){let d=e[t]?.trim()?.match(Xd);if(d){let u=d[1].trim();for(t++;t<e.length&&e[t]?.trim()==="";)t++;let f=e[t]?.match(Is);if(!f){a.push(`**${u}** has no code fence \u2014 block skipped`);continue}let p=f[1];t++;let m=t+1,h=[],b=Ra(p);for(;t<e.length&&!e[t]?.match(b);)h.push(e[t]),t++;let A=t<e.length;t++,a.push(...iv(u,h,A)),i.set(u,h.join(`
|
|
5
5
|
`)),o.set(u,m),l=t}else t++}return{frontmatter:s,files:i,warnings:a,bodyEndLine:l,starts:o}}catch{return null}}function iv(n,e,t){let r=[];for(let s=0;s<e.length;s++){let i=e[s]?.trim().match(Xd);i&&sv.has(i[1].trim())&&ov(e,s)&&r.push(i[1].trim())}return r.length?r.map(s=>`**${n}** block has an unterminated code fence \u2014 it swallowed the **${s}** block.`):t?[]:[`**${n}** block has an unterminated code fence (it runs to the end of the file).`]}function ov(n,e){let t=e+1;for(;t<n.length&&n[t]?.trim()==="";)t++;return!!n[t]?.match(Is)}function av(n){let e={};for(let t of n){let r=t.indexOf(":");if(r===-1)continue;let s=t.slice(0,r).trim(),i=t.slice(r+1).trim();switch(s){case"format":e.format=i;break;case"name":e.name=Ca(i);break}}return!Gd(e.format)||!e.name?null:e}function Qd(n){return ue(n)?.warnings??[]}function Zd(n){let e=Object.fromEntries(_e.map(t=>[t,n.files.get(le[t].path)||""]));return{name:n.frontmatter.name,...e}}var Xd,Is,sv,Ra,_a=v(()=>{_s();Ns();Xd=/^\*\*(.+)\*\*$/,Is=/^(`{3,})(\w*)\s*$/,sv=new Set(_e.map(n=>le[n].path)),Ra=n=>new RegExp(`^${n}\\s*$`)});function ef(n){let e=n.match(/^`{3,}/gm),t=e?Math.max(...e.map(r=>r.length)):0;return"`".repeat(Math.max(3,t+1))}function tf(n,e){let{path:t}=le[n],r=t.split(".").pop(),s=ef(e);return`**${t}**
|
|
6
6
|
|
|
@@ -169,17 +169,17 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
169
169
|
html[data-theme="dark"] { color-scheme: dark; }
|
|
170
170
|
html[data-theme="light"] { color-scheme: light; }`,kc=" html, body { height: 100%; }"});var ne=v(()=>{_s();_a();of();uf();yc();cm();bm();vm();Sm();Ns()});function we(n){return n.length>5e4?n.slice(0,5e4)+`
|
|
171
171
|
\u2026[${n.length-5e4} more characters truncated]`:n}function $e(n){let e=n.replace(eE,"").split(`
|
|
172
|
-
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let r=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${r} (+${s} line${s===1?"":"s"})`:r}var eE,Li,Fr=v(()=>{eE=/\u001b\[[0-9;]*m/g;Li=(n,e)=>``});import{existsSync as tE,readdirSync as nE,statSync as rE}from"fs";import{join as sE}from"path";function Mi(n){if(!tE(n))return[];let e;try{e=nE(n)}catch{return[]}let t=[];for(let r of e){if(!r.endsWith(".jsonl"))continue;let s=sE(n,r);try{let i=rE(s);i.isFile()&&t.push({sessionId:r.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Ec=v(()=>{});var St,Bi=v(()=>{St=class{ensureHarnessSupport(){}}});import{openSync as iE,readSync as oE,closeSync as aE,statSync as lE,readdirSync as cE,readFileSync as uE,existsSync as dE}from"fs";import{join as qr}from"path";import{homedir as Oc}from"os";function fE(n){return n.replace(/[^a-zA-Z0-9]/g,"-")}function Di(n){let e=n?.type==="image"?n.source:void 0;return e?.type==="base64"&&e.data?Li(e.data,e.media_type):""}function Ac(n){return typeof n=="string"?we(n):Array.isArray(n)?n.map(e=>{if(typeof e=="string")return we(e);let t=e;return typeof t?.text=="string"?we(t.text):t?.content!=null?Ac(t.content):Di(t)}).join(`
|
|
172
|
+
`).map(i=>i.trim()).filter(Boolean),t=e[0];if(!t)return"";let r=t.length>300?t.slice(0,300).trimEnd()+"\u2026":t,s=e.length-1;return s>0?`${r} (+${s} line${s===1?"":"s"})`:r}var eE,Li,Fr=v(()=>{"use strict";eE=/\u001b\[[0-9;]*m/g;Li=(n,e)=>``});import{existsSync as tE,readdirSync as nE,statSync as rE}from"fs";import{join as sE}from"path";function Mi(n){if(!tE(n))return[];let e;try{e=nE(n)}catch{return[]}let t=[];for(let r of e){if(!r.endsWith(".jsonl"))continue;let s=sE(n,r);try{let i=rE(s);i.isFile()&&t.push({sessionId:r.slice(0,-6),file:s,mtime:i.mtimeMs})}catch{}}return t}var Ec=v(()=>{"use strict"});var St,Bi=v(()=>{"use strict";St=class{ensureHarnessSupport(){}}});import{openSync as iE,readSync as oE,closeSync as aE,statSync as lE,readdirSync as cE,readFileSync as uE,existsSync as dE}from"fs";import{join as qr}from"path";import{homedir as Oc}from"os";function fE(n){return n.replace(/[^a-zA-Z0-9]/g,"-")}function Di(n){let e=n?.type==="image"?n.source:void 0;return e?.type==="base64"&&e.data?Li(e.data,e.media_type):""}function Ac(n){return typeof n=="string"?we(n):Array.isArray(n)?n.map(e=>{if(typeof e=="string")return we(e);let t=e;return typeof t?.text=="string"?we(t.text):t?.content!=null?Ac(t.content):Di(t)}).join(`
|
|
173
173
|
`):n==null?"":we(JSON.stringify(n))}function hE(n){let e=n.trim();return!!e&&Tm.some(t=>t.test(e))}function mE(n){let e=n.trim();return e?Tm.some(t=>{let r=t.exec(e);return!!r&&r.index===0}):!0}function yE(n){return n.replace(gE,"")}function bE(n){let e=/^<command-name>([\s\S]*?)<\/command-name>/.exec(n)?.[1]?.trim();if(!e)return;let t=/<command-args>([\s\S]*?)<\/command-args>/.exec(n)?.[1]?.trim();return t?`${e} ${t}`:e}function kt(n){let e=yE(n).trim();return e?bE(e)??(hE(e)?"":e):""}function Tc(n){return n?.type==="text"&&typeof n.text=="string"?kt(n.text):""}function Pc(n,e){if(typeof n=="string")return $e(n);if(!n||typeof n!="object")return $e(e);let t=n;if(t.type==="text"&&typeof t.file?.numLines=="number")return Le(t.file.numLines,"line");if(t.type==="image"){let r=Em(t.file?.originalSize);return r?`image (${r})`:"image"}if(t.type==="pdf"){let r=Em(t.file?.originalSize);return r?`PDF (${r})`:"PDF"}if(t.type==="parts"&&typeof t.file?.count=="number")return Le(t.file.count,"page");if(t.type==="file_unchanged")return"unchanged since last read";if(t.type==="create"&&typeof t.content=="string")return`created, ${Le(t.content.split(`
|
|
174
174
|
`).length,"line")}`;if(t.mode==="content")return Le(t.numLines??0,"line");if(t.mode==="count")return`${Le(t.numMatches??0,"match","matches")} (${Le(t.numFiles??0,"file")})`;if(t.mode==="files_with_matches")return Le(t.numFiles??0,"file");if(Array.isArray(t.structuredPatch)){let r=0,s=0;for(let i of t.structuredPatch)for(let o of i?.lines??[])typeof o=="string"&&(o.startsWith("+")?r++:o.startsWith("-")&&s++);return`+${r} \u2212${s}`}return typeof t.stdout=="string"||typeof t.stderr=="string"?t.backgroundTaskId?"running in background":t.interrupted?"interrupted":$e(t.stdout||t.stderr||"")||"no output":typeof t.code=="number"&&typeof t.codeText=="string"?`${t.code} ${t.codeText}`:typeof t.searchCount=="number"?Le(t.searchCount,"search","searches"):Array.isArray(t.matches)&&typeof t.total_deferred_tools=="number"?Le(t.matches.length,"tool"):Array.isArray(t.newTodos)?Le(t.newTodos.length,"todo"):typeof t.numFiles=="number"?Le(t.numFiles,"file"):$e(e)}function Ur(n){return!!n.isSidechain||!!n.isMeta}function wE(n){let e;try{e=iE(n,"r")}catch{return""}try{let r=65536;try{r=lE(n).size}catch{}let s=(c,d)=>{if(d<=0)return"";let u=Buffer.alloc(d),f=oE(e,u,0,d,c);return u.subarray(0,f).toString("utf8")},i=(c,d,u)=>{let f="";for(let p of c.split(`
|
|
175
175
|
`)){if(!p.includes(`"${d}"`))continue;let m;try{m=JSON.parse(p)}catch{continue}let h=m?.[u];m?.type===d&&typeof h=="string"&&h&&(f=h)}return f},o=s(0,Math.min(65536,r)),a=r>65536?s(r-65536,65536):"",l=i(a,"custom-title","customTitle")||i(o,"custom-title","customTitle")||i(a,"ai-title","aiTitle")||i(o,"ai-title","aiTitle");if(l)return l.replace(/\s+/g," ").trim().slice(0,200);for(let c of o.split(`
|
|
176
|
-
`)){if(!c.trim())continue;let d;try{d=JSON.parse(c)}catch{continue}if(!d||Ur(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=kt(u):Array.isArray(u)&&(f=u.map(Tc).filter(Boolean).join(" "));let p=f.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{aE(e)}}function vE(n){let e;try{e=cE(Am)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let r=JSON.parse(uE(qr(Am,t),"utf8"));if(r?.sessionId!==n)continue;return process.kill(r.pid,0),!0}catch{}return!1}var pE,xm,Tm,gE,Le,Em,Am,On,ji=v(()=>{Fr();Ec();Bi();pE=qr(Oc(),".claude","projects"),xm=n=>qr(pE,fE(n));Tm=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];gE=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Le=(n,e,t=e+"s")=>`${n} ${n===1?e:t}`,Em=n=>typeof n!="number"?"":n<1024?`${n}B`:n<1048576?`${Math.round(n/1024)}KB`:`${(n/1048576).toFixed(1)}MB`;Am=qr(Oc(),".claude","sessions");On=class extends St{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return dE(qr(Oc(),".claude"))}sessionsDir(e){return xm(e)}listSessionFiles(e){return Mi(xm(e))}parseEntry(e){try{return JSON.parse(e)}catch{return null}}idOf(e){return e.uuid}parentOf(e){return e.parentUuid}timestampOf(e){return e.timestamp}isSidechain(e){return!!e.isSidechain}isLeafType(e){return e.type==="user"||e.type==="assistant"}isRecoveryNoise(e){return!!e.isApiErrorMessage}apply(e,t){if(Ur(e))return{events:[]};let r=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=kt(s);i&&r.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Ac(i.content);r.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Pc(e.toolUseResult,o)})}else{let o=Tc(i)||Di(i);o&&r.push({type:"user",text:o})}return{events:r}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=kt(Ac(e.attachment.prompt));return s&&r.push({type:"user",text:s}),{events:r}}if(e.type==="assistant"){let s=e.message?.content,i=Array.isArray(s)?s:[],o=i.filter(u=>u.type==="text").map(u=>u.text??"").filter(u=>!mE(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
176
|
+
`)){if(!c.trim())continue;let d;try{d=JSON.parse(c)}catch{continue}if(!d||Ur(d)||d.type!=="user")continue;let u=d.message?.content,f="";typeof u=="string"?f=kt(u):Array.isArray(u)&&(f=u.map(Tc).filter(Boolean).join(" "));let p=f.replace(/\s+/g," ").trim();if(p)return(p.replace(/^Continuing from a prior session\. Here is the summary of our work so far:\s*/i,"").trim()||p).slice(0,200)}return""}finally{aE(e)}}function vE(n){let e;try{e=cE(Am)}catch{return!1}for(let t of e)if(t.endsWith(".json"))try{let r=JSON.parse(uE(qr(Am,t),"utf8"));if(r?.sessionId!==n)continue;return process.kill(r.pid,0),!0}catch{}return!1}var pE,xm,Tm,gE,Le,Em,Am,On,ji=v(()=>{"use strict";Fr();Ec();Bi();pE=qr(Oc(),".claude","projects"),xm=n=>qr(pE,fE(n));Tm=[/\[Request interrupted by user\b/i,/\[Tool use was interrupted\]/i,/Claude Code returned an error/i,/\[ede_diagnostic\]/i,/^No response requested\.?$/i,/^<task-notification\b/i,/^<system-reminder\b/i,/^<local-command-stdout\b/i,/^<local-command-stderr\b/i];gE=/<ide_[a-z_]+>[\s\S]*?<\/ide_[a-z_]+>/gi;Le=(n,e,t=e+"s")=>`${n} ${n===1?e:t}`,Em=n=>typeof n!="number"?"":n<1024?`${n}B`:n<1048576?`${Math.round(n/1024)}KB`:`${(n/1048576).toFixed(1)}MB`;Am=qr(Oc(),".claude","sessions");On=class extends St{displayName="Claude Mirror";detectsSelf(){return process.env.CLAUDECODE==="1"}detectsInstalled(){return dE(qr(Oc(),".claude"))}sessionsDir(e){return xm(e)}listSessionFiles(e){return Mi(xm(e))}parseEntry(e){try{return JSON.parse(e)}catch{return null}}idOf(e){return e.uuid}parentOf(e){return e.parentUuid}timestampOf(e){return e.timestamp}isSidechain(e){return!!e.isSidechain}isLeafType(e){return e.type==="user"||e.type==="assistant"}isRecoveryNoise(e){return!!e.isApiErrorMessage}apply(e,t){if(Ur(e))return{events:[]};let r=[];if(e.type==="user"){let s=e.message?.content;if(typeof s=="string"){let i=kt(s);i&&r.push({type:"user",text:i})}else if(Array.isArray(s))for(let i of s)if(i?.type==="tool_result"){let o=Ac(i.content);r.push({type:"tool_result",id:i.tool_use_id??"",content:o,isError:!!i.is_error,digest:Pc(e.toolUseResult,o)})}else{let o=Tc(i)||Di(i);o&&r.push({type:"user",text:o})}return{events:r}}if(e.type==="attachment"&&e.attachment?.type==="queued_command"){let s=kt(Ac(e.attachment.prompt));return s&&r.push({type:"user",text:s}),{events:r}}if(e.type==="assistant"){let s=e.message?.content,i=Array.isArray(s)?s:[],o=i.filter(u=>u.type==="text").map(u=>u.text??"").filter(u=>!mE(u)).join(""),a=i.filter(u=>u.type==="thinking").map(u=>u.thinking??"").join(`
|
|
177
177
|
`),l=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||l.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;r.push({type:"assistant",text:o,thinking:a,tools:l,live:f})}let c=e.message?.usage??e.usage,d=c&&{in:c.input_tokens??0,out:c.output_tokens??0,cached:c.cache_read_input_tokens??0,cacheCreate:c.cache_creation_input_tokens??0};return{events:r,usage:d,model:e.message?.model}}return{events:r}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(c=>c&&c.type==="text").map(c=>c.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(c=>c&&c.type==="tool_result"))&&a.trim()&&kt(a)==="")return!1}catch{}return!0}let s=(Array.isArray(t.message?.content)?t.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(s.length===0)return!1;let i=new Set;for(let o of e){let a=o.message?.content;if(Array.isArray(a))for(let l of a)l.type==="tool_result"&&l.tool_use_id&&i.add(l.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return vE(e)}readPreview(e){return wE(e)}searchText(e){if(!e||Ur(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,r="";if(typeof t=="string")r=kt(t);else if(Array.isArray(t)){let s=t;r=e.type==="user"?s.map(Tc).filter(Boolean).join(" "):s.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")}return r.replace(/\s+/g," ").trim()}}});import{statSync as SE,readdirSync as kE,openSync as xE,readSync as EE,closeSync as AE,existsSync as TE}from"fs";import{basename as OE,join as Cc,resolve as PE}from"path";import{homedir as Om}from"os";function RE(n){let e=n.trimStart();return CE.some(t=>e.startsWith(t))}function Jr(n,e){return Array.isArray(n)?n.map(t=>typeof t?.text=="string"?e&&RE(t.text)?"":we(t.text):t?.type==="input_image"&&typeof t.image_url=="string"&&t.image_url.startsWith("data:")?``:"").filter(Boolean).join(`
|
|
178
178
|
`):""}function _E(n){return typeof n=="string"?we(n):Jr(n,!1)}function NE(n){let e=n??"";for(let t of[/tools\.shell_command\((\{[\s\S]*?\})\)/,/tools\.shell_command\((\{[\s\S]*\})\)/]){let r=t.exec(e);if(r)try{return JSON.parse(r[1])}catch{}}return{script:e}}function IE(n){if(typeof n=="string"&&n)try{let e=JSON.parse(n);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{arguments:n??""}}function Cm(n,e){let t;try{t=xE(n,"r")}catch{return}try{let r=Buffer.alloc(e),s=EE(t,r,0,e,0);return{text:r.subarray(0,s).toString("utf8"),bytes:s}}finally{AE(t)}}function $E(n){let t=Cm(n,65536);if(t===void 0)return;let r=t.text.indexOf(`
|
|
179
|
-
`);if(r<0)return t.bytes>=65536?"":void 0;try{let s=JSON.parse(t.text.slice(0,r));return s?.type==="session_meta"&&typeof s.payload?.cwd=="string"?s.payload.cwd:""}catch{return""}}var CE,Pm,Pn,Rc=v(()=>{Fr();Bi();CE=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<user_instructions>"];Pm=n=>{let e=PE(n);return process.platform==="win32"?e.toLowerCase():e},Pn=class extends St{constructor(t=Cc(Om(),".codex","sessions")){super();this.root=t}displayName="Codex Mirror";#e=0;#t;#n=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}detectsInstalled(){return TE(Cc(Om(),".codex"))}sessionsDir(t){return this.root}listSessionFiles(t){let r=Pm(t),s=[];for(let i of this.#r()){let o;try{let l=SE(i);if(!l.isFile())continue;o=l.mtimeMs}catch{continue}let a=this.#n.get(i);if(a===void 0){if(a=$E(i),a===void 0)continue;this.#n.set(i,a)}Pm(a)===r&&s.push({sessionId:OE(i,".jsonl"),file:i,mtime:o})}return s}#r(){let t=[],r=s=>{try{return kE(s).map(i=>Cc(s,i))}catch{return[]}};for(let s of r(this.root))for(let i of r(s))for(let o of r(i))for(let a of r(o))a.endsWith(".jsonl")&&t.push(a);return t}parseEntry(t){let r;try{r=JSON.parse(t)}catch{return null}return!r||typeof r.type!="string"?null:r}idOf(t){return t.ord===void 0&&(t.ord=String(this.#e++),t.parent=this.#t,this.#t=t.ord),t.ord}parentOf(t){return t.parent}timestampOf(t){return t.timestamp}isSidechain(t){return!1}isLeafType(t){return!0}isRecoveryNoise(t){return!1}apply(t,r){let s=[],i=t.payload;if(!i)return{events:s};let o=()=>{let a=Date.parse(t.timestamp??"");return!isNaN(a)&&a>=r};if(t.type==="response_item"){if(i.type==="message"){if(i.role==="user"){let a=Jr(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=Jr(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=Jr(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.type==="custom_tool_call"?NE(i.input):IE(i.arguments);return s.push({type:"assistant",text:"",thinking:"",tools:[{id:i.call_id??"",name:i.name??"",input:a}],live:o()}),{events:s}}if(i.type==="custom_tool_call_output"||i.type==="function_call_output"){let a=_E(i.output);return s.push({type:"tool_result",id:i.call_id??"",content:a,isError:!1,digest:$e(a)}),{events:s}}return{events:s}}if(t.type==="event_msg"){if(i.type==="token_count"){let a=i.info?.last_token_usage;if(!a)return{events:s};let l={in:Math.max(0,(a.input_tokens??0)-(a.cached_input_tokens??0)),out:a.output_tokens??0,cached:a.cached_input_tokens??0,cacheCreate:a.cache_write_input_tokens??0};return{events:s,usage:l}}return{events:s}}return t.type==="turn_context"?{events:s,model:i.model}:{events:s}}chainWorking(t){let r=!1;for(let s of t){if(s.type!=="event_msg")continue;let i=s.payload?.type;i==="task_started"?r=!0:(i==="task_complete"||i==="turn_aborted")&&(r=!1)}return r}sessionAlive(){}readPreview(t){for(let r of(Cm(t,256*1024)?.text??"").split(`
|
|
180
|
-
`))if(r.includes('"user_message"'))try{let s=JSON.parse(r);if(s?.type==="event_msg"&&s.payload?.type==="user_message"&&typeof s.payload.message=="string"){let i=s.payload.message.replace(/\s+/g," ").trim();if(i)return i.slice(0,200)}}catch{}return""}searchText(t){if(t?.type!=="response_item"||t.payload?.type!=="message")return"";let r=t.payload.role;return r!=="user"&&r!=="assistant"?"":Jr(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as LE}from"fs";import{createHash as ME}from"crypto";import{join as Fi,resolve as BE}from"path";import{homedir as DE}from"os";function xt(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?Fi(n,".."):Fi(DE(),".typebulb")}function Ze(){Rm||(Rm=!0,console.error(`${xt()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function et(){return process.env.TYPEBULB_SERVERS_DIR||Fi(xt(),"servers")}function _m(n){let e=X(n),t=ME("sha1").update(e).digest("hex").slice(0,8),r=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return Fi(xt(),"canvas",`${r}-${t}.png`)}function X(n){let e=BE(n),t=e;try{t=LE.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Nm(n,e){let t=X(n),r=X(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Rm,Et=v(()=>{Rm=!1});var Me,Ui=v(()=>{Me="0.
|
|
179
|
+
`);if(r<0)return t.bytes>=65536?"":void 0;try{let s=JSON.parse(t.text.slice(0,r));return s?.type==="session_meta"&&typeof s.payload?.cwd=="string"?s.payload.cwd:""}catch{return""}}var CE,Pm,Pn,Rc=v(()=>{"use strict";Fr();Bi();CE=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<user_instructions>"];Pm=n=>{let e=PE(n);return process.platform==="win32"?e.toLowerCase():e},Pn=class extends St{constructor(t=Cc(Om(),".codex","sessions")){super();this.root=t}displayName="Codex Mirror";#e=0;#t;#n=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}detectsInstalled(){return TE(Cc(Om(),".codex"))}sessionsDir(t){return this.root}listSessionFiles(t){let r=Pm(t),s=[];for(let i of this.#r()){let o;try{let l=SE(i);if(!l.isFile())continue;o=l.mtimeMs}catch{continue}let a=this.#n.get(i);if(a===void 0){if(a=$E(i),a===void 0)continue;this.#n.set(i,a)}Pm(a)===r&&s.push({sessionId:OE(i,".jsonl"),file:i,mtime:o})}return s}#r(){let t=[],r=s=>{try{return kE(s).map(i=>Cc(s,i))}catch{return[]}};for(let s of r(this.root))for(let i of r(s))for(let o of r(i))for(let a of r(o))a.endsWith(".jsonl")&&t.push(a);return t}parseEntry(t){let r;try{r=JSON.parse(t)}catch{return null}return!r||typeof r.type!="string"?null:r}idOf(t){return t.ord===void 0&&(t.ord=String(this.#e++),t.parent=this.#t,this.#t=t.ord),t.ord}parentOf(t){return t.parent}timestampOf(t){return t.timestamp}isSidechain(t){return!1}isLeafType(t){return!0}isRecoveryNoise(t){return!1}apply(t,r){let s=[],i=t.payload;if(!i)return{events:s};let o=()=>{let a=Date.parse(t.timestamp??"");return!isNaN(a)&&a>=r};if(t.type==="response_item"){if(i.type==="message"){if(i.role==="user"){let a=Jr(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=Jr(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=Jr(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.type==="custom_tool_call"?NE(i.input):IE(i.arguments);return s.push({type:"assistant",text:"",thinking:"",tools:[{id:i.call_id??"",name:i.name??"",input:a}],live:o()}),{events:s}}if(i.type==="custom_tool_call_output"||i.type==="function_call_output"){let a=_E(i.output);return s.push({type:"tool_result",id:i.call_id??"",content:a,isError:!1,digest:$e(a)}),{events:s}}return{events:s}}if(t.type==="event_msg"){if(i.type==="token_count"){let a=i.info?.last_token_usage;if(!a)return{events:s};let l={in:Math.max(0,(a.input_tokens??0)-(a.cached_input_tokens??0)),out:a.output_tokens??0,cached:a.cached_input_tokens??0,cacheCreate:a.cache_write_input_tokens??0};return{events:s,usage:l}}return{events:s}}return t.type==="turn_context"?{events:s,model:i.model}:{events:s}}chainWorking(t){let r=!1;for(let s of t){if(s.type!=="event_msg")continue;let i=s.payload?.type;i==="task_started"?r=!0:(i==="task_complete"||i==="turn_aborted")&&(r=!1)}return r}sessionAlive(){}readPreview(t){for(let r of(Cm(t,256*1024)?.text??"").split(`
|
|
180
|
+
`))if(r.includes('"user_message"'))try{let s=JSON.parse(r);if(s?.type==="event_msg"&&s.payload?.type==="user_message"&&typeof s.payload.message=="string"){let i=s.payload.message.replace(/\s+/g," ").trim();if(i)return i.slice(0,200)}}catch{}return""}searchText(t){if(t?.type!=="response_item"||t.payload?.type!=="message")return"";let r=t.payload.role;return r!=="user"&&r!=="assistant"?"":Jr(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as LE}from"fs";import{createHash as ME}from"crypto";import{join as Fi,resolve as BE}from"path";import{homedir as DE}from"os";function xt(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?Fi(n,".."):Fi(DE(),".typebulb")}function Ze(){Rm||(Rm=!0,console.error(`${xt()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function et(){return process.env.TYPEBULB_SERVERS_DIR||Fi(xt(),"servers")}function _m(n){let e=X(n),t=ME("sha1").update(e).digest("hex").slice(0,8),r=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return Fi(xt(),"canvas",`${r}-${t}.png`)}function X(n){let e=BE(n),t=e;try{t=LE.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function Nm(n,e){let t=X(n),r=X(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Rm,Et=v(()=>{"use strict";Rm=!1});var Me,Ui=v(()=>{"use strict";Me="0.51.0"});import{spawn as Im}from"child_process";import{readdir as jE,readFile as Lm,writeFile as Mm,unlink as _c,mkdir as FE}from"fs/promises";import{mkdirSync as Bm,writeFileSync as qi,appendFileSync as UE,readFileSync as Nc}from"fs";import*as Ee from"path";import{fileURLToPath as qE}from"url";function Ic(n){return Ee.join(et(),`${n}.json`)}function Hr(n){return Ee.join(et(),`${n}.log`)}function $c(n){return Ee.join(et(),`${n}.wait.json`)}function Dm(n){try{let e=JSON.parse(Nc($c(n),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Lc(n,e=""){let t=Dm(n)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function Ji(n,e,t=""){try{Bm(et(),{recursive:!0});let r=Dm(n);r[t]=e,qi($c(n),JSON.stringify({cursors:r}))}catch{}}function Ki(n){let e=Hr(n);try{Bm(et(),{recursive:!0}),qi(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(UE(e,l),s+=l.length,s>2*$m){let c=Nc(e),d=c.subarray(Math.max(0,c.length-$m));qi(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),t(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=t,process.stderr.write=r}}function jm(n){try{qi(Hr(n),"")}catch{}}function We(n,e=0){try{let t=Nc(Hr(n)),r=e>=0&&e<=t.length?e:0;return{text:t.subarray(r).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function Mc(n){return`\u2500\u2500 run ${n} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function KE(n){let e=JE.exec(n);return e?Number(e[1]):void 0}function Fm(n,e){let t=n.split(`
|
|
181
181
|
`),r=[];if(t.forEach((o,a)=>{let l=KE(o);l!==void 0&&r.push({id:l,idx:a})}),!r.length)return e==="latest"?n:"";let s=e==="latest"?r[r.length-1]:r.find(o=>o.id===e);if(!s)return"";let i=r.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
|
|
182
|
-
`)}function Bc(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function Um(n){try{await FE(et(),{recursive:!0}),await Mm(Ic(n.pid),JSON.stringify({version:Me,...n}))}catch{Ze()}}async function qm(n,e){let t=Ic(n);try{let r=JSON.parse(await Lm(t,"utf8"));if(r.denied===e)return;r.denied=e,await Mm(t,JSON.stringify(r))}catch{}}async function Kr(n){await _c(Ic(n)).catch(()=>{}),await _c(Hr(n)).catch(()=>{}),await _c($c(n)).catch(()=>{})}async function Q(n){let e;try{e=await jE(et())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Lm(Ee.join(et(),s),"utf8"))}catch{await Kr(i);return}o&&typeof o.pid=="number"&&Bc(o.pid)?t.push(o):await Kr(i)})),(n?t.filter(s=>s.agent==null&&Nm(s.file,n)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Dc(n,e){let t=X(n);return(await Q()).find(r=>r.cwd!=null&&X(r.cwd)===t&&(e?r.agent===e:r.agent!=null))}async function Wt(n){try{process.kill(n,"SIGTERM")}catch{}await Kr(n)}function Cn(n,e){let t=X(e);return n.filter(r=>r.agent==null&&r.pid!==process.pid&&X(r.file)===t)}async function jc(n){let e=Cn(await Q(),n);for(let t of e)await Wt(t.pid);return e}function WE(n,e,t){(process.platform==="win32"?Im("cmd",["/c","start","","/b",n,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Im(n,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Jm(){return Ee.join(Ee.dirname(qE(import.meta.url)),"index.js")}function YE(n,e={}){return{command:process.execPath,args:[Jm(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],n,...e.open===!1?["--no-open"]:[]]}}function VE(n){return{command:process.execPath,args:[Jm(),`agent:${n}`,"--no-open"]}}async function Km(n,e,t,r){let s=await n();if(s)return s;WE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await HE(150);let o=await n();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function Hi(n,e={}){let t=e.cwd??process.cwd(),r=Ee.resolve(t,n),[s]=await jc(r),i={...e,batch:e.batch??s?.batch,mode:e.mode??s?.mode};return Km(async()=>Cn(await Q(),r)[0],YE(n,i),t,Ee.basename(n))}async function Hm(n,e=process.cwd()){return Km(()=>Dc(e,n),VE(n),e,`the ${n} mirror`)}var $m,JE,HE,Be=v(()=>{Et();Ui();$m=1e6;JE=/^── run (\d+) ── /;HE=n=>new Promise(e=>setTimeout(e,n))});function Rn(n){return{...Zd(n),server:n.files.get("server.ts")??""}}function Wi(n){return!!n.server&&!n.code}var Wr=v(()=>{ne();ne()});function Yi(n){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(n),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Fc(n){return An(Yi(n)??"bulb")||"bulb"}var Uc=v(()=>{ne()});import{transform as zE}from"sucrase";function qc(n,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=zE(n,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var Wm=v(()=>{});function Jc(n){let e=n.split(""),t=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
|
|
182
|
+
`)}function Bc(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function Um(n){try{await FE(et(),{recursive:!0}),await Mm(Ic(n.pid),JSON.stringify({version:Me,...n}))}catch{Ze()}}async function qm(n,e){let t=Ic(n);try{let r=JSON.parse(await Lm(t,"utf8"));if(r.denied===e)return;r.denied=e,await Mm(t,JSON.stringify(r))}catch{}}async function Kr(n){await _c(Ic(n)).catch(()=>{}),await _c(Hr(n)).catch(()=>{}),await _c($c(n)).catch(()=>{})}async function Q(n){let e;try{e=await jE(et())}catch{return[]}let t=[];return await Promise.all(e.map(async s=>{if(!/^\d+\.json$/.test(s))return;let i=parseInt(s,10),o;try{o=JSON.parse(await Lm(Ee.join(et(),s),"utf8"))}catch{await Kr(i);return}o&&typeof o.pid=="number"&&Bc(o.pid)?t.push(o):await Kr(i)})),(n?t.filter(s=>s.agent==null&&Nm(s.file,n)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Dc(n,e){let t=X(n);return(await Q()).find(r=>r.cwd!=null&&X(r.cwd)===t&&(e?r.agent===e:r.agent!=null))}async function Wt(n){try{process.kill(n,"SIGTERM")}catch{}await Kr(n)}function Cn(n,e){let t=X(e);return n.filter(r=>r.agent==null&&r.pid!==process.pid&&X(r.file)===t)}async function jc(n){let e=Cn(await Q(),n);for(let t of e)await Wt(t.pid);return e}function WE(n,e,t){(process.platform==="win32"?Im("cmd",["/c","start","","/b",n,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Im(n,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Jm(){return Ee.join(Ee.dirname(qE(import.meta.url)),"index.js")}function YE(n,e={}){return{command:process.execPath,args:[Jm(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],n,...e.open===!1?["--no-open"]:[]]}}function VE(n){return{command:process.execPath,args:[Jm(),`agent:${n}`,"--no-open"]}}async function Km(n,e,t,r){let s=await n();if(s)return s;WE(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await HE(150);let o=await n();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function Hi(n,e={}){let t=e.cwd??process.cwd(),r=Ee.resolve(t,n),[s]=await jc(r),i={...e,batch:e.batch??s?.batch,mode:e.mode??s?.mode};return Km(async()=>Cn(await Q(),r)[0],YE(n,i),t,Ee.basename(n))}async function Hm(n,e=process.cwd()){return Km(()=>Dc(e,n),VE(n),e,`the ${n} mirror`)}var $m,JE,HE,Be=v(()=>{"use strict";Et();Ui();$m=1e6;JE=/^── run (\d+) ── /;HE=n=>new Promise(e=>setTimeout(e,n))});function Rn(n){return{...Zd(n),server:n.files.get("server.ts")??""}}function Wi(n){return!!n.server&&!n.code}var Wr=v(()=>{"use strict";ne();ne()});function Yi(n){let e=/^---[^\n]*\n([\s\S]*?)\n---/.exec(n),t=e?/^\s*name:\s*(.+?)\s*$/m.exec(e[1]):null;return t?t[1].replace(/^["']|["']$/g,""):void 0}function Fc(n){return An(Yi(n)??"bulb")||"bulb"}var Uc=v(()=>{"use strict";ne()});import{transform as zE}from"sucrase";function qc(n,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=zE(n,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var Wm=v(()=>{});function Jc(n){let e=n.split(""),t=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
|
|
183
183
|
`&&(e[a]=" ")},r=0,s="";for(;r<n.length;){let i=n[r],o=n[r+1];if(i==="/"&&o==="/"){let a=r;for(;a<n.length&&n[a]!==`
|
|
184
184
|
`;)a++;t(r,a),r=a}else if(i==="/"&&o==="*"){let a=r+2;for(;a<n.length&&!(n[a]==="*"&&n[a+1]==="/");)a++;t(r,Math.min(a+2,n.length)),r=a+2}else if(i==="/"&&GE.has(s)){let a=r+1,l=!1;for(;a<n.length&&n[a]!==`
|
|
185
185
|
`;){let c=n[a];if(c==="\\")a++;else if(c==="[")l=!0;else if(c==="]")l=!1;else if(c==="/"&&!l)break;a++}r=a+1,s="/"}else if(i==='"'||i==="'"){let a=r+1;for(;a<n.length&&n[a]!==i&&n[a]!==`
|
|
@@ -358,8 +358,8 @@ const something = require('module-name') // NOT SUPPORTED!
|
|
|
358
358
|
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Yt,Vt,XE,QE,Vi=v(()=>{Vm();Yt=["client"],Vt=["client","server"],XE=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Yt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Vt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Yt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Yt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Yt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Vt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Vt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Vt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Vt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Vt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Vt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Yt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Yt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Yt}],QE=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function rA(n){return n.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
359
359
|
`)[0]}`).join(`
|
|
360
360
|
`)}function Xm(n,e){let t=Yr(n,{target:"client",dependencies:e}).filter(r=>r.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
361
|
-
${rA(t)}`)}var Qm=v(()=>{Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="https://cdn.jsdelivr.net/npm/",Kc="https://data.jsdelivr.com/v1/package/npm/"});function Zm(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var j,_n,eg,Gr=v(()=>{zr();j=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=_n(t??s.version),this.subpath=_n(r??s.subpath)}static parse(e){let t=Zm(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=eg(t[1]??""),a=_n(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=eg(t[0]),o=_n(t.slice(1).join("/"));return new n({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),r=new URL(At).host,s=new URL(Vr).host;if(t.host===r){let i=Zm(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return n.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return n.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return n.parse(e).name}withVersion(e){return new n({name:this.name,version:_n(e),subpath:this.subpath})}static isBare(e){if(!e||e.startsWith(".")||e.startsWith("/"))return!1;let t=e.toLowerCase();return!t.startsWith("http://")&&!t.startsWith("https://")}},_n=n=>n&&n.length?n:void 0,eg=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),_n(n.slice(e+1))]}});async function ye(n){try{return await n()}catch{return}}var zi=v(()=>{});function zt(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Hc(n){return n.startsWith("./")?n:`./${n}`}var Xr,Wc=v(()=>{Gr();zi();zr();Xr=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new j(e):e;return`${Vr}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(zt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:r="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:r});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${At}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),r=this.pinCache.get(e);if(r&&t-r.ts<this.pinMs)return r.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${At}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await ye(()=>this.http.head(t)),s=this.parseVersionFromUrl(r?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let r=await ye(()=>this.http.getJson(`${Kc}${encodeURIComponent(e)}`));if(!r?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=r.tags&&Object.keys(r.tags).length?r.tags:void 0;return await this.cache.setIndex(e,r.versions,s),{versions:r.versions,distTags:s}}parseVersionFromUrl(e){let t=j.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let r=await this.cache.getMeta(e,t);if(r&&Date.now()-r.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=r;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new j(`${e}@${t}`)),i=await ye(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),l=o(i.peerDependencies),c=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,l,c),{name:e,version:t,dependencies:a,peerDependencies:l,peerDependenciesMeta:c}}}});var tg,Qr,Yc,sA,Zr,Gi=v(()=>{tg=n=>n.startsWith("@types/"),Qr=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!tg(e)),Yc=n=>Object.keys(n?.dependencies||{}).filter(e=>!tg(e)),sA=n=>Qr(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),Zr=class{constructor(e){this.cdn=e}async resolve(e,t){let r=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(r,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:r})=>({name:t,version:r,meta:await this.cdn.fetchPackageMeta(t,r)})))}async expandWithPeers(e,t){let r=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of sA(i.meta))!r.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),l=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:l})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Qr(i.meta))),r=new Map;for(let i of e)for(let o of Yc(i.meta))r.set(o,(r.get(o)||0)+1);let s=new Set([...r.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:Qr(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var es,Vc=v(()=>{Gr();zi();es=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await ye(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let r=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(r)return r}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let r=await this.cache.getPinnedExact(e,t);if(r){if(this.semver.isExactVersion(r))return r;console.debug("[typebulb] cached version for",e,"is not exact (",r,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await ye(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await ye(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let l=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(l)return l}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let r=new j(e),s=r.root(),i=t[s],o=i?await ye(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as iA,parse as oA}from"es-module-lexer";var Nn,zc=v(()=>{Gr();zr();Gi();Nn=class n{constructor(e,t,r){this.version=e,this.cdn=t,this.peer=r}extractImportsSync(e){let t=new Set;for(let r of n.importPatterns){r.lastIndex=0;for(let s of e.matchAll(r))j.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,r=s=>{j.isBare(s)&&t.add(s)};try{await iA;let[s]=oA(e);s.forEach(i=>r(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,r){let s=(await this.extractImports(e)).filter(u=>!r?.has(j.rootOf(u))),i=[...new Set(s.map(j.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:l,autoAddedPeers:c}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...c.map(u=>u.name)],a,l);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let r=t[e],s=await this.version.resolveExactForRoot(e,r);if(!s)throw new Error(`Cannot resolve ${r?`${e}@${r}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,r){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let m=s.get(j.rootOf(p));return new j(p).withVersion(m.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==j.rootOf(p)).map(j.rootOf)),l=[],c=new Set,d=new Set(e.filter(p=>p===j.rootOf(p))),u=new Set;for(let p of e){let m=j.rootOf(p),h=s.get(m),{isPeerRoot:b,hasPeers:A,isSharedDep:S}=r.get(m),P=a.has(m),_=p!==m,R=!(b||S)&&(P||!A),$=this.singletonDepsOf(h,o),x=_&&d.has(m);x&&u.add(m);let D=x?[...$,m]:$.length?$:void 0;l.push([p,this.cdn.buildEsmUrl(i(p),{bundle:R,external:D})]),c.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(c.has(p)||l.push([p,this.cdn.buildEsmUrl(i(p),{})]),l.push([`${p}/`,`${At}/${i(p)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Qr(e.meta),...Yc(e.meta)])].filter(r=>t.has(r))}};Nn.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as ng,satisfies as aA,maxSatisfying as rg,major as lA,valid as cA}from"semver";var Xi,Gt,Gc=v(()=>{Xi=class{cmp(e,t){return e===t?0:ng(e,t)?1:ng(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!aA(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let r=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(r,i))return i;if(s){let a=rg(e,r,{includePrerelease:!1});if(a)return a}return rg(e,r,{includePrerelease:!0})??void 0}majorOf(e){return lA(e)}isExactVersion(e){return cA(e)!==null}},Gt=new Xi});function uA(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var Xt,sg=v(()=>{zi();Xt=class{constructor(e){this.store=e}async isNegative(e){let t=await ye(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await ye(()=>this.store.get(e)))?.attempts||0)+1;await ye(()=>this.store.set(e,{until:Date.now()+uA(r),attempts:r}))}async clearNegative(e){await ye(()=>this.store.delete(e))}}});function ig(n,e){let t=new Xr(n,e),r=new Zr(t),s=new es(n,t,Gt);return{packageService:new Nn(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var tt=v(()=>{Wc();Gi();Vc();zc();Gc();Gr();Gc();zr();Wc();Gi();Vc();zc();sg()});import*as Xc from"fs/promises";import*as og from"crypto";function De(n){return og.createHash("sha1").update(n).digest("hex")}async function nt(n){try{return JSON.parse(await Xc.readFile(n,"utf8"))}catch{return}}async function Qi(n){try{return await Xc.readFile(n,"utf8")}catch{return}}var In=v(()=>{});import*as Ot from"fs/promises";import*as rt from"path";import*as lg from"os";function Z(){return Qc||(Qc=fA().catch(()=>Ze())),Qc}function eo(n,e){return rt.join(dA,De(n),e)}async function fA(){await Ot.mkdir(Tt,{recursive:!0});let n=rt.join(Tt,"version.json");if((await nt(n))?.version===ag)return;let t=await Ot.readdir(Tt).catch(()=>[]);await Promise.all(t.map(r=>Ot.rm(rt.join(Tt,r),{recursive:!0,force:!0}))),await Ot.writeFile(n,JSON.stringify({version:ag})+`
|
|
362
|
-
`,"utf8")}var ag,Tt,ts,ns,Zi,dA,Qc,$n=v(()=>{In();Et();ag=1,Tt=rt.join(lg.homedir(),".typebulb","cache"),ts=rt.join(Tt,"packages"),ns=rt.join(Tt,"proxy"),Zi=rt.join(Tt,"dts"),dA=rt.join(Tt,"emit")});import*as Pt from"fs/promises";import*as cg from"path";async function Ae(n,e){let t=`${n}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await Pt.mkdir(cg.dirname(n),{recursive:!0}),await Pt.writeFile(t,e,"utf8")}catch{Ze();return}await Pt.rename(t,n).catch(async()=>{await Pt.rm(t,{force:!0}).catch(()=>{})})}var rs=v(()=>{Et()});var Ln,Zc=v(()=>{rs();In();Ln=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=nt(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let r=await this.load();r.set(e,t),await this.persist(r)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await Ae(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as fg from"fs/promises";import*as je from"path";function dg(n,e){return je.join(pA,to(n),encodeURIComponent(e)+".json")}function to(n){return n.replace(/\//g,"__")}var eu,ug,pA,hA,no,pg=v(()=>{tt();$n();rs();Zc();In();eu=je.join(ts,"indexes"),ug=je.join(ts,"pinned"),pA=je.join(ts,"meta"),hA=je.join(ts,"negative.json"),no=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Xt(new Ln(hA));async getPinnedExact(e,t){let r=`${e}@${t}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await Z();let s=await Qi(je.join(ug,De(r)+".txt"));return this.pinnedMem.set(r,s),s}async setPinnedExact(e,t,r){let s=`${e}@${t}`;this.pinnedMem.set(s,r),await Z(),await Ae(je.join(ug,De(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await Z();let t=await nt(je.join(eu,to(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,r){let s={versions:t,distTags:r,updatedAt:Date.now()};this.indexMem.set(e,s),await Z(),await Ae(je.join(eu,to(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await fg.rm(je.join(eu,to(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await Z(),this.negativeCache.isNegative(e)}async recordNegative(e){await Z(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let r=`${e}@${t}`;if(this.metaMem.has(r))return this.metaMem.get(r);await Z();let s=await nt(dg(e,t));return this.metaMem.set(r,s),s}async setMeta(e,t,r,s,i){let o={dependencies:r,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await Z(),await Ae(dg(e,t),JSON.stringify(o))}}});var hg,mg=v(()=>{hg={async getJson(n){try{let e=await fetch(n,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(n){try{let e=await fetch(n,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}}});var mA,ro,gg,yg,d$,tu=v(()=>{tt();pg();mg();mA=new no,{packageService:ro,versionResolver:gg,cdnClient:yg,peerResolver:d$}=ig(mA,hg)});function so(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function io(n,e){return` <script>
|
|
361
|
+
${rA(t)}`)}var Qm=v(()=>{"use strict";Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="https://cdn.jsdelivr.net/npm/",Kc="https://data.jsdelivr.com/v1/package/npm/"});function Zm(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var j,_n,eg,Gr=v(()=>{zr();j=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=_n(t??s.version),this.subpath=_n(r??s.subpath)}static parse(e){let t=Zm(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=eg(t[1]??""),a=_n(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=eg(t[0]),o=_n(t.slice(1).join("/"));return new n({name:s,version:i,subpath:o})}}static fromUrl(e){try{let t=new URL(e),r=new URL(At).host,s=new URL(Vr).host;if(t.host===r){let i=Zm(t.pathname.replace(/^\/v\d+\//,"/"));if(!i.length)return;let o=i[0].startsWith("@")?`${i[0]}/${i[1]??""}`:i[0];return n.parse(o)}if(t.host===s){let i=t.pathname.split("/npm/")[1];if(!i)return;let o=i.split("/")[0]||"";return n.parse(o)}return}catch{return}}format(){let e=this.version?`${this.name}@${this.version}`:this.name;return this.subpath?`${e}/${this.subpath}`:e}root(){return this.name}static rootOf(e){return n.parse(e).name}withVersion(e){return new n({name:this.name,version:_n(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},_n=n=>n&&n.length?n:void 0,eg=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),_n(n.slice(e+1))]}});async function ye(n){try{return await n()}catch{return}}var zi=v(()=>{});function zt(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Hc(n){return n.startsWith("./")?n:`./${n}`}var Xr,Wc=v(()=>{Gr();zi();zr();Xr=class{constructor(e,t){this.cache=e,this.http=t,this.pinMs=1e4,this.versionsIndexMs=1440*60*1e3,this.metaTtlMs=10080*60*1e3,this.pinCache=new Map}baseDir(e){let t=typeof e=="string"?new j(e):e;return`${Vr}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(zt(t),this.baseDir(e)).toString()}packageJson(e){return this.file(e,"package.json")}buildEsmUrl(e,t={}){let{target:r="es2022",bundle:s=!1,external:i}=t,o=new URLSearchParams({target:r});return s&&o.append("bundle",""),i?.length&&o.append("external",i.join(",")),`${At}/${e}?${o.toString()}`}async resolveExactVersion(e){let t=Date.now(),r=this.pinCache.get(e);if(r&&t-r.ts<this.pinMs)return r.value;let s=await this.tryResolveFromUrls([this.buildEsmUrl(e),`${At}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await ye(()=>this.http.head(t)),s=this.parseVersionFromUrl(r?.url||t);if(s)return s}}async fetchVersionsIndex(e){if(await this.cache.isNegative(e))return;let t=await this.cache.getIndex(e);if(t&&Date.now()-t.updatedAt<this.versionsIndexMs)return{versions:t.versions,distTags:t.distTags};let r=await ye(()=>this.http.getJson(`${Kc}${encodeURIComponent(e)}`));if(!r?.versions?.length){await this.cache.recordNegative(e);return}await this.cache.clearNegative(e);let s=r.tags&&Object.keys(r.tags).length?r.tags:void 0;return await this.cache.setIndex(e,r.versions,s),{versions:r.versions,distTags:s}}parseVersionFromUrl(e){let t=j.fromUrl(e)?.version;return t&&/\d+\.\d+\.\d+/.test(t)?t:void 0}async fetchPackageMeta(e,t){let r=await this.cache.getMeta(e,t);if(r&&Date.now()-r.updatedAt<this.metaTtlMs){let{dependencies:d,peerDependencies:u,peerDependenciesMeta:f}=r;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new j(`${e}@${t}`)),i=await ye(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),l=o(i.peerDependencies),c=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,l,c),{name:e,version:t,dependencies:a,peerDependencies:l,peerDependenciesMeta:c}}}});var tg,Qr,Yc,sA,Zr,Gi=v(()=>{tg=n=>n.startsWith("@types/"),Qr=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!tg(e)),Yc=n=>Object.keys(n?.dependencies||{}).filter(e=>!tg(e)),sA=n=>Qr(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),Zr=class{constructor(e){this.cdn=e}async resolve(e,t){let r=await this.fetchMeta(e),{allRoots:s,autoAddedPeers:i}=await this.expandWithPeers(r,t),o=this.computeFlags(s);return{allRoots:s,flags:o,autoAddedPeers:i}}async fetchMeta(e){return Promise.all(e.map(async({name:t,version:r})=>({name:t,version:r,meta:await this.cdn.fetchPackageMeta(t,r)})))}async expandWithPeers(e,t){let r=new Map(e.map(i=>[i.name,i])),s=[];for(let i of e)for(let o of sA(i.meta))!r.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),l=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:l})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Qr(i.meta))),r=new Map;for(let i of e)for(let o of Yc(i.meta))r.set(o,(r.get(o)||0)+1);let s=new Set([...r.entries()].filter(([,i])=>i>=2).map(([i])=>i));return new Map(e.map(i=>[i.name,{isPeerRoot:t.has(i.name),hasPeers:Qr(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var es,Vc=v(()=>{Gr();zi();es=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await ye(()=>this.cdn.fetchVersionsIndex(e));if(t?.versions?.length){let r=this.semver.selectBestVersion(t.versions,{distTags:t.distTags});if(r)return r}return this.cdn.resolveExactVersion(e)}async resolveExactForRoot(e,t){if(!t)return this.learnExactVersion(e);let r=await this.cache.getPinnedExact(e,t);if(r){if(this.semver.isExactVersion(r))return r;console.debug("[typebulb] cached version for",e,"is not exact (",r,"); re-resolving from registry")}let s=async o=>{if(o&&this.semver.isExactVersion(o))return await this.cache.setPinnedExact(e,t,o),o},i=await ye(()=>this.cdn.fetchVersionsIndex(e));if(i?.versions?.length){let o=this.semver.selectBestVersion(i.versions,{range:t,distTags:i.distTags});if(o){let a=await s(o);if(a)return a}else{console.debug("[typebulb] refreshing version cache for",e,"(",t,"not in cached set \u2014 likely a new release)"),await this.cache.invalidateVersionsCache(e);let a=await ye(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let l=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(l)return l}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let r=new j(e),s=r.root(),i=t[s],o=i?await ye(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as iA,parse as oA}from"es-module-lexer";var Nn,zc=v(()=>{Gr();zr();Gi();Nn=class n{constructor(e,t,r){this.version=e,this.cdn=t,this.peer=r}extractImportsSync(e){let t=new Set;for(let r of n.importPatterns){r.lastIndex=0;for(let s of e.matchAll(r))j.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,r=s=>{j.isBare(s)&&t.add(s)};try{await iA;let[s]=oA(e);s.forEach(i=>r(e.slice(i.s,i.e).trim()))}catch{return this.extractImportsSync(e)}return Array.from(t)}async buildImportMap(e,t,r){let s=(await this.extractImports(e)).filter(u=>!r?.has(j.rootOf(u))),i=[...new Set(s.map(j.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:l,autoAddedPeers:c}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...c.map(u=>u.name)],a,l);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let r=t[e],s=await this.version.resolveExactForRoot(e,r);if(!s)throw new Error(`Cannot resolve ${r?`${e}@${r}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,r){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let m=s.get(j.rootOf(p));return new j(p).withVersion(m.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==j.rootOf(p)).map(j.rootOf)),l=[],c=new Set,d=new Set(e.filter(p=>p===j.rootOf(p))),u=new Set;for(let p of e){let m=j.rootOf(p),h=s.get(m),{isPeerRoot:b,hasPeers:A,isSharedDep:S}=r.get(m),P=a.has(m),_=p!==m,R=!(b||S)&&(P||!A),$=this.singletonDepsOf(h,o),x=_&&d.has(m);x&&u.add(m);let D=x?[...$,m]:$.length?$:void 0;l.push([p,this.cdn.buildEsmUrl(i(p),{bundle:R,external:D})]),c.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(c.has(p)||l.push([p,this.cdn.buildEsmUrl(i(p),{})]),l.push([`${p}/`,`${At}/${i(p)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Qr(e.meta),...Yc(e.meta)])].filter(r=>t.has(r))}};Nn.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as ng,satisfies as aA,maxSatisfying as rg,major as lA,valid as cA}from"semver";var Xi,Gt,Gc=v(()=>{Xi=class{cmp(e,t){return e===t?0:ng(e,t)?1:ng(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!aA(t,e,{includePrerelease:!0})}selectBestVersion(e,t){if(!e?.length)return;let r=t?.range?.trim()||"*",s=t?.preferStable??!0,i=t?.distTags?.latest;if(i&&e.includes(i)&&this.satisfies(r,i))return i;if(s){let a=rg(e,r,{includePrerelease:!1});if(a)return a}return rg(e,r,{includePrerelease:!0})??void 0}majorOf(e){return lA(e)}isExactVersion(e){return cA(e)!==null}},Gt=new Xi});function uA(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var Xt,sg=v(()=>{zi();Xt=class{constructor(e){this.store=e}async isNegative(e){let t=await ye(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await ye(()=>this.store.get(e)))?.attempts||0)+1;await ye(()=>this.store.set(e,{until:Date.now()+uA(r),attempts:r}))}async clearNegative(e){await ye(()=>this.store.delete(e))}}});function ig(n,e){let t=new Xr(n,e),r=new Zr(t),s=new es(n,t,Gt);return{packageService:new Nn(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var tt=v(()=>{Wc();Gi();Vc();zc();Gc();Gr();Gc();zr();Wc();Gi();Vc();zc();sg()});import*as Xc from"fs/promises";import*as og from"crypto";function De(n){return og.createHash("sha1").update(n).digest("hex")}async function nt(n){try{return JSON.parse(await Xc.readFile(n,"utf8"))}catch{return}}async function Qi(n){try{return await Xc.readFile(n,"utf8")}catch{return}}var In=v(()=>{"use strict"});import*as Ot from"fs/promises";import*as rt from"path";import*as lg from"os";function Z(){return Qc||(Qc=fA().catch(()=>Ze())),Qc}function eo(n,e){return rt.join(dA,De(n),e)}async function fA(){await Ot.mkdir(Tt,{recursive:!0});let n=rt.join(Tt,"version.json");if((await nt(n))?.version===ag)return;let t=await Ot.readdir(Tt).catch(()=>[]);await Promise.all(t.map(r=>Ot.rm(rt.join(Tt,r),{recursive:!0,force:!0}))),await Ot.writeFile(n,JSON.stringify({version:ag})+`
|
|
362
|
+
`,"utf8")}var ag,Tt,ts,ns,Zi,dA,Qc,$n=v(()=>{"use strict";In();Et();ag=1,Tt=rt.join(lg.homedir(),".typebulb","cache"),ts=rt.join(Tt,"packages"),ns=rt.join(Tt,"proxy"),Zi=rt.join(Tt,"dts"),dA=rt.join(Tt,"emit")});import*as Pt from"fs/promises";import*as cg from"path";async function Ae(n,e){let t=`${n}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await Pt.mkdir(cg.dirname(n),{recursive:!0}),await Pt.writeFile(t,e,"utf8")}catch{Ze();return}await Pt.rename(t,n).catch(async()=>{await Pt.rm(t,{force:!0}).catch(()=>{})})}var rs=v(()=>{"use strict";Et()});var Ln,Zc=v(()=>{"use strict";rs();In();Ln=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=nt(this.filePath).then(e=>(this.mem=new Map(Object.entries(e??{})),this.mem))),this.loadPromise)}async get(e){return(await this.load()).get(e)}async set(e,t){let r=await this.load();r.set(e,t),await this.persist(r)}async delete(e){let t=await this.load();t.delete(e)&&await this.persist(t)}async persist(e){await Ae(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as fg from"fs/promises";import*as je from"path";function dg(n,e){return je.join(pA,to(n),encodeURIComponent(e)+".json")}function to(n){return n.replace(/\//g,"__")}var eu,ug,pA,hA,no,pg=v(()=>{"use strict";tt();$n();rs();Zc();In();eu=je.join(ts,"indexes"),ug=je.join(ts,"pinned"),pA=je.join(ts,"meta"),hA=je.join(ts,"negative.json"),no=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new Xt(new Ln(hA));async getPinnedExact(e,t){let r=`${e}@${t}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await Z();let s=await Qi(je.join(ug,De(r)+".txt"));return this.pinnedMem.set(r,s),s}async setPinnedExact(e,t,r){let s=`${e}@${t}`;this.pinnedMem.set(s,r),await Z(),await Ae(je.join(ug,De(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await Z();let t=await nt(je.join(eu,to(e)+".json"));return this.indexMem.set(e,t),t}async setIndex(e,t,r){let s={versions:t,distTags:r,updatedAt:Date.now()};this.indexMem.set(e,s),await Z(),await Ae(je.join(eu,to(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await fg.rm(je.join(eu,to(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await Z(),this.negativeCache.isNegative(e)}async recordNegative(e){await Z(),await this.negativeCache.recordNegative(e)}async clearNegative(e){await this.negativeCache.clearNegative(e)}async getMeta(e,t){let r=`${e}@${t}`;if(this.metaMem.has(r))return this.metaMem.get(r);await Z();let s=await nt(dg(e,t));return this.metaMem.set(r,s),s}async setMeta(e,t,r,s,i){let o={dependencies:r,peerDependencies:s,peerDependenciesMeta:i,updatedAt:Date.now()};this.metaMem.set(`${e}@${t}`,o),await Z(),await Ae(dg(e,t),JSON.stringify(o))}}});var hg,mg=v(()=>{"use strict";hg={async getJson(n){try{let e=await fetch(n,{redirect:"follow"});return e.ok?await e.json():void 0}catch{return}},async head(n){try{let e=await fetch(n,{method:"HEAD",redirect:"follow"});return{ok:e.ok,url:e.url}}catch{return}}}});var mA,ro,gg,yg,d$,tu=v(()=>{"use strict";tt();pg();mg();mA=new no,{packageService:ro,versionResolver:gg,cdnClient:yg,peerResolver:d$}=ig(mA,hg)});function so(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function io(n,e){return` <script>
|
|
363
363
|
(function() {
|
|
364
364
|
try {
|
|
365
365
|
var KEY = ${Ct(JSON.stringify("tb-theme:"+n))};
|
|
@@ -385,7 +385,17 @@ ${rA(t)}`)}var Qm=v(()=>{Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="h
|
|
|
385
385
|
apply(effective());
|
|
386
386
|
var onOsChange = function() { if (!stored() && !FORCED) apply(os()); };
|
|
387
387
|
mq.addEventListener ? mq.addEventListener('change', onOsChange) : mq.addListener(onOsChange);
|
|
388
|
-
window.__tbTheme = { get: stored, set: set, effective: effective };
|
|
388
|
+
window.__tbTheme = { get: stored, set: set, apply: apply, effective: effective };
|
|
389
|
+
/* The host pushes its theme when it flips (render.ts): a framed bulb's baseline is stamped
|
|
390
|
+
into its srcdoc at creation, so it would otherwise hold the theme it was born in. The
|
|
391
|
+
host owns the baseline, the bulb owns its override. */
|
|
392
|
+
if (window.parent !== window) {
|
|
393
|
+
window.addEventListener('message', function(e) {
|
|
394
|
+
if (e.source !== window.parent) return;
|
|
395
|
+
var d = e.data;
|
|
396
|
+
if (d && d.__typebulbEmbed === true && d.kind === 'theme' && (d.theme === 'dark' || d.theme === 'light')) apply(d.theme);
|
|
397
|
+
});
|
|
398
|
+
}
|
|
389
399
|
window.addEventListener('keydown', function(e) {
|
|
390
400
|
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.code === 'KeyL') {
|
|
391
401
|
e.preventDefault();
|
|
@@ -394,7 +404,7 @@ ${rA(t)}`)}var Qm=v(()=>{Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="h
|
|
|
394
404
|
});
|
|
395
405
|
} catch (e) {}
|
|
396
406
|
})();
|
|
397
|
-
</script>`}var Ct,oo,ao=v(()=>{ne();Ct=n=>n.replace(/<\/script/gi,"<\\/script");oo=`
|
|
407
|
+
</script>`}var Ct,oo,ao=v(()=>{"use strict";ne();Ct=n=>n.replace(/<\/script/gi,"<\\/script");oo=`
|
|
398
408
|
const es = new EventSource('/__reload');
|
|
399
409
|
let bootId = null;
|
|
400
410
|
let firstErrorAt = 0;
|
|
@@ -411,7 +421,7 @@ ${rA(t)}`)}var Qm=v(()=>{Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="h
|
|
|
411
421
|
es.onerror = () => {
|
|
412
422
|
if (!firstErrorAt) firstErrorAt = Date.now();
|
|
413
423
|
if (Date.now() - firstErrorAt > RETRY_WINDOW_MS) es.close();
|
|
414
|
-
};`});var bg,wg=v(()=>{ao();ne();bg=`
|
|
424
|
+
};`});var bg,wg=v(()=>{"use strict";ao();ne();bg=`
|
|
415
425
|
(() => {
|
|
416
426
|
// Inline (bulb-in-a-bulb): runs inside a sandboxed iframe with no parent
|
|
417
427
|
// bridge, so privileged tb.* (AI, fs, server RPC) can't reach a host and would
|
|
@@ -1191,6 +1201,23 @@ ${rA(t)}`)}var Qm=v(()=>{Vi()});var At,Vr,Kc,zr=v(()=>{At="https://esm.sh",Vr="h
|
|
|
1191
1201
|
});
|
|
1192
1202
|
};
|
|
1193
1203
|
|
|
1204
|
+
// tb:theme (Specs/Theme.md) \u2014 flip the page's theme so an agent can read the other render back
|
|
1205
|
+
// with tb:png / tb:snapshot. TRANSIENT by design, and the one place the durable rule is wrong:
|
|
1206
|
+
// it calls apply(), never set(), so it never writes the per-bulb localStorage key and a reload
|
|
1207
|
+
// restores whatever the user was looking at. The reply says so, because a probe with a visible
|
|
1208
|
+
// after-effect has to state it.
|
|
1209
|
+
const actTheme = (rest) => {
|
|
1210
|
+
const m = /^\\s*(dark|light)?\\s*$/.exec(rest);
|
|
1211
|
+
if (!m) throw new Error('usage: tb:theme [dark|light] (bare clears the probe)');
|
|
1212
|
+
const engine = window.__tbTheme;
|
|
1213
|
+
if (!engine || !engine.apply) throw new Error('this page has no theme engine');
|
|
1214
|
+
const resting = engine.effective();
|
|
1215
|
+
const want = m[1] || resting;
|
|
1216
|
+
engine.apply(want);
|
|
1217
|
+
return postFrameSnapshot().then((s) =>
|
|
1218
|
+
'theme: ' + want + ' \u2014 transient, not saved (a reload restores ' + resting + ')\\n' + s);
|
|
1219
|
+
};
|
|
1220
|
+
|
|
1194
1221
|
// Events channel (dev server only): 'reload' drives hot reload (only emitted when watching),
|
|
1195
1222
|
// 'message' delivers \`typebulb send\` pushes to tb.onMessage. Connect for a CLI-served page (http
|
|
1196
1223
|
// origin, not an inline bulb); a srcdoc inline bulb or a file:// static export has no server, so onMessage just
|
|
@@ -1225,7 +1252,8 @@ ${oo}
|
|
|
1225
1252
|
if (p === 'tb:set' || p.indexOf('tb:set ') === 0) return actSet(p.slice(7));
|
|
1226
1253
|
if (p === 'tb:rect' || p.indexOf('tb:rect ') === 0) return readRect(p.slice(8));
|
|
1227
1254
|
if (p === 'tb:png' || p.indexOf('tb:png ') === 0) return readPng(p.slice(7));
|
|
1228
|
-
|
|
1255
|
+
if (p === 'tb:theme' || p.indexOf('tb:theme ') === 0) return actTheme(p.slice(9));
|
|
1256
|
+
throw new Error('unknown reserved message: ' + p + ' (known: tb:snapshot, tb:rect, tb:png, tb:click, tb:set, tb:theme)');
|
|
1229
1257
|
};
|
|
1230
1258
|
const value = parseMsg(env.payload);
|
|
1231
1259
|
const calls = typeof env.payload === 'string' && env.payload.indexOf('tb:') === 0
|
|
@@ -1280,7 +1308,7 @@ ${yA(t,u)}
|
|
|
1280
1308
|
</script>`}function bA(n,e){if(!n)return"";let t=e.split(`
|
|
1281
1309
|
`).length,r={version:3,file:n.file,sources:[`/__source/${n.file}`],names:[],mappings:["AAAA",...Array(Math.max(0,t-1)).fill("AACA")].join(";")};return`
|
|
1282
1310
|
//# sourceURL=${n.file.replace(/\s/g,"%20")}
|
|
1283
|
-
//# sourceMappingURL=data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(r))}`}function vA(n){let e={};for(let[t,r]of Object.entries(n))e[t]=r.startsWith("https://")?"/proxy/"+r:r;return e}var gA,wA,Sg=v(()=>{wg();ao();gA=["globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */","await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */"];wA=`<script>
|
|
1311
|
+
//# sourceMappingURL=data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(r))}`}function vA(n){let e={};for(let[t,r]of Object.entries(n))e[t]=r.startsWith("https://")?"/proxy/"+r:r;return e}var gA,wA,Sg=v(()=>{"use strict";wg();ao();gA=["globalThis.__tbEntryRan = true; /* import graph resolved \u2014 the load-failure backstop's signal (imports hoist above this line) */","await globalThis.__tbBoot; /* #tb= fragment restore, set by the shim when present (TB-Inference.md) */"];wA=`<script>
|
|
1284
1312
|
(function () {
|
|
1285
1313
|
var framed = window.parent !== window;
|
|
1286
1314
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1380,16 +1408,16 @@ ${yA(t,u)}
|
|
|
1380
1408
|
});
|
|
1381
1409
|
})();
|
|
1382
1410
|
</script>`});import*as co from"fs/promises";import*as lo from"path";import{existsSync as kg,readFileSync as SA}from"fs";import{execFile as kA}from"child_process";import{promisify as xA}from"util";import{builtinModules as EA}from"node:module";import{satisfies as AA}from"semver";async function uo(n,e,t,r){let i=n.map(c=>CA(c,t)).filter(c=>!RA(c,e));if(i.length===0)return;let o=i.filter(c=>!PA.test(c));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1383
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await co.mkdir(e,{recursive:!0});let a=lo.join(e,"package.json");kg(a)||await co.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let l=["--no-audit","--no-fund",...r?.ignoreScripts?["--ignore-scripts"]:[]];await TA("npm",["install",...l,...i],{cwd:e,shell:!0})}function CA(n,e){if(!e||j.parse(n).version)return n;let t=e[n];return t?`${n}@${t}`:n}function RA(n,e){let{name:t,version:r}=j.parse(n),s=lo.join(e,"node_modules",t);if(!kg(s))return!1;if(!r)return!0;try{let i=JSON.parse(SA(lo.join(s,"package.json"),"utf-8")).version;return AA(i,r)}catch{return!1}}function fo(n){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,r;for(;r=t.exec(n);){let s=r[1];if(s.includes(":"))continue;let i=j.rootOf(s);OA.has(i)||e.add(i)}return[...e]}var TA,OA,PA,nu=v(()=>{tt();TA=xA(kA),OA=new Set(EA),PA=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var xg,Eg=v(()=>{xg=n=>n!=null&&n>=0&&n<=
|
|
1411
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await co.mkdir(e,{recursive:!0});let a=lo.join(e,"package.json");kg(a)||await co.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let l=["--no-audit","--no-fund",...r?.ignoreScripts?["--ignore-scripts"]:[]];await TA("npm",["install",...l,...i],{cwd:e,shell:!0})}function CA(n,e){if(!e||j.parse(n).version)return n;let t=e[n];return t?`${n}@${t}`:n}function RA(n,e){let{name:t,version:r}=j.parse(n),s=lo.join(e,"node_modules",t);if(!kg(s))return!1;if(!r)return!0;try{let i=JSON.parse(SA(lo.join(s,"package.json"),"utf-8")).version;return AA(i,r)}catch{return!1}}function fo(n){let e=new Set,t=/\bimport\s+(?:[\s\S]*?\s+from\s+)?['"]([^./][^'"]*)['"]/g,r;for(;r=t.exec(n);){let s=r[1];if(s.includes(":"))continue;let i=j.rootOf(s);OA.has(i)||e.add(i)}return[...e]}var TA,OA,PA,nu=v(()=>{"use strict";tt();TA=xA(kA),OA=new Set(EA),PA=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var xg,Eg=v(()=>{xg=n=>n!=null&&n>=0&&n<=4?n:void 0});var ve,Fe,Mn=v(()=>{ve=class extends Error{constructor(e,t="unknown",r=!1){super(e),this.code=t,this.retryable=r}},Fe=class{getPath(e,t){return this.path}parseError(e,t){return this.parseJsonError(e,t)}parseStreamChunk(e){return this.checkAndThrowError(e),this.parseProviderStreamChunk(e)}extractSystemMessages(e,t=`
|
|
1384
1412
|
|
|
1385
|
-
`){let r=e.filter(s=>s.role==="system").map(s=>s.content);return{system:r.length?r.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let r=JSON.parse(e);return r.error&&typeof r.error=="object"?{message:r.error.message||`HTTP ${t}`,type:r.error.type}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let r=t.code||"unknown";throw new ve(t.message,r,!!t.retryable)}if(t.error){let r=t.error,s=typeof r=="object"&&r!==null?String(r.type??r.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new ve(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}}});var po,ru=v(()=>{Mn();po=class extends Fe{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,r,s){let i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};if(r?.webSearch
|
|
1413
|
+
`){let r=e.filter(s=>s.role==="system").map(s=>s.content);return{system:r.length?r.join(t):void 0,conversationMessages:e.filter(s=>s.role!=="system")}}parseJsonError(e,t){if(!e)return{message:`HTTP ${t}`};try{let r=JSON.parse(e);return r.error&&typeof r.error=="object"?{message:r.error.message||`HTTP ${t}`,type:r.error.type}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}checkAndThrowError(e){if(typeof e!="object"||e===null)return;let t=e;if(t.type==="error"&&"message"in t){let r=t.code||"unknown";throw new ve(t.message,r,!!t.retryable)}if(t.error){let r=t.error,s=typeof r=="object"&&r!==null?String(r.type??r.code??""):"",i=/rate_limit|too_many_requests/i.test(s),o=/overloaded|server_error|unavailable/i.test(s),a=/context_length/i.test(s);throw new ve(this.extractErrorMessage(t.error),i?"rate_limit":a?"context_exceeded":"unknown",i||o)}}extractErrorMessage(e){if(typeof e=="string")try{let t=JSON.parse(e);return t.error?.message||t.message||e}catch{return e}return typeof e=="object"&&e!==null?e.message||JSON.stringify(e):`${this.providerName} returned an error`}}});var po,ru=v(()=>{Mn();po=class extends Fe{constructor(){super(...arguments),this.providerName="OpenAI",this.defaultBaseUrl="https://api.openai.com",this.path="/v1/responses",this.effortMap={0:"none",1:"low",2:"medium",3:"high",4:"xhigh"}}buildHeaders(e){return{Authorization:`Bearer ${e}`,"Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,r,s){let i=this.convertMessagesToInput(e),o={model:t,input:i,stream:s};if(r?.webSearch===!0&&(o.tools=[{type:"web_search"}]),r?.effort!==void 0){let a=this.effortMap[r.effort];o.reasoning=a==="none"?{effort:a}:{effort:a,summary:"auto"}}return r?.maxOutputTokens!==void 0&&(o.max_output_tokens=r.maxOutputTokens),o}parseNonStreamingResponse(e){if(!this.isResponsesApiResponse(e))return{text:""};let t=e.output_text||"",r;if(e.output&&Array.isArray(e.output))for(let s of e.output)s.type==="reasoning"&&s.summary&&(r=s.summary.map(i=>i.text).join(`
|
|
1386
1414
|
`)),!t&&s.type==="message"&&s.content&&(t=s.content.filter(i=>i.type==="output_text").map(i=>i.text).join(""));return{text:t,reasoning:r}}parseProviderStreamChunk(e){if(!this.isResponsesApiEvent(e))return null;switch(e.type){case"response.failed":{let r=e.response?.error,s=r?.message||"Response failed",i=r?.code==="insufficient_quota"||r?.code==="rate_limit_exceeded";throw new ve(s,i?"rate_limit":"unknown",i)}case"response.output_text.delta":return{text:e.delta};case"response.reasoning_summary_text.delta":return{reasoning:e.delta};default:return null}}convertMessagesToInput(e){return e.map(t=>t.role==="system"?`System: ${t.content}`:t.role==="user"?`User: ${t.content}`:t.role==="assistant"?`Assistant: ${t.content}`:t.content).join(`
|
|
1387
1415
|
|
|
1388
|
-
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var Bn,ho=v(()=>{Mn();Bn=class extends Fe{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,r=t.choices[0],s=r?.message,i=s?.content??r?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let r=t.delta||t.message;if(!r)return null;let s=r.content||void 0,i=r.reasoning||r.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var mo,su=v(()=>{ho();mo=class extends Bn{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high"}}buildHeaders(e,t){let r={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(r["HTTP-Referer"]=t,r.Referer=t,r.Origin=t),r}buildPayload(e,t,r,s){let i={model:t,messages:e,stream:s};r?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=r?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),i}}});var go,iu=v(()=>{Mn();go=class extends Fe{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,r,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e),a={model:t,max_tokens:this.getMaxTokens(t),messages:this.withTailMessagesCached(o),stream:s};r?.webSearch
|
|
1416
|
+
`)}isResponsesApiEvent(e){return typeof e=="object"&&e!==null&&"type"in e&&typeof e.type=="string"}isResponsesApiResponse(e){return typeof e=="object"&&e!==null&&e.object==="response"}}});var Bn,ho=v(()=>{Mn();Bn=class extends Fe{parseNonStreamingResponse(e){if(!this.hasChoices(e))return{text:""};let t=e,r=t.choices[0],s=r?.message,i=s?.content??r?.text??"",o=s?.reasoning??s?.reasoning_content??t.reasoning;return{text:i,reasoning:o}}parseProviderStreamChunk(e){if(!this.hasChoices(e))return null;let t=e.choices[0];if(!t)return null;let r=t.delta||t.message;if(!r)return null;let s=r.content||void 0,i=r.reasoning||r.reasoning_content||void 0;return!s&&!i?null:{text:s,reasoning:i}}hasChoices(e){return typeof e=="object"&&e!==null&&"choices"in e&&Array.isArray(e.choices)}}});var mo,su=v(()=>{ho();mo=class extends Bn{constructor(){super(...arguments),this.providerName="OpenRouter",this.defaultBaseUrl="https://openrouter.ai",this.path="/api/v1/chat/completions",this.effortMap={0:"none",1:"low",2:"medium",3:"high",4:"xhigh"}}buildHeaders(e,t){let r={Authorization:`Bearer ${e}`,"x-api-key":e,"Content-Type":"application/json",Accept:"application/json","X-Title":"Typebulb"};return t&&(r["HTTP-Referer"]=t,r.Referer=t,r.Origin=t),r}buildPayload(e,t,r,s){let i={model:t,messages:e,stream:s};r?.webSearch===!0&&(i.plugins=[{id:"web"}]);let o=r?.effort;return o!==void 0&&(i.reasoning={effort:this.effortMap[o]}),r?.maxOutputTokens!==void 0&&(i.max_tokens=r.maxOutputTokens),i}}});var go,iu=v(()=>{Mn();go=class extends Fe{constructor(){super(...arguments),this.providerName="Anthropic",this.defaultBaseUrl="https://api.anthropic.com",this.path="/v1/messages"}buildHeaders(e){return{"x-api-key":e,"anthropic-version":"2023-06-01","Content-Type":"application/json",Accept:"application/json"}}buildPayload(e,t,r,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e),a={model:t,max_tokens:Math.min(this.getMaxTokens(t),r?.maxOutputTokens??1/0),messages:this.withTailMessagesCached(o),stream:s};r?.webSearch===!0&&(a.tools=[{type:"web_search_20250305",name:"web_search"}]),i&&(a.system=[{type:"text",text:i,cache_control:{type:"ephemeral"}}]);let l=r?.effort;if(l!==void 0){if(this.isModernModel(t))if(l===0)this.alwaysThinks(t)||(a.thinking={type:"disabled"}),a.output_config={effort:"low"};else{let c={1:"low",2:"medium",3:"high",4:"max"};a.thinking={type:"adaptive",display:"summarized"},a.output_config={effort:c[l]}}else if(l!==0){let c={1:2048,2:4096,3:8192,4:16384};a.thinking={type:"enabled",budget_tokens:c[l]}}}return a}parseNonStreamingResponse(e){if(!this.isAnthropicResponse(e))return{text:""};let t=e.content.filter(s=>s.type==="text").map(s=>s.text).join(""),r=e.content.filter(s=>s.type==="thinking").map(s=>s.thinking).join(`
|
|
1389
1417
|
|
|
1390
|
-
`);return{text:t,reasoning:r||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withTailMessagesCached(e){let t=Math.max(0,e.length-2);return e.map((r,s)=>s>=t?{role:r.role,content:[{type:"text",text:r.content,cache_control:{type:"ephemeral"}}]}:r)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let r=+t[1],s=t[2]?+t[2]:0;return r>4||r===4&&s>=6}alwaysThinks(e){return/^claude-(fable|mythos)\b/i.test(e)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var yo,ou=v(()=>{Mn();yo=class extends Fe{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1}}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,r,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
1391
|
-
`),l={contents:o.map(d=>({role:d.role==="assistant"?"model":"user",parts:[{text:d.content}]}))};r?.webSearch
|
|
1392
|
-
`)[0],type:s.status,code:s.code?.toString()}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",r=e.candidates?.[0]?.finishReason,s="complete";return r==="MAX_TOKENS"?s="interrupted":(r==="SAFETY"||r==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let r=["minimal","low","medium","high"][t];return r==="minimal"&&e<3.5?"low":r}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let r="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:r+=i.text);return{text:r||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ve(`Prompt blocked: ${t}`)}}}});var bo,au=v(()=>{ho();bo=class extends Bn{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}buildPayload(e,t,r,s){return{model:t,messages:e,stream:s}}}});function Qt(n){let e=_A.get(n);if(!e)throw new Error(`Unsupported protocol: ${n}`);return e}function NA(n,e){return n.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function lu(n,e){let t=Qt(n.protocol),r=t.getPath(n.model,e.stream),s=NA(n.baseUrl,r),i=t.buildHeaders(n.apiKey,e.origin),o=t.buildPayload(e.messages,n.model,{effort:e.effort,webSearch:e.webSearch},e.stream);return
|
|
1418
|
+
`);return{text:t,reasoning:r||void 0}}parseProviderStreamChunk(e){return this.isAnthropicEvent(e)&&e.type==="content_block_delta"?e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:null:null}withTailMessagesCached(e){let t=Math.max(0,e.length-2);return e.map((r,s)=>s>=t?{role:r.role,content:[{type:"text",text:r.content,cache_control:{type:"ephemeral"}}]}:r)}isAnthropicResponse(e){return typeof e=="object"&&e!==null&&e.type==="message"&&Array.isArray(e.content)}isAnthropicEvent(e){return typeof e=="object"&&e!==null&&"type"in e}isModernModel(e){let t=e.match(/^claude-[a-z]+-(\d+)(?:-(\d+))?/i);if(!t)return!1;let r=+t[1],s=t[2]?+t[2]:0;return r>4||r===4&&s>=6}alwaysThinks(e){return/^claude-(fable|mythos)\b/i.test(e)}getMaxTokens(e){return this.isModernModel(e)?64e3:32e3}}});var yo,ou=v(()=>{Mn();yo=class extends Fe{constructor(){super(...arguments),this.providerName="Gemini",this.defaultBaseUrl="https://generativelanguage.googleapis.com",this.path="/v1beta/models",this.budgetMap={0:0,1:1024,2:8192,3:-1,4:-1}}getPath(e,t){return`/v1beta/models/${e}:${t?"streamGenerateContent":"generateContent"}${t?"?alt=sse":""}`}buildHeaders(e){return{"Content-Type":"application/json","x-goog-api-key":e}}buildPayload(e,t,r,s){let{system:i,conversationMessages:o}=this.extractSystemMessages(e,`
|
|
1419
|
+
`),l={contents:o.map(d=>({role:d.role==="assistant"?"model":"user",parts:[{text:d.content}]}))};r?.webSearch===!0&&(l.tools=[{google_search:{}}]),i&&(l.systemInstruction={role:"system",parts:[{text:i}]});let c=r?.effort;if(c!==void 0){let d=this.geminiVersion(t),u=d!==null&&d>=3?{thinkingLevel:this.thinkingLevelFor(d,c)}:{thinkingBudget:this.budgetMap[c]};l.generationConfig={thinkingConfig:c===0?u:{includeThoughts:!0,...u}}}return r?.maxOutputTokens!==void 0&&(l.generationConfig={...l.generationConfig,maxOutputTokens:r.maxOutputTokens}),l}parseError(e,t){if(!e)return{message:`HTTP ${t}`};try{let r=JSON.parse(e),s=Array.isArray(r)?r[0]?.error:r?.error;return s&&typeof s=="object"?{message:(s.message||`HTTP ${t}`).split(`
|
|
1420
|
+
`)[0],type:s.status,code:s.code?.toString()}:r.message?{message:r.message}:{message:e}}catch{return{message:e}}}parseNonStreamingResponse(e){if(this.checkAndThrowError(e),this.checkGeminiError(e),!this.isGeminiResponse(e))return{text:"",status:"failed",error:"Invalid response format"};let t=this.extractParts(e).text||"",r=e.candidates?.[0]?.finishReason,s="complete";return r==="MAX_TOKENS"?s="interrupted":(r==="SAFETY"||r==="RECITATION")&&(s="failed"),{text:t,status:s}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return null;let t=this.extractParts(e);return t.text||t.reasoning?t:null}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):null}thinkingLevelFor(e,t){let r=["minimal","low","medium","high","high"][t];return r==="minimal"&&e<3.5?"low":r}isGeminiResponse(e){return typeof e=="object"&&e!==null&&"candidates"in e&&Array.isArray(e.candidates)}extractParts(e){let t=e.candidates?.[0]?.content?.parts;if(!t)return{};let r="",s="";for(let i of t)i.text&&(i.thought?s+=i.text:r+=i.text);return{text:r||void 0,reasoning:s||void 0}}checkGeminiError(e){if(this.isGeminiResponse(e)&&e.promptFeedback?.blockReason){let t=e.promptFeedback.blockReason;throw new ve(`Prompt blocked: ${t}`)}}}});var bo,au=v(()=>{ho();bo=class extends Bn{constructor(){super(...arguments),this.providerName="Ollama",this.defaultBaseUrl="http://localhost:11434",this.path="/chat/completions"}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"application/json"};return e&&(t.Authorization=`Bearer ${e}`),t}buildPayload(e,t,r,s){return{model:t,messages:e,stream:s}}}});function Qt(n){let e=_A.get(n);if(!e)throw new Error(`Unsupported protocol: ${n}`);return e}function NA(n,e){return n.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function lu(n,e){let t=Qt(n.protocol),r=t.getPath(n.model,e.stream),s=NA(n.baseUrl,r),i=t.buildHeaders(n.apiKey,e.origin),o=t.buildPayload(e.messages,n.model,{effort:e.effort,webSearch:e.webSearch,maxOutputTokens:e.maxOutputTokens},e.stream);return fetch(s,{method:"POST",headers:i,body:JSON.stringify(o),signal:e.signal})}function IA(n){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(n)}async function Dn(n,e){let t=Qt(e),r=await n.text().catch(()=>""),{message:s}=t.parseError(r,n.status),i=n.status,o="unknown";return i===429?o="rate_limit":(i===413||IA(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Ag,_A,cu=v(()=>{ru();su();iu();ou();au();Ag=new bo,_A=new Map([["openai",new po],["openrouter",new mo],["anthropic",new go],["gemini",new yo],["ollama",Ag],["openai-compat",Ag]])});function Tg(n){let e=n.indexOf(`\r
|
|
1393
1421
|
\r
|
|
1394
1422
|
`),t=n.indexOf(`
|
|
1395
1423
|
|
|
@@ -1413,8 +1441,8 @@ ${r}
|
|
|
1413
1441
|
Output only valid JSON. No explanation, no markdown fences, just the JSON object. Every number must be a JSON literal \u2014 never an expression like 2 * pi; write the computed decimal instead.`),t.join(`
|
|
1414
1442
|
|
|
1415
1443
|
`)}function ss(n){try{return JSON.parse(n)}catch{return null}}function jA(n,e){let t="",r=0,s=!1,i=!1;for(let o=0;o<n.length;o++){let a=n[o];if(i){i=!1;continue}if(a==="\\"){i=!0;continue}a==='"'&&(s?(t+=n.slice(r,o+1),r=o+1):(t+=e(n.slice(r,o))+'"',r=o+1),s=!s)}return t+=s?n.slice(r):e(n.slice(r)),t}function FA(n){let e=jA(n,t=>t.replace(/\bpi\b/g,"3.141592653589793").replace(/\be\b/g,"2.718281828459045").replace(/-?\d[\d.\s+\-*/()]*\d|\(-?\d[\d.\s+\-*/()]*\d\)/g,r=>{if(!/[+\-*/]/.test(r.replace(/^-/,""))||r.length>64||!/^[\d\s.+\-*/()]+$/.test(r))return r;try{let s=Function(`"use strict"; return (${r})`)();return typeof s=="number"&&Number.isFinite(s)?String(s):r}catch{return r}}));return e!==n?e:null}function UA(n,e){let t=0,r=!1,s=!1;for(let i=e;i<n.length;i++){let o=n[i];if(s){s=!1;continue}if(o==="\\"){s=!0;continue}if(o==='"'){r=!r;continue}if(!r){if(o==="{"||o==="[")t++;else if((o==="}"||o==="]")&&(t--,t===0))return i}}return-1}function qA(n){let e=null,t=0;for(;t<n.length;){let r=n[t];if(r==="{"||r==="["){let s=UA(n,t);if(s!==-1){let i=n.slice(t,s+1),o=ss(i);o!==null&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function pu(n){let e=[],t=n.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let r=ss(t);if(r!==null)return{parsed:r,json:t,fixesApplied:e};let s=t.match(/```(?:json)?\s*\n([\s\S]*?)\n?```\s*$/);if(s&&(t=s[1].trim(),e.push("preamble before fenced JSON"),r=ss(t),r!==null))return{parsed:r,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),l=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(l>0&&(t=t.slice(l),e.push("preamble text"),r=ss(t),r!==null))return{parsed:r,json:t,fixesApplied:e}}for(let[o,a]of DA){let l=a(t);if(l!==null){let c=ss(l);if(c!==null)return{parsed:c,json:l,fixesApplied:[...e,o]}}}let i=qA(n);return i!==null?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:null,json:t,fixesApplied:e}}function hu(n){try{let e={i:n.insight,d:n.data},t=JSON.stringify(e),r=MA($A(t),{level:9}),s=KA(r),i=`${Cg}:${s}`;return i.length>JA?"":"#"+du+i}catch{return""}}function mu(n){try{let e=n.startsWith("#")?n.slice(1):n;if(!e.startsWith(du))return null;let t=e.slice(du.length),r=t.indexOf(":");if(r===-1||t.slice(0,r)!==Cg)return null;let s=HA(t.slice(r+1)),i=JSON.parse(LA(BA(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?null:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return null}}function KA(n){let e="";for(let t=0;t<n.length;t+=32768)e+=String.fromCharCode(...n.subarray(t,t+32768));return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function HA(n){let e=n.replace(/-/g,"+").replace(/_/g,"/");for(;e.length%4;)e+="=";let t=atob(e),r=new Uint8Array(t.length);for(let s=0;s<t.length;s++)r[s]=t.charCodeAt(s);return r}var DA,du,Cg,JA,Rg=v(()=>{DA=[["orphan quote",n=>{let e=n.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==n?e:null}],["trailing }",n=>n.endsWith("}}")?n.slice(0,-1):null],["trailing ]",n=>n.endsWith("]]")?n.slice(0,-1):null],["trailing },",n=>n.endsWith("},")?n.slice(0,-1):null],["trailing ],",n=>n.endsWith("],")?n.slice(0,-1):null],["trailing comma in object",n=>n.match(/,\s*\}$/)?n.replace(/,\s*\}$/,"}"):null],["trailing comma in array",n=>n.match(/,\s*\]$/)?n.replace(/,\s*\]$/,"]"):null],["arithmetic constants",FA]];du="tb=",Cg="1",JA=6e4});var tn=v(()=>{Eg();Mn();cu();Pg();Rg();ho();iu();ou();ru();su();au()});import{readFileSync as _g,existsSync as WA}from"fs";import*as Ye from"path";function Ng(n){return[...n?[`.env.${n}.local`,`.env.${n}`]:[],".env.local",".env"]}function Te(n,e=process.cwd()){let t={},r=[];for(let s of Ng(n)){let i;try{i=_g(Ye.resolve(e,s),"utf-8")}catch{continue}r.push(s);for(let[o,a]of Ig(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:n,sources:t,loaded:r}}function*Ig(n){for(let e of n.split(`
|
|
1416
|
-
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;let r=t.indexOf("=");if(r===-1)continue;let s=t.slice(0,r).trim(),i=t.slice(r+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function wo(n,e=process.cwd()){for(let t of Ng()){let r;try{r=_g(Ye.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Ig(r))if(s===n)return i}return process.env[n]}function YA(n){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let r;r=t.exec(n);)e.add(r[1]??r[2]);return[...e]}function $g(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}function Rt(n,e,t){let{sources:r,mode:s,loaded:i}=n,o=process.cwd(),a=Ye.dirname(e),l=`(mode: ${s??"none"})`,c=t?YA(t):[],d=c.filter(p=>r[p]).map(p=>`${p} \u2190 ${r[p]}`);d.length?console.log(`env: ${d.join(", ")} ${l}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${l}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Ye.resolve(a)!==Ye.resolve(o);if(u)for(let p of[".env.local",".env"])WA(Ye.join(a,p))&&console.log(`env: ${Ye.join(a,p)} present but not loaded (cwd is ${o})`);let f=c.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}var st=v(()=>{});function Fn(n){return(n.includes("://")?n:`http://${n}`).replace(/\/+$/,"")}function gu(){return os}async function it(){let[n,e]=await Promise.all([Mg(),ZA()]);return QA([...eT(e),...n],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function QA(n,e,t){return!e||!t?n:n.map(r=>r.provider===e&&r.name===t?{...r,default:!0}:r)}async function Lg(){let n;try{n=await fetch(VA,{signal:AbortSignal.timeout(GA)})}catch(e){return os=`catalog fetch failed: ${e?.message??e}`,null}if(!n.ok)return os=`catalog fetch failed: HTTP ${n.status}`,null;try{return await n.json()}catch(e){return os=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function ZA(){if(is&&Date.now()-is.fetchedAt<=zA)return is.models;let n=await Lg()??await Lg();return n?(is={models:n,fetchedAt:Date.now()},os=null,n):is?.models??[]}async function Mg(){if(vo&&Date.now()-vo.fetchedAt<=XA)return vo.models;let n=Fn(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let t=await fetch(new URL("/api/tags",n).toString());t.ok&&(e=((await t.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return vo={models:e,fetchedAt:Date.now()},e}function eT(n){let e=new Set(Object.entries(jn).filter(([,t])=>!!process.env[t]).map(([t])=>t));return n.filter(t=>e.has(t.provider))}function yu(){return Object.values(jn).some(n=>!!process.env[n])}async function So(){return yu()||process.env.TB_AI_BASE_URL||(await Mg()).length>0?"own":"none"}function Bg(n,e,t){let r=Math.max(...n.map(o=>o.name.length)),s=Math.max(...n.map(o=>o.friendlyName.length)),i=["Models available to tb.ai (filtered by your .env keys):",""];for(let o of n)i.push(` ${o.name.padEnd(r)} ${o.friendlyName.padEnd(s)} (${o.provider})`);return i.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&i.push(`Default (from .env): ${e} / ${t}`),i.join(`
|
|
1417
|
-
`)}var jn,VA,zA,GA,XA,is,vo,os,nn=v(()=>{jn={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};VA="https://api.typebulb.com/api/models",zA=1440*60*1e3,GA=5e3,XA=60*1e3,is=null,vo=null,os=null});function ot(n,e){let t=n??process.env.TB_AI_PROVIDER,r=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!r)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=Qt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Fn(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:r,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:r,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=jn[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:r,isFreeModel:!1}:`No API key for '${t}'. Set ${i} \u2014 ${$g()}.`}function _t(n,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return lu(n,{messages:t,stream:!0,effort:xg(e.effort),webSearch:e.webSearch??!0,signal:e.signal})}var ko=v(()=>{tn();tn();st();nn()});import*as Un from"fs/promises";import*as at from"path";function xo(n,e,t=e){let r=at.resolve(e,n),s=at.normalize(t),i=at.normalize(r);if(i!==s&&!i.startsWith(s+at.sep))throw new Error("Path traversal detected - access denied");return r}async function as(n,e,t){return Un.readFile(xo(n,e,t))}async function Eo(n,e,t,r){let s=xo(n,t,r);await Un.mkdir(at.dirname(s),{recursive:!0}),await Un.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var bu=v(()=>{});async function Dg(n){let e=ot(n.provider,n.model);if(typeof e=="string")throw new Error(e);let t=await _t(e,n);if(!t.ok){let r=await Dn(t,e.protocol);throw new Error(r.message)}return{response:t,protocol:e.protocol}}async function tT(n){let{response:e,protocol:t}=await Dg(n);return{text:await Zt(e,t)}}async function*nT(n){let{response:e,protocol:t}=await Dg(n);yield*en(e,t)}function jg(n,e=process.cwd()){let t=Object.assign(tT,{stream:nT}),r={read:async s=>{let i=await as(s,n,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await as(s,n,e)),write:async(s,i)=>(await Eo(s,i,n,e),!0)};globalThis.tb=Object.freeze({log:(...s)=>{console.log(...s)},ai:t,fs:r,dir:n,models:()=>it(),aiAccess:So,mode:Tn.local})}var Fg=v(()=>{tn();ne();ko();nn();bu()});import*as Ue from"fs/promises";import*as ie from"path";import{pathToFileURL as rT}from"url";async function Ug(n){let t=(await Ue.readdir(n)).find(r=>r.endsWith(".bulb.md"));return t?ie.join(n,t):null}function Nt(n,e){let t=ie.resolve(n),r=ie.join(ie.dirname(t),ie.basename(t).replace(/\.bulb\.md$/,""));return e?ie.join(r,"batches",e):r}async function qn(n,e){let t=Nt(n,e);await Ue.mkdir(t,{recursive:!0});let r=new Date;await Ue.utimes(t,r,r).catch(()=>{})}function Jn(n){let[e,t,r,s]=n.split(ie.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!r||!s?.endsWith(".bulb.md")))return{userSlug:r,slug:s.slice(0,-8)}}async function qe(n){let e=await Ue.readFile(n,"utf-8"),t=ue(e);if(!t)throw new Error("Invalid .bulb.md file format");let r=Rn(t);return{bulb:r,config:ir(r.config),warnings:Qd(e),starts:t.starts}}function wu(n){let e=ie.basename(n).replace(/\.bulb\.md$/i,"");return ie.join(ie.dirname(n),".typebulb",`${e}.server.mjs`)}async function ls(n,e,t,r,s){let i=qc(n,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await Yd(o,t));let a=ie.join(ie.dirname(e),".typebulb");await Ue.mkdir(a,{recursive:!0});let l=fo(o);l.length>0&&await uo(l,a,r);let c=wu(e);return await Ue.writeFile(c,o,"utf-8"),jg(Nt(e,s)),await import(`${rT(c).href}?t=${Date.now()}`)}async function vu(n,e,t,r,s){let{bulb:i,config:o,starts:a}=await qe(n),l=Ni(i.data);Xm(i.code,o.dependencies??{});let c=qc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:d}=await ro.buildImportMap(c.code,o.dependencies??{},r?new Set([r.name]):void 0);r&&(d.imports[r.name]=r.entryUrl);let u=vg({name:i.name,code:c.code,css:i.css,html:i.html,data:l,insight:i.insight,importMap:d,dir:Nt(n,s),watch:e,source:{file:ie.basename(n),codeLine:a.get("code.tsx")??1},compileError:c.error?String(c.error):void 0}),f=null;return i.server&&t&&(f=await ls(i.server,n,r,o.dependencies,s)),{html:u,bulb:i,serverExports:f}}var It,Ve=v(()=>{Wr();Wm();Qm();tu();Sg();nu();Rs();Fg();It=(n,e)=>ie.join(Nt(n,e),"assets")});import{readdirSync as qg,readFileSync as sT,statSync as Jg}from"fs";import{join as Ao,basename as iT}from"path";function Kg(n,e,t){if(e>8)return t;let r;try{r=qg(n,{withFileTypes:!0})}catch{return t}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Kg(Ao(n,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Ao(n,s.name));return t}function Su(n){let e=Ao(Nt(n),"batches"),t;try{t=qg(e,{withFileTypes:!0})}catch{return[]}return t.filter(r=>r.isDirectory()).map(r=>{let s=0;try{s=Jg(Ao(e,r.name)).mtimeMs}catch{}return{name:r.name,mtime:s}}).sort((r,s)=>s.mtime-r.mtime).map(r=>r.name)}function To(n){return Kg(n,0,[]).map(e=>{let t=0;try{t=Jg(e).mtimeMs}catch{}let r,s=!1;try{let i=sT(e,"utf8");r=Yi(i.slice(0,1024));let o=ue(i);s=!!o&&Wi(Rn(o))}catch{}return{path:e,name:r??iT(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Hg=v(()=>{ne();Wr();Uc();Ve()});import*as Vg from"net";import{mkdir as oT,readFile as aT,writeFile as zg}from"fs/promises";import{existsSync as lT}from"fs";import{join as Gg}from"path";function Zg(){return Gg(xt(),"blocks")}function ku(n){return Gg(Zg(),`${n}.json`)}function Po(n){return new Promise(e=>{let t=Vg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function dT(n){for(let e=n;e<65535;e++)if(await Po(e))return e;throw new Error(`No free port found above ${n}`)}async function xu(n){let e=(await Q()).find(r=>r.port===n),t=e?` (pid ${e.pid}, ${e.agent?`agent:${e.agent}`:e.file})`:"";console.error(`port ${n} in use${t}`),process.exit(1)}async function Co(n){try{let e=JSON.parse(await aT(ku(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Ro(n,e){try{return await zg(ku(n),JSON.stringify(e,null,2)),!0}catch{return Ze(),!1}}async function fT(n){let e=X(n);try{await oT(Zg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Qg;o++)t.push(Xg+o*rn);let r=await Promise.all(t.map(async o=>({base:o,block:await Co(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 zg(ku(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await Co(o))?.cwd===e)return o;l.code!=="EEXIST"&&Ze();continue}if(!lT(a.cwd))return await Ro(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Wg(o.block)-Wg(a.block))[0];if(i)return await Ro(i.base,s)?i.base:void 0}function Wg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function pT(n,e){let t=await Co(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Yg(t),a=o.has(0)?uT:0;for(;a>Oo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Ro(n,t),a}let r=X(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Yg(t);for(s=Oo;s<rn&&i.has(s);)s++;if(s>=rn){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:Oo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Ro(n,t),s}function Yg(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function hT(n,e){let t=await fT(e);return t===void 0?void 0:t+await pT(t,n)}async function cs(n){let e=X(n);for(let t=0;t<Qg;t++){let r=await Co(Xg+t*rn);if(r?.cwd===e)return s=>r.slots[X(s)]?.usedAt??0}return()=>0}async function _o(n){if(n.explicit!==void 0)return await Po(n.explicit)||await xu(n.explicit),{port:n.explicit};let e=await hT(n.target,n.cwd);if(e!==void 0){let r=e-e%rn;for(let s=0;s<4;s++){if(await Po(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=Oo;s<rn;s++){let i=r+s;if(i!==e&&await Po(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await dT(cT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Xg,rn,Qg,cT,Oo,uT,Kn=v(()=>{Et();Be();Xg=20100,rn=100,Qg=19,cT=23e3,Oo=1,uT=rn-1});function Hn(n){if(n.server.trim())return"server-side code (server.ts)";let e=n.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||n.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var No=v(()=>{});import{readFile as mT}from"fs/promises";async function Eu(n){try{let e=ue(await mT(n,"utf-8"));return e?Hn(Rn(e)):void 0}catch{return}}var ey=v(()=>{Wr();No()});function Au(n){let e=ue(n);if(!e)return n;let t=e.files.get("code.tsx");if(!t)return n;let r=Gm(t);if(!r.length)return n;let s=e.files.get("config.json"),i={};if(s)try{let c=JSON.parse(s);c&&typeof c=="object"&&(i=c)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=r.filter(c=>!(c in o));if(!a.length)return n;for(let c of a)o[c]="latest";i.dependencies=o;let l={name:e.frontmatter.name};for(let[c,d]of e.files){let u=Vd(c);u&&(l[u]=d)}return l.config=JSON.stringify(i,null,2),nf(l)}var ty=v(()=>{ne();Vi()});import{spawn as ny}from"child_process";import{basename as gT}from"path";function yT(){return process.env.TYPEBULB_EDITOR||"code"}function wT(n,e,t){return t==null?[e]:bT.test(gT(n))?["-g",`${e}:${t}`]:[`+${t}`,e]}function vT(n,e){let t=yT();return{command:t,args:wT(t,n,e)}}function Tu(n,e){let{command:t,args:r}=vT(n,e),s=process.platform==="win32"?ny("cmd.exe",["/d","/s","/c",t,...r],{detached:!0,stdio:"ignore",windowsHide:!0}):ny(t,r,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var bT,ry=v(()=>{bT=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as ST,writeFileSync as kT,mkdirSync as xT}from"fs";import{join as ET}from"path";function Ou(){return ET(xt(),"trust.json")}function Pu(){try{let n=JSON.parse(ST(Ou(),"utf8"));return new Set(Array.isArray(n)?n:[])}catch{return new Set}}function AT(n){try{xT(xt(),{recursive:!0}),kT(Ou(),JSON.stringify([...n]))}catch(e){throw new Error(`can't write ${Ou()} \u2014 trust not remembered (unwritable home; sandboxed shell?): ${e.message}`)}}function sn(n){return Pu().has(X(n))}function Wn(n,e){let t=Pu(),r=X(n);(e?t.has(r):!t.has(r))||(e?t.add(r):t.delete(r),AT(t))}function Cu(){return[...Pu()]}var us=v(()=>{Et()});import{readFileSync as fM,existsSync as TT}from"fs";import*as Yn from"path";import{fileURLToPath as OT}from"url";function PT(){let n=Yn.dirname(OT(import.meta.url));for(;!TT(Yn.join(n,"package.json"));){let e=Yn.dirname(n);if(e===n)break;n=e}return n}function ds(){return Yn.join(PT(),"SKILL.md")}var Ru=v(()=>{});import*as Se from"fs/promises";import*as Oe from"path";import{createHash as CT}from"crypto";async function Nu(n,e,t){let r=[...n],s=async()=>{for(let i=r.shift();i!==void 0;i=r.shift())await t(i)};await Promise.all(Array.from({length:Math.min(e,n.length)},s))}function Vn(n){try{return JSON.parse(n).error||n}catch{return n}}async function $u(n,e){try{let t=await fetch(fs(n),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});return t.ok?t.headers.get("content-type")?.includes("json")?{entries:await t.json()}:{error:"manifest response is not JSON \u2014 wrong origin?"}:{error:`manifest request failed (${t.status}): ${Vn(await t.text())}`}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}function Lu(n,e){Te(e);let t=process.env.TYPEBULB_ORIGIN||RT;try{return Lo(n,process.cwd(),t)}catch(r){console.error(r instanceof Error?r.message:String(r)),process.exit(1)}}function Lo(n,e,t){if(/^https?:\/\//i.test(n)){let i=new URL(n),o=i.pathname.split("/").filter(Boolean).map(decodeURIComponent),a=o[0]==="api"&&o[1]==="scripts"?o.slice(2):o;if(a[0]!=="u"||!a[1]||!a[2])throw new Error(`Not a bulb URL: ${n}
|
|
1444
|
+
`)){let t=e.trim();if(!t||t.startsWith("#"))continue;let r=t.indexOf("=");if(r===-1)continue;let s=t.slice(0,r).trim(),i=t.slice(r+1).trim();(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1)),yield[s,i]}}function wo(n,e=process.cwd()){for(let t of Ng()){let r;try{r=_g(Ye.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of Ig(r))if(s===n)return i}return process.env[n]}function YA(n){let e=new Set,t=/process\.env\.([A-Za-z_$][\w$]*)|process\.env\[\s*['"]([^'"]+)['"]\s*\]/g;for(let r;r=t.exec(n);)e.add(r[1]??r[2]);return[...e]}function $g(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}function Rt(n,e,t){let{sources:r,mode:s,loaded:i}=n,o=process.cwd(),a=Ye.dirname(e),l=`(mode: ${s??"none"})`,c=t?YA(t):[],d=c.filter(p=>r[p]).map(p=>`${p} \u2190 ${r[p]}`);d.length?console.log(`env: ${d.join(", ")} ${l}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${l}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=Ye.resolve(a)!==Ye.resolve(o);if(u)for(let p of[".env.local",".env"])WA(Ye.join(a,p))&&console.log(`env: ${Ye.join(a,p)} present but not loaded (cwd is ${o})`);let f=c.filter(p=>process.env[p]===void 0);if(f.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${f.join(", ")} but ${f.length>1?"they are":"it's"} unset${p}`)}}var st=v(()=>{"use strict"});function Fn(n){return(n.includes("://")?n:`http://${n}`).replace(/\/+$/,"")}function gu(){return os}async function it(){let[n,e]=await Promise.all([Mg(),ZA()]);return QA([...eT(e),...n],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function QA(n,e,t){return!e||!t?n:n.map(r=>r.provider===e&&r.name===t?{...r,default:!0}:r)}async function Lg(){let n;try{n=await fetch(VA,{signal:AbortSignal.timeout(GA)})}catch(e){return os=`catalog fetch failed: ${e?.message??e}`,null}if(!n.ok)return os=`catalog fetch failed: HTTP ${n.status}`,null;try{return await n.json()}catch(e){return os=`catalog returned an unreadable body: ${e?.message??e}`,null}}async function ZA(){if(is&&Date.now()-is.fetchedAt<=zA)return is.models;let n=await Lg()??await Lg();return n?(is={models:n,fetchedAt:Date.now()},os=null,n):is?.models??[]}async function Mg(){if(vo&&Date.now()-vo.fetchedAt<=XA)return vo.models;let n=Fn(process.env.OLLAMA_HOST??"http://localhost:11434"),e=[];try{let t=await fetch(new URL("/api/tags",n).toString());t.ok&&(e=((await t.json()).models??[]).map(s=>s.name).filter(s=>!!s).map(s=>({provider:"ollama",name:s,friendlyName:s,providerName:"Ollama"})))}catch{}return vo={models:e,fetchedAt:Date.now()},e}function eT(n){let e=new Set(Object.entries(jn).filter(([,t])=>!!process.env[t]).map(([t])=>t));return n.filter(t=>e.has(t.provider))}function yu(){return Object.values(jn).some(n=>!!process.env[n])}async function So(){return yu()||process.env.TB_AI_BASE_URL||(await Mg()).length>0?"own":"none"}function Bg(n,e,t){let r=Math.max(...n.map(o=>o.name.length)),s=Math.max(...n.map(o=>o.friendlyName.length)),i=["Models available to tb.ai (filtered by your .env keys):",""];for(let o of n)i.push(` ${o.name.padEnd(r)} ${o.friendlyName.padEnd(s)} (${o.provider})`);return i.push("","Pass an id as the `model` in tb.ai({ provider, model })."),e&&t&&i.push(`Default (from .env): ${e} / ${t}`),i.join(`
|
|
1445
|
+
`)}var jn,VA,zA,GA,XA,is,vo,os,nn=v(()=>{"use strict";jn={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};VA="https://api.typebulb.com/api/models",zA=1440*60*1e3,GA=5e3,XA=60*1e3,is=null,vo=null,os=null});function ot(n,e){let t=n??process.env.TB_AI_PROVIDER,r=e??process.env.TB_AI_MODEL;if(!t)return"No provider specified. Set TB_AI_PROVIDER in your .env file or pass provider in the tb.ai() call.";if(!r)return"No model specified. Set TB_AI_MODEL in your .env file or pass model in the tb.ai() call.";let s;try{s=Qt(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${Fn(process.env.OLLAMA_HOST??s.defaultBaseUrl)}/v1`,protocol:t,model:r,isFreeModel:!1};if(t==="openai-compat"){let a=process.env.TB_AI_BASE_URL;return a?{apiKey:process.env.TB_AI_API_KEY??"",baseUrl:a,protocol:t,model:r,isFreeModel:!1}:"No base URL for openai-compat. Set TB_AI_BASE_URL (the OpenAI-style base ending in /v1, e.g. http://localhost:1234/v1) in your .env file."}let i=jn[t];if(!i)return`Unknown provider '${t}'.`;let o=process.env[i];return o?{apiKey:o,baseUrl:s.defaultBaseUrl,protocol:t,model:r,isFreeModel:!1}:`No API key for '${t}'. Set ${i} \u2014 ${$g()}.`}function _t(n,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return lu(n,{messages:t,stream:!0,effort:xg(e.effort),webSearch:e.webSearch,signal:e.signal})}var ko=v(()=>{"use strict";tn();tn();st();nn()});import*as Un from"fs/promises";import*as at from"path";function xo(n,e,t=e){let r=at.resolve(e,n),s=at.normalize(t),i=at.normalize(r);if(i!==s&&!i.startsWith(s+at.sep))throw new Error("Path traversal detected - access denied");return r}async function as(n,e,t){return Un.readFile(xo(n,e,t))}async function Eo(n,e,t,r){let s=xo(n,t,r);await Un.mkdir(at.dirname(s),{recursive:!0}),await Un.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var bu=v(()=>{"use strict"});async function Dg(n){let e=ot(n.provider,n.model);if(typeof e=="string")throw new Error(e);let t=await _t(e,n);if(!t.ok){let r=await Dn(t,e.protocol);throw new Error(r.message)}return{response:t,protocol:e.protocol}}async function tT(n){let{response:e,protocol:t}=await Dg(n);return{text:await Zt(e,t)}}async function*nT(n){let{response:e,protocol:t}=await Dg(n);yield*en(e,t)}function jg(n,e=process.cwd()){let t=Object.assign(tT,{stream:nT}),r={read:async s=>{let i=await as(s,n,e);try{return new TextDecoder("utf-8",{fatal:!0}).decode(i)}catch{throw new Error(`File is not valid UTF-8 text: ${s} \u2014 use tb.fs.readBytes() for binary files.`)}},readBytes:async s=>new Uint8Array(await as(s,n,e)),write:async(s,i)=>(await Eo(s,i,n,e),!0)};globalThis.tb=Object.freeze({log:(...s)=>{console.log(...s)},ai:t,fs:r,dir:n,models:()=>it(),aiAccess:So,mode:Tn.local})}var Fg=v(()=>{"use strict";tn();ne();ko();nn();bu()});import*as Ue from"fs/promises";import*as ie from"path";import{pathToFileURL as rT}from"url";async function Ug(n){let t=(await Ue.readdir(n)).find(r=>r.endsWith(".bulb.md"));return t?ie.join(n,t):null}function Nt(n,e){let t=ie.resolve(n),r=ie.join(ie.dirname(t),ie.basename(t).replace(/\.bulb\.md$/,""));return e?ie.join(r,"batches",e):r}async function qn(n,e){let t=Nt(n,e);await Ue.mkdir(t,{recursive:!0});let r=new Date;await Ue.utimes(t,r,r).catch(()=>{})}function Jn(n){let[e,t,r,s]=n.split(ie.sep).slice(-4);if(!(e!=="typebulbs"||t!=="u"||!r||!s?.endsWith(".bulb.md")))return{userSlug:r,slug:s.slice(0,-8)}}async function qe(n){let e=await Ue.readFile(n,"utf-8"),t=ue(e);if(!t)throw new Error("Invalid .bulb.md file format");let r=Rn(t);return{bulb:r,config:ir(r.config),warnings:Qd(e),starts:t.starts}}function wu(n){let e=ie.basename(n).replace(/\.bulb\.md$/i,"");return ie.join(ie.dirname(n),".typebulb",`${e}.server.mjs`)}async function ls(n,e,t,r,s){let i=qc(n,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await Yd(o,t));let a=ie.join(ie.dirname(e),".typebulb");await Ue.mkdir(a,{recursive:!0});let l=fo(o);l.length>0&&await uo(l,a,r);let c=wu(e);return await Ue.writeFile(c,o,"utf-8"),jg(Nt(e,s)),await import(`${rT(c).href}?t=${Date.now()}`)}async function vu(n,e,t,r,s){let{bulb:i,config:o,starts:a}=await qe(n),l=Ni(i.data);Xm(i.code,o.dependencies??{});let c=qc(i.code,{jsxImportSource:o.ts?.jsxImportSource});c.error&&console.error("Compilation error:",c.error);let{importMap:d}=await ro.buildImportMap(c.code,o.dependencies??{},r?new Set([r.name]):void 0);r&&(d.imports[r.name]=r.entryUrl);let u=vg({name:i.name,code:c.code,css:i.css,html:i.html,data:l,insight:i.insight,importMap:d,dir:Nt(n,s),watch:e,source:{file:ie.basename(n),codeLine:a.get("code.tsx")??1},compileError:c.error?String(c.error):void 0}),f=null;return i.server&&t&&(f=await ls(i.server,n,r,o.dependencies,s)),{html:u,bulb:i,serverExports:f}}var It,Ve=v(()=>{"use strict";Wr();Wm();Qm();tu();Sg();nu();Rs();Fg();It=(n,e)=>ie.join(Nt(n,e),"assets")});import{readdirSync as qg,readFileSync as sT,statSync as Jg}from"fs";import{join as Ao,basename as iT}from"path";function Kg(n,e,t){if(e>8)return t;let r;try{r=qg(n,{withFileTypes:!0})}catch{return t}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;Kg(Ao(n,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Ao(n,s.name));return t}function Su(n){let e=Ao(Nt(n),"batches"),t;try{t=qg(e,{withFileTypes:!0})}catch{return[]}return t.filter(r=>r.isDirectory()).map(r=>{let s=0;try{s=Jg(Ao(e,r.name)).mtimeMs}catch{}return{name:r.name,mtime:s}}).sort((r,s)=>s.mtime-r.mtime).map(r=>r.name)}function To(n){return Kg(n,0,[]).map(e=>{let t=0;try{t=Jg(e).mtimeMs}catch{}let r,s=!1;try{let i=sT(e,"utf8");r=Yi(i.slice(0,1024));let o=ue(i);s=!!o&&Wi(Rn(o))}catch{}return{path:e,name:r??iT(e).replace(/\.bulb\.md$/,""),mtime:t,serverOnly:s}})}var Hg=v(()=>{"use strict";ne();Wr();Uc();Ve()});import*as Vg from"net";import{mkdir as oT,readFile as aT,writeFile as zg}from"fs/promises";import{existsSync as lT}from"fs";import{join as Gg}from"path";function Zg(){return Gg(xt(),"blocks")}function ku(n){return Gg(Zg(),`${n}.json`)}function Po(n){return new Promise(e=>{let t=Vg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function dT(n){for(let e=n;e<65535;e++)if(await Po(e))return e;throw new Error(`No free port found above ${n}`)}async function xu(n){let e=(await Q()).find(r=>r.port===n),t=e?` (pid ${e.pid}, ${e.agent?`agent:${e.agent}`:e.file})`:"";console.error(`port ${n} in use${t}`),process.exit(1)}async function Co(n){try{let e=JSON.parse(await aT(ku(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Ro(n,e){try{return await zg(ku(n),JSON.stringify(e,null,2)),!0}catch{return Ze(),!1}}async function fT(n){let e=X(n);try{await oT(Zg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Qg;o++)t.push(Xg+o*rn);let r=await Promise.all(t.map(async o=>({base:o,block:await Co(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 zg(ku(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await Co(o))?.cwd===e)return o;l.code!=="EEXIST"&&Ze();continue}if(!lT(a.cwd))return await Ro(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Wg(o.block)-Wg(a.block))[0];if(i)return await Ro(i.base,s)?i.base:void 0}function Wg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function pT(n,e){let t=await Co(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Yg(t),a=o.has(0)?uT:0;for(;a>Oo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Ro(n,t),a}let r=X(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Yg(t);for(s=Oo;s<rn&&i.has(s);)s++;if(s>=rn){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:Oo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Ro(n,t),s}function Yg(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function hT(n,e){let t=await fT(e);return t===void 0?void 0:t+await pT(t,n)}async function cs(n){let e=X(n);for(let t=0;t<Qg;t++){let r=await Co(Xg+t*rn);if(r?.cwd===e)return s=>r.slots[X(s)]?.usedAt??0}return()=>0}async function _o(n){if(n.explicit!==void 0)return await Po(n.explicit)||await xu(n.explicit),{port:n.explicit};let e=await hT(n.target,n.cwd);if(e!==void 0){let r=e-e%rn;for(let s=0;s<4;s++){if(await Po(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=Oo;s<rn;s++){let i=r+s;if(i!==e&&await Po(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await dT(cT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Xg,rn,Qg,cT,Oo,uT,Kn=v(()=>{"use strict";Et();Be();Xg=20100,rn=100,Qg=19,cT=23e3,Oo=1,uT=rn-1});function Hn(n){if(n.server.trim())return"server-side code (server.ts)";let e=n.code;if(/\btb\s*\.\s*fs\b/.test(e)||e.includes("/__fs"))return"the filesystem";if(/\btb\s*\.\s*ai\b/.test(e)||e.includes("/__ai")||n.infer.trim()||/\btb\s*\.\s*infer\b/.test(e))return"AI (your API keys)";if(/\btb\s*\.\s*server\s*\.\s*\w/.test(e)||e.includes("/__api"))return"server-side code (server.ts)"}var No=v(()=>{"use strict"});import{readFile as mT}from"fs/promises";async function Eu(n){try{let e=ue(await mT(n,"utf-8"));return e?Hn(Rn(e)):void 0}catch{return}}var ey=v(()=>{"use strict";Wr();No()});function Au(n){let e=ue(n);if(!e)return n;let t=e.files.get("code.tsx");if(!t)return n;let r=Gm(t);if(!r.length)return n;let s=e.files.get("config.json"),i={};if(s)try{let c=JSON.parse(s);c&&typeof c=="object"&&(i=c)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=r.filter(c=>!(c in o));if(!a.length)return n;for(let c of a)o[c]="latest";i.dependencies=o;let l={name:e.frontmatter.name};for(let[c,d]of e.files){let u=Vd(c);u&&(l[u]=d)}return l.config=JSON.stringify(i,null,2),nf(l)}var ty=v(()=>{"use strict";ne();Vi()});import{spawn as ny}from"child_process";import{basename as gT}from"path";function yT(){return process.env.TYPEBULB_EDITOR||"code"}function wT(n,e,t){return t==null?[e]:bT.test(gT(n))?["-g",`${e}:${t}`]:[`+${t}`,e]}function vT(n,e){let t=yT();return{command:t,args:wT(t,n,e)}}function Tu(n,e){let{command:t,args:r}=vT(n,e),s=process.platform==="win32"?ny("cmd.exe",["/d","/s","/c",t,...r],{detached:!0,stdio:"ignore",windowsHide:!0}):ny(t,r,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var bT,ry=v(()=>{"use strict";bT=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as ST,writeFileSync as kT,mkdirSync as xT}from"fs";import{join as ET}from"path";function Ou(){return ET(xt(),"trust.json")}function Pu(){try{let n=JSON.parse(ST(Ou(),"utf8"));return new Set(Array.isArray(n)?n:[])}catch{return new Set}}function AT(n){try{xT(xt(),{recursive:!0}),kT(Ou(),JSON.stringify([...n]))}catch(e){throw new Error(`can't write ${Ou()} \u2014 trust not remembered (unwritable home; sandboxed shell?): ${e.message}`)}}function sn(n){return Pu().has(X(n))}function Wn(n,e){let t=Pu(),r=X(n);(e?t.has(r):!t.has(r))||(e?t.add(r):t.delete(r),AT(t))}function Cu(){return[...Pu()]}var us=v(()=>{"use strict";Et()});import{readFileSync as fM,existsSync as TT}from"fs";import*as Yn from"path";import{fileURLToPath as OT}from"url";function PT(){let n=Yn.dirname(OT(import.meta.url));for(;!TT(Yn.join(n,"package.json"));){let e=Yn.dirname(n);if(e===n)break;n=e}return n}function ds(){return Yn.join(PT(),"SKILL.md")}var Ru=v(()=>{"use strict"});import*as Se from"fs/promises";import*as Oe from"path";import{createHash as CT}from"crypto";async function Nu(n,e,t){let r=[...n],s=async()=>{for(let i=r.shift();i!==void 0;i=r.shift())await t(i)};await Promise.all(Array.from({length:Math.min(e,n.length)},s))}function Vn(n){try{return JSON.parse(n).error||n}catch{return n}}async function $u(n,e){try{let t=await fetch(fs(n),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});return t.ok?t.headers.get("content-type")?.includes("json")?{entries:await t.json()}:{error:"manifest response is not JSON \u2014 wrong origin?"}:{error:`manifest request failed (${t.status}): ${Vn(await t.text())}`}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}function Lu(n,e){Te(e);let t=process.env.TYPEBULB_ORIGIN||RT;try{return Lo(n,process.cwd(),t)}catch(r){console.error(r instanceof Error?r.message:String(r)),process.exit(1)}}function Lo(n,e,t){if(/^https?:\/\//i.test(n)){let i=new URL(n),o=i.pathname.split("/").filter(Boolean).map(decodeURIComponent),a=o[0]==="api"&&o[1]==="scripts"?o.slice(2):o;if(a[0]!=="u"||!a[1]||!a[2])throw new Error(`Not a bulb URL: ${n}
|
|
1418
1446
|
Expected <origin>/u/<user>/<slug>`);let l=a[1],c=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:i.origin,userSlug:l,slug:c,dest:Oe.join(e,Io(l,c))}}let r=Oe.resolve(e,n),s=Jn(r);if(!s)throw new Error(`Not a conventional bulb path: ${n}
|
|
1419
1447
|
A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.bulb.md \u2014 the path is its remote identity.`);return{origin:t,...s,dest:r}}async function _T(n,e){let t=await $u(n,e);if("error"in t||!t.entries.length)return{kind:"none"};let r=t.entries,s=It(n.dest),i=[],o=[],a=0;for(let l of r){let c=await Se.readFile(Oe.join(s,...l.path.split("/"))).catch(()=>{});c===void 0?i.push(l.path):Iu(c)===l.md5?a++:e.force?i.push(l.path):o.push(l.path)}return o.length?{kind:"conflict",paths:o}:{kind:"plan",toGet:i,unchanged:a}}async function NT(n,e,t){let r=It(n.dest),s=[],i=0;return await Nu(e.toGet,4,async o=>{try{let a=await fetch(`${fs(n)}/${$o(o)}`,{headers:t.token?{Authorization:`Bearer ${t.token}`}:{},signal:AbortSignal.timeout(t.timeoutMs??3e4)});if(!a.ok){s.push(`${o}: HTTP ${a.status}`);return}let l=Oe.join(r,...o.split("/"));await Se.mkdir(Oe.dirname(l),{recursive:!0}),await Se.writeFile(l,new Uint8Array(await a.arrayBuffer())),i++}catch(a){s.push(`${o}: ${a instanceof Error?a.message:String(a)}`)}}),{downloaded:i,unchanged:e.unchanged,errors:s}}async function Mo(n,e={}){let t=await fetch(_u(n),{headers:e.token?{Authorization:`Bearer ${e.token}`}:{},signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0});if(!t.ok)return{kind:"http-error",status:t.status};let r=t.headers.get("content-type");if(!r?.includes("text/markdown"))return{kind:"not-markdown",contentType:r};let s=await t.text(),i;try{i=await Se.readFile(n.dest,"utf-8")}catch{}let o=i!==void 0&&IT(i,s);if(i!==void 0&&!o&&!e.force){let{mtime:c}=await Se.stat(n.dest);return{kind:"conflict",dest:n.dest,localMtime:c,remoteLastModified:t.headers.get("last-modified")}}let a=await _T(n,e);if(a.kind==="conflict")return{kind:"asset-conflict",dest:n.dest,paths:a.paths};if(!o){await Se.mkdir(Oe.dirname(n.dest),{recursive:!0}),await Se.writeFile(n.dest,s);let c=new Date(t.headers.get("last-modified")??"");isNaN(c.getTime())||await Se.utimes(n.dest,new Date,c)}let l=a.kind==="plan"?await NT(n,a,e):void 0;return o?{kind:"up-to-date",dest:n.dest,assets:l}:{kind:"written",dest:n.dest,created:i===void 0,assets:l}}function IT(n,e){let t=i=>i.replace(/\r\n/g,`
|
|
1420
1448
|
`),r=ue(t(n)),s=ue(t(e));return!r||!s?t(n)===t(e):r.frontmatter.name===s.frontmatter.name&&_e.every(i=>(r.files.get(le[i].path)||"")===(s.files.get(le[i].path)||""))}async function iy(n,e){n||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=Lu(n,e.mode),r=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await Mo(t,{force:e.force,token:process.env.TYPEBULB_TOKEN})}catch(o){console.error(`Could not reach ${t.origin}: ${o instanceof Error?o.message:String(o)}`),process.exitCode=1;return}let i=Oe.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${r} \u2192 ${i}${s.created?"":" (overwritten)"}`),sy(s.assets);return;case"up-to-date":console.log(`up to date: ${i}`),sy(s.assets);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${r}
|
|
@@ -1423,10 +1451,10 @@ A pull target must be a bulb URL, or a local file at typebulbs/u/<user>/<slug>.b
|
|
|
1423
1451
|
Re-run with --force to overwrite the local file.`),process.exitCode=1;return;case"asset-conflict":console.error(`Refusing to overwrite local assets that differ from the hosted copies:
|
|
1424
1452
|
`+s.paths.map(o=>` assets/${o}`).join(`
|
|
1425
1453
|
`)+`
|
|
1426
|
-
Re-run with --force to overwrite them.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${r}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${r}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}function sy(n){if(!(!n||!n.downloaded&&!n.errors.length)){console.log(`assets: ${n.downloaded} downloaded${n.unchanged?`, ${n.unchanged} unchanged`:""}`);for(let e of n.errors)console.error(` asset failed \u2014 ${e} (a re-pull retries just the missing ones)`);n.errors.length&&(process.exitCode=1)}}var RT,Io,_u,$o,fs,Iu,Bo=v(()=>{st();ne();Ve();RT="https://typebulb.com",Io=(n,e)=>Oe.join("typebulbs","u",n,`${e}.bulb.md`),_u=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}.md`,$o=n=>n.split("/").map(encodeURIComponent).join("/"),fs=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}/assets`;Iu=n=>CT("md5").update(n).digest("hex")});import*as ze from"fs/promises";import*as ps from"path";async function oy(n,e=""){let t=await ze.readdir(n,{withFileTypes:!0}).catch(()=>[]),r=[];for(let s of t)s.isDirectory()?r.push(...await oy(ps.join(n,s.name),`${e}${s.name}/`)):s.isFile()&&r.push(e+s.name);return r}async function $T(n,e){let t=e.timeoutMs??3e4,r=fs(n),s={Authorization:`Bearer ${e.token}`},i=It(n.dest);if(!await ze.stat(i).then(m=>m.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await oy(i),a=await $u(n,{token:e.token,timeoutMs:t});if("error"in a)return{kind:"sync-error",message:a.error};let l=a.entries;if(!o.length&&!l.length)return{kind:"skipped"};let c=new Map(l.map(m=>[m.path,m.md5])),d=new Set(o),u=l.map(m=>m.path).filter(m=>!d.has(m)),f=0,p=0;try{await Nu(o,4,async m=>{let h=await ze.readFile(ps.join(i,...m.split("/")));if(c.get(m)===Iu(h)){p++;return}let b=await fetch(`${r}/${$o(m)}`,{method:"PUT",body:new Uint8Array(h),headers:s,signal:AbortSignal.timeout(t)});if(!b.ok)throw new Error(`upload of '${m}' refused (${b.status}): ${Vn(await b.text())}`);f++})}catch(m){return{kind:"sync-error",message:m instanceof Error?m.message:String(m)}}return{kind:"synced",uploaded:f,unchanged:p,toDelete:u,base:$s(n.userSlug,n.slug)}}async function LT(n,e,t){let r=t.timeoutMs??3e4,s=fs(n),i=[];for(let o of e)try{let a=await fetch(`${s}/${$o(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(r)});if(!a.ok)return{deleted:i,error:`delete of '${o}' refused (${a.status}): ${Vn(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function Do(n,e){let t=await ze.readFile(n.dest,"utf-8"),{mtime:r}=await ze.stat(n.dest),s=await $T(n,{token:e.token,timeoutMs:e.timeoutMs});if(s.kind==="sync-error")return{kind:"asset-error",message:s.message};let i=s.kind==="synced"?{uploaded:s.uploaded,unchanged:s.unchanged,deleted:[],base:s.base}:void 0,o={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(o["If-Unmodified-Since"]=r.toUTCString());let a=await fetch(_u(n),{method:"PUT",body:t,headers:o,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),l=await a.text();if(a.status===409)return{kind:"conflict",message:Vn(l),assets:i};if(!a.ok)return{kind:"http-error",status:a.status,message:Vn(l),assets:i};let c=JSON.parse(l);if(await ze.utimes(n.dest,new Date,new Date(c.updatedAt)),i&&s.kind==="synced"&&s.toDelete.length){let d=await LT(n,s.toDelete,{token:e.token,timeoutMs:e.timeoutMs});i.deleted=d.deleted,d.error&&(i.pruneError=d.error)}return{kind:"pushed",created:c.created,serverStripped:c.serverStripped,updatedAt:c.updatedAt,assets:i}}async function ay(n,e){n||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(n)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Lu(n,e.mode),r=process.env.TYPEBULB_TOKEN;r||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=ps.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Do(t,{token:r,force:e.force})}catch(a){let l=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${l}`),process.exitCode=1;return}switch(o.kind!=="asset-error"&&o.assets&&console.log(`assets: ${o.assets.uploaded} uploaded, ${o.assets.unchanged} unchanged \u2192 ${o.assets.base}`),o.kind){case"asset-error":console.error(`assets sync failed: ${o.message}
|
|
1454
|
+
Re-run with --force to overwrite them.`),process.exitCode=1;return;case"http-error":s.status===404?console.error(`Bulb not found: ${r}`):s.status===401||s.status===403?console.error(`This bulb is private (${s.status}) \u2014 pulling it needs a TYPEBULB_TOKEN for its owner.`):console.error(`Pull failed: ${t.origin} responded ${s.status}`),process.exitCode=1;return;case"not-markdown":console.error(`${r}.md did not return bulb markdown (got ${s.contentType??"no content-type"}) \u2014 is ${t.origin} a typebulb host?`),process.exitCode=1}}function sy(n){if(!(!n||!n.downloaded&&!n.errors.length)){console.log(`assets: ${n.downloaded} downloaded${n.unchanged?`, ${n.unchanged} unchanged`:""}`);for(let e of n.errors)console.error(` asset failed \u2014 ${e} (a re-pull retries just the missing ones)`);n.errors.length&&(process.exitCode=1)}}var RT,Io,_u,$o,fs,Iu,Bo=v(()=>{"use strict";st();ne();Ve();RT="https://typebulb.com",Io=(n,e)=>Oe.join("typebulbs","u",n,`${e}.bulb.md`),_u=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}.md`,$o=n=>n.split("/").map(encodeURIComponent).join("/"),fs=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}/assets`;Iu=n=>CT("md5").update(n).digest("hex")});import*as ze from"fs/promises";import*as ps from"path";async function oy(n,e=""){let t=await ze.readdir(n,{withFileTypes:!0}).catch(()=>[]),r=[];for(let s of t)s.isDirectory()?r.push(...await oy(ps.join(n,s.name),`${e}${s.name}/`)):s.isFile()&&r.push(e+s.name);return r}async function $T(n,e){let t=e.timeoutMs??3e4,r=fs(n),s={Authorization:`Bearer ${e.token}`},i=It(n.dest);if(!await ze.stat(i).then(m=>m.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await oy(i),a=await $u(n,{token:e.token,timeoutMs:t});if("error"in a)return{kind:"sync-error",message:a.error};let l=a.entries;if(!o.length&&!l.length)return{kind:"skipped"};let c=new Map(l.map(m=>[m.path,m.md5])),d=new Set(o),u=l.map(m=>m.path).filter(m=>!d.has(m)),f=0,p=0;try{await Nu(o,4,async m=>{let h=await ze.readFile(ps.join(i,...m.split("/")));if(c.get(m)===Iu(h)){p++;return}let b=await fetch(`${r}/${$o(m)}`,{method:"PUT",body:new Uint8Array(h),headers:s,signal:AbortSignal.timeout(t)});if(!b.ok)throw new Error(`upload of '${m}' refused (${b.status}): ${Vn(await b.text())}`);f++})}catch(m){return{kind:"sync-error",message:m instanceof Error?m.message:String(m)}}return{kind:"synced",uploaded:f,unchanged:p,toDelete:u,base:$s(n.userSlug,n.slug)}}async function LT(n,e,t){let r=t.timeoutMs??3e4,s=fs(n),i=[];for(let o of e)try{let a=await fetch(`${s}/${$o(o)}`,{method:"DELETE",headers:{Authorization:`Bearer ${t.token}`},signal:AbortSignal.timeout(r)});if(!a.ok)return{deleted:i,error:`delete of '${o}' refused (${a.status}): ${Vn(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function Do(n,e){let t=await ze.readFile(n.dest,"utf-8"),{mtime:r}=await ze.stat(n.dest),s=await $T(n,{token:e.token,timeoutMs:e.timeoutMs});if(s.kind==="sync-error")return{kind:"asset-error",message:s.message};let i=s.kind==="synced"?{uploaded:s.uploaded,unchanged:s.unchanged,deleted:[],base:s.base}:void 0,o={Authorization:`Bearer ${e.token}`,"Content-Type":"text/markdown; charset=utf-8"};e.force||(o["If-Unmodified-Since"]=r.toUTCString());let a=await fetch(_u(n),{method:"PUT",body:t,headers:o,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),l=await a.text();if(a.status===409)return{kind:"conflict",message:Vn(l),assets:i};if(!a.ok)return{kind:"http-error",status:a.status,message:Vn(l),assets:i};let c=JSON.parse(l);if(await ze.utimes(n.dest,new Date,new Date(c.updatedAt)),i&&s.kind==="synced"&&s.toDelete.length){let d=await LT(n,s.toDelete,{token:e.token,timeoutMs:e.timeoutMs});i.deleted=d.deleted,d.error&&(i.pruneError=d.error)}return{kind:"pushed",created:c.created,serverStripped:c.serverStripped,updatedAt:c.updatedAt,assets:i}}async function ay(n,e){n||(console.error("Usage: typebulb push <typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1)),/^https?:\/\//i.test(n)&&(console.error("push takes a local .bulb.md file, not a URL (the path is its remote identity)"),process.exit(1));let t=Lu(n,e.mode),r=process.env.TYPEBULB_TOKEN;r||(console.error("push needs TYPEBULB_TOKEN in your .env \u2014 create one on your typebulb.com settings page."),process.exit(1));let s=`${t.origin}/u/${t.userSlug}/${t.slug}`,i=ps.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Do(t,{token:r,force:e.force})}catch(a){let l=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${l}`),process.exitCode=1;return}switch(o.kind!=="asset-error"&&o.assets&&console.log(`assets: ${o.assets.uploaded} uploaded, ${o.assets.unchanged} unchanged \u2192 ${o.assets.base}`),o.kind){case"asset-error":console.error(`assets sync failed: ${o.message}
|
|
1427
1455
|
push refused: the bulb text was not pushed.`),process.exitCode=1;return;case"pushed":{console.log(`pushed ${i} \u2192 ${s}`),o.created&&(console.log(" created a new bulb, unlisted \u2014 nothing existed at this URL before"),console.log(" if you renamed this file, its previous bulb is still live at the old URL")),o.serverStripped&&console.log("note: the server.ts block was stripped on the server copy (CLI-only); your local file is untouched.");for(let a of o.assets?.deleted??[])console.log(` deleted ${a} (no longer in assets/)`);o.assets?.pruneError&&console.log(`note: asset cleanup incomplete \u2014 ${o.assets.pruneError}; the next push will retry.`);return}case"conflict":console.error(`${o.message}
|
|
1428
1456
|
pull to see the remote: typebulb pull ${i}
|
|
1429
|
-
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var Mu=v(()=>{ne();Bo();Ve()});var zn=v(()=>{Be();Hg();Kn();ey();Uc();ty();ry();us();nn();nn();ko();Ru();Bo();Mu();st()});import{existsSync as MT,mkdirSync as BT,rmSync as DT,writeFileSync as jT}from"fs";import{homedir as FT}from"os";import*as Gn from"path";function KT(){return JT.replace('"__TB_SKILL_PATH__"',JSON.stringify(ds()))}function ly(){try{if(!MT(Bu()))return}catch{return}try{let n=UT();BT(Gn.dirname(n),{recursive:!0}),jT(n,KT())}catch{}for(let n of qT())try{DT(n,{force:!0})}catch{}}var Bu,UT,qT,JT,cy=v(()=>{zn();Bu=()=>Gn.join(FT(),".pi","agent"),UT=()=>Gn.join(Bu(),"extensions","typebulb.ts"),qT=()=>["typebulb-wait.ts","matchu-patchu.ts"].map(n=>Gn.join(Bu(),"extensions",n)),JT=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1457
|
+
or overwrite it: typebulb push ${i} --force`),process.exitCode=1;return;case"http-error":o.status===401?console.error("The server rejected TYPEBULB_TOKEN (401) \u2014 it may be revoked; mint a new one on the settings page."):console.error(`Push failed: ${t.origin} responded ${o.status}${o.message?` \u2014 ${o.message}`:""}`),process.exitCode=1}}var Mu=v(()=>{"use strict";ne();Bo();Ve()});var zn=v(()=>{"use strict";Be();Hg();Kn();ey();Uc();ty();ry();us();nn();nn();ko();Ru();Bo();Mu();st()});import{existsSync as MT,mkdirSync as BT,rmSync as DT,writeFileSync as jT}from"fs";import{homedir as FT}from"os";import*as Gn from"path";function KT(){return JT.replace('"__TB_SKILL_PATH__"',JSON.stringify(ds()))}function ly(){try{if(!MT(Bu()))return}catch{return}try{let n=UT();BT(Gn.dirname(n),{recursive:!0}),jT(n,KT())}catch{}for(let n of qT())try{DT(n,{force:!0})}catch{}}var Bu,UT,qT,JT,cy=v(()=>{"use strict";zn();Bu=()=>Gn.join(FT(),".pi","agent"),UT=()=>Gn.join(Bu(),"extensions","typebulb.ts"),qT=()=>["typebulb-wait.ts","matchu-patchu.ts"].map(n=>Gn.join(Bu(),"extensions",n)),JT=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1430
1458
|
import { spawn } from "node:child_process";
|
|
1431
1459
|
import { existsSync } from "node:fs";
|
|
1432
1460
|
|
|
@@ -1571,25 +1599,25 @@ export default function (pi) {
|
|
|
1571
1599
|
try { pi.on("session_shutdown", () => { for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
1572
1600
|
} catch (e) { logErr("load", e && e.message); }
|
|
1573
1601
|
}
|
|
1574
|
-
`});function Y(n){return n?.message??String(n)}var z,$t=v(()=>{z=process.cwd()});import{spawn as uy}from"child_process";import{StringDecoder as HT}from"string_decoder";function ZT(n,e){let t=new HT("utf8"),r="";n.on("data",s=>{r+=typeof s=="string"?s:t.write(s);let i;for(;(i=r.indexOf(`
|
|
1575
|
-
`))>=0;){let o=r.slice(0,i);r=r.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var WT,YT,dy,VT,zT,GT,XT,QT,jo,Fo,fy,py=v(()=>{
|
|
1602
|
+
`});function Y(n){return n?.message??String(n)}var z,$t=v(()=>{"use strict";z=process.cwd()});import{spawn as uy}from"child_process";import{StringDecoder as HT}from"string_decoder";function ZT(n,e){let t=new HT("utf8"),r="";n.on("data",s=>{r+=typeof s=="string"?s:t.write(s);let i;for(;(i=r.indexOf(`
|
|
1603
|
+
`))>=0;){let o=r.slice(0,i);r=r.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var WT,YT,dy,VT,zT,GT,XT,QT,jo,Fo,fy,py=v(()=>{"use strict";$t();WT=3e4,YT=5e3,dy=2e3,VT=2e3,zT=12e4,GT=8e3,XT=15e3,QT=new Set(["get_state","get_commands","get_available_models","set_model","set_thinking_level","cycle_thinking_level","get_session_stats","compact","set_auto_compaction","get_fork_messages","fork","clone","set_session_name","export_html","bash","abort_bash"]),jo=new Set;process.on("exit",()=>{for(let n of jo)try{n.kill()}catch{}});Fo=class{#e;#t=!1;#n=0;#r=!1;#c=null;#h=null;#s=null;#o=null;#u=new Map;#i=[];#m=null;#w=null;#g=null;#d;#f;#y="";#A=1;#a=new Map;#v;#b;constructor(e,t,r=(s,i)=>uy(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#v=new Promise(o=>{this.#b=o}),t?.includes('"')){this.#f="session path contains a quote \u2014 cannot drive it",this.#b();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=r(s,e)}catch(o){this.#f=`could not start pi: ${Y(o)}`,this.#b();return}this.#e=i,this.#d=t,jo.add(i),i.stdout&&ZT(i.stdout,o=>this.#T(o)),i.stderr&&i.stderr.on("data",o=>{this.#y=(this.#y+o.toString()).slice(-VT)}),i.on("error",o=>this.#x(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#x(o?`pi exited (code ${o})${this.#y.trim()?`: ${this.#y.trim()}`:""}`:"pi exited"),jo.delete(i),this.#b()}),this.#l({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#d=a);let l=o.data?.model;l&&typeof l.id=="string"&&l.id&&(this.#g=l.id)}).catch(()=>{}),this.#S()}get streaming(){return this.#t||Date.now()<this.#n}get draft(){return this.#c}get echo(){return this.#h}get queue(){return this.#m}get stats(){return this.#w}get model(){return this.#g}get sessionFile(){return this.#d}get error(){return this.#f}get status(){if(this.#s)return this.#s;if(this.#o){if(Date.now()<this.#o.until)return{text:this.#o.text,kind:this.#o.kind};this.#o=null}return this.#u.size?{text:[...this.#u.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#i.length;){let t=this.#i[0];if(e<t.until)return t.req;this.#i.shift(),t.ownTimeout||this.#k({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#p(e,t)}respondUi(e,t){let r=this.#i.findIndex(o=>o.req.id===e);if(r<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#i.splice(r,1),i={type:"extension_ui_response",id:e};return t.cancelled?i.cancelled=!0:s.req.method==="confirm"?i.confirmed=!!t.confirmed:i.value=t.value??"",this.#k(i),{ok:!0}}async rpc(e){if(!QT.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#l(e);if(t.success&&e.type==="set_model"){let r=t.data?.id;typeof r=="string"&&r&&(this.#g=r)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#l({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#d=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#d}}}return t.success?{ok:!0,data:t.data}:{ok:!1,error:t.error??`pi rejected ${e.type}`}}catch(t){return{ok:!1,error:Y(t)}}}async send(e,t){let r=this.streaming,s=r?e.trimStart().startsWith("/")?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},i;try{i=await this.#l(s)}catch(o){return{ok:!1,error:Y(o)}}return i.success&&!r&&(this.#n=Date.now()+YT),i.success&&!r&&!e.trimStart().startsWith("/")&&(this.#h=e),i.success?{ok:!0}:{ok:!1,error:i.error??"pi rejected the message"}}async stop(){if(this.#e)try{await this.#l({type:"abort"})}catch{}}clearCompletedDraft(){this.#r||(this.#c=null)}clearEcho(){this.#h=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#t){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
1576
1604
|
`)}catch{}await Promise.race([this.#v,fy(dy)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#v,fy(dy)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{uy("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}jo.delete(e),this.#i=[],this.#E("pi was shut down")}}#k(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1577
1605
|
`)}catch{}}#p(e,t){let r=e.length>200?e.slice(0,200)+"\u2026":e;r&&(this.#o={text:r,kind:t,until:Date.now()+(t==="info"?GT:XT)})}#S(){this.#l({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#w={cost:typeof t.cost=="number"?t.cost:0,contextTokens:typeof t.contextUsage?.tokens=="number"?t.contextUsage.tokens:null,contextPercent:typeof t.contextUsage?.percent=="number"?t.contextUsage.percent:null}}).catch(()=>{})}#l(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#f??"pi is not running"));let r=`tb-${this.#A++}`;return new Promise((s,i)=>{let o=setTimeout(()=>{this.#a.delete(r),i(new Error("pi did not respond (30s)"))},WT);o.unref?.(),this.#a.set(r,{resolve:s,timer:o});try{t.stdin.write(JSON.stringify({id:r,...e})+`
|
|
1578
1606
|
`)}catch(a){clearTimeout(o),this.#a.delete(r),i(new Error(Y(a)))}})}#T(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let r=t,s=r.id?this.#a.get(r.id):void 0;s&&(this.#a.delete(r.id),clearTimeout(s.timer),s.resolve(r));return}case"agent_start":this.#t=!0,this.#n=0;return;case"agent_end":this.#t=!1,this.#n=0,this.#r=!1,this.#s=null,this.#m=null,this.#S();return;case"message_start":{t.message?.role==="assistant"&&(this.#r=!0,this.#c={text:"",thinking:""});return}case"message_update":{if(!this.#r)return;let r=t.message,s=Array.isArray(r?.content)?r.content:[],i=s[s.length-1];this.#c={text:s.filter(o=>o?.type==="text").map(o=>o.text??"").join(""),thinking:s.filter(o=>o?.type==="thinking").map(o=>o.thinking??"").join(`
|
|
1579
|
-
`),tool:i?.type==="toolCall"?i.name:void 0};return}case"message_end":this.#r=!1;return;case"auto_retry_start":this.#s={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#s=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#s={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#s=null;let r=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):r?.tokensBefore&&this.#p(`compacted: ~${Math.round(r.tokensBefore/1e3)}k \u2192 ~${Math.round((r.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let r=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#m=r.length||s.length?{steering:r,followUp:s}:null;return}case"extension_ui_request":{let r=String(t.method??"");if(r==="select"||r==="confirm"||r==="input"||r==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#i.push({req:{id:String(t.id??""),method:r,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??zT),ownTimeout:s!==void 0})}else if(r==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(r==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#f=e,this.#t=!1,this.#n=0,this.#r=!1,this.#c=null,this.#h=null,this.#s=null,this.#o=null,this.#u.clear(),this.#i=[],this.#m=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#a)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#a.clear()}},fy=n=>new Promise(e=>{setTimeout(e,n).unref?.()})});import{existsSync as hy,readFileSync as eO,realpathSync as tO}from"fs";import{join as on,dirname as by,resolve as nO}from"path";import{homedir as my}from"os";function sO(n,e){let t=on(n,".pi");if(rO.some(s=>hy(on(t,s))))return!0;let r=on(e,".agents","skills");for(let s=n;;){let i=on(s,".agents","skills");if(i!==r&&hy(i))return!0;let o=by(s);if(o===s)return!1;s=o}}function iO(n,e){for(let t=e;;){if(n[t]===!0||n[t]===!1)return!0;let r=by(t);if(r===t)return!1;t=r}}function wy(n,e){try{let t=e?.agentDir??on(my(),".pi","agent"),r=gy(e?.home??process.env.HOME??my()),s=gy(nO(n));if(!sO(s,r))return null;let i=yy(on(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||iO(yy(on(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var rO,gy,yy,vy=v(()=>{rO=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],gy=n=>{try{return tO(n)}catch{return n}},yy=n=>{try{return JSON.parse(eO(n,"utf8"))}catch{return{}}}});import{statSync as oO,openSync as aO,readSync as lO,closeSync as cO,existsSync as ky}from"fs";import{join as Uo}from"path";import{homedir as Du}from"os";import{execFile as uO}from"child_process";async function fO(n){let e=Uo(Du(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...ky(e)?[e]:[]]){let r=await new Promise(s=>{uO(t,["--base-directory",n,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(r!==null)return r.split(`
|
|
1580
|
-
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function pO(n){return`--${n.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function Sy(n){return n.type==="message"?hO(n.message?.role):n.type==="custom_message"?n.display!==!1:!1}var dO,hO,Xn,ju=v(()=>{Fr();Ec();Bi();cy();py();vy();dO=Uo(Du(),".pi","agent","sessions");hO=n=>n==="user"||n==="assistant"||n==="toolResult"||n==="bashExecution";Xn=class extends St{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return ky(Uo(Du(),".pi","agent"))}ensureHarnessSupport(){ly()}createDriver(e,t){let r=new Fo(e,t),s=wy(e);return s&&r.notice(s,"warning"),r}walkFiles(e){return fO(e)}sessionsDir(e){return Uo(dO,pO(e))}listSessionFiles(e){return Mi(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return Sy(e)}isRecoveryNoise(e){return!1}apply(e,t){let r=[];if(e.type==="custom_message"){if(e.display===!1)return{events:r};let i=this.contentText(e.content).trim();return i&&r.push({type:"user",text:i}),{events:r}}if(e.type!=="message"||!e.message)return{events:r};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&r.push({type:"user",text:i}),{events:r}}if(s.role==="toolResult"){let i=this.contentText(s.content);return r.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:$e(i)}),{events:r}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&r.push({type:"user",text:`$ ${s.command}`}),{events:r};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(f=>f.type==="text").map(f=>f.text??"").join(""),a=i.filter(f=>f.type==="thinking").map(f=>f.thinking??"").join(`
|
|
1607
|
+
`),tool:i?.type==="toolCall"?i.name:void 0};return}case"message_end":this.#r=!1;return;case"auto_retry_start":this.#s={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#s=null,t.success===!1&&this.#p(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#s={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#s=null;let r=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#p(`compaction failed: ${t.errorMessage}`,"error"):r?.tokensBefore&&this.#p(`compacted: ~${Math.round(r.tokensBefore/1e3)}k \u2192 ~${Math.round((r.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#S();return}case"queue_update":{let r=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#m=r.length||s.length?{steering:r,followUp:s}:null;return}case"extension_ui_request":{let r=String(t.method??"");if(r==="select"||r==="confirm"||r==="input"||r==="editor"){let s=typeof t.timeout=="number"&&t.timeout>0?t.timeout:void 0;this.#i.push({req:{id:String(t.id??""),method:r,title:typeof t.title=="string"?t.title:void 0,message:typeof t.message=="string"?t.message:void 0,options:Array.isArray(t.options)?t.options.map(String):void 0,placeholder:typeof t.placeholder=="string"?t.placeholder:void 0,prefill:typeof t.prefill=="string"?t.prefill:void 0},until:Date.now()+(s??zT),ownTimeout:s!==void 0})}else if(r==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#p(String(t.message??""),s),console.log(`[composer] pi extension: ${String(t.message??"")}`)}else if(r==="setStatus"){let s=String(t.statusKey??"");typeof t.statusText=="string"&&t.statusText?this.#u.set(s,t.statusText):this.#u.delete(s)}return}default:return}}#x(e){this.#f=e,this.#t=!1,this.#n=0,this.#r=!1,this.#c=null,this.#h=null,this.#s=null,this.#o=null,this.#u.clear(),this.#i=[],this.#m=null,this.#w=null,this.#g=null,this.#e=void 0,this.#E(e)}#E(e){for(let[,t]of this.#a)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#a.clear()}},fy=n=>new Promise(e=>{setTimeout(e,n).unref?.()})});import{existsSync as hy,readFileSync as eO,realpathSync as tO}from"fs";import{join as on,dirname as by,resolve as nO}from"path";import{homedir as my}from"os";function sO(n,e){let t=on(n,".pi");if(rO.some(s=>hy(on(t,s))))return!0;let r=on(e,".agents","skills");for(let s=n;;){let i=on(s,".agents","skills");if(i!==r&&hy(i))return!0;let o=by(s);if(o===s)return!1;s=o}}function iO(n,e){for(let t=e;;){if(n[t]===!0||n[t]===!1)return!0;let r=by(t);if(r===t)return!1;t=r}}function wy(n,e){try{let t=e?.agentDir??on(my(),".pi","agent"),r=gy(e?.home??process.env.HOME??my()),s=gy(nO(n));if(!sO(s,r))return null;let i=yy(on(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||iO(yy(on(t,"trust.json")),s)?null:"pi has no trust decision for this project \u2014 running untrusted; run `pi` once in a terminal to grant it"}catch{return null}}var rO,gy,yy,vy=v(()=>{"use strict";rO=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],gy=n=>{try{return tO(n)}catch{return n}},yy=n=>{try{return JSON.parse(eO(n,"utf8"))}catch{return{}}}});import{statSync as oO,openSync as aO,readSync as lO,closeSync as cO,existsSync as ky}from"fs";import{join as Uo}from"path";import{homedir as Du}from"os";import{execFile as uO}from"child_process";async function fO(n){let e=Uo(Du(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...ky(e)?[e]:[]]){let r=await new Promise(s=>{uO(t,["--base-directory",n,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(r!==null)return r.split(`
|
|
1608
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function pO(n){return`--${n.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function Sy(n){return n.type==="message"?hO(n.message?.role):n.type==="custom_message"?n.display!==!1:!1}var dO,hO,Xn,ju=v(()=>{"use strict";Fr();Ec();Bi();cy();py();vy();dO=Uo(Du(),".pi","agent","sessions");hO=n=>n==="user"||n==="assistant"||n==="toolResult"||n==="bashExecution";Xn=class extends St{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return ky(Uo(Du(),".pi","agent"))}ensureHarnessSupport(){ly()}createDriver(e,t){let r=new Fo(e,t),s=wy(e);return s&&r.notice(s,"warning"),r}walkFiles(e){return fO(e)}sessionsDir(e){return Uo(dO,pO(e))}listSessionFiles(e){return Mi(this.sessionsDir(e))}parseEntry(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||t.type==="session"||!t.id?null:t}idOf(e){return e.id}parentOf(e){return e.parentId??void 0}timestampOf(e){return e.timestamp}isSidechain(e){return!1}isLeafType(e){return Sy(e)}isRecoveryNoise(e){return!1}apply(e,t){let r=[];if(e.type==="custom_message"){if(e.display===!1)return{events:r};let i=this.contentText(e.content).trim();return i&&r.push({type:"user",text:i}),{events:r}}if(e.type!=="message"||!e.message)return{events:r};let s=e.message;if(s.role==="user"){let i=this.contentText(s.content).trim();return i&&r.push({type:"user",text:i}),{events:r}}if(s.role==="toolResult"){let i=this.contentText(s.content);return r.push({type:"tool_result",id:s.toolCallId??"",content:i,isError:!!s.isError,digest:$e(i)}),{events:r}}if(s.role==="bashExecution")return s.command&&!s.excludeFromContext&&r.push({type:"user",text:`$ ${s.command}`}),{events:r};if(s.role==="assistant"){let i=Array.isArray(s.content)?s.content:[],o=i.filter(f=>f.type==="text").map(f=>f.text??"").join(""),a=i.filter(f=>f.type==="thinking").map(f=>f.thinking??"").join(`
|
|
1581
1609
|
`),l=i.filter(f=>f.type==="toolCall").map(f=>({id:f.id??"",name:f.name??"",input:f.arguments??{}}));if(o||a||l.length){let f=Date.parse(e.timestamp??""),p=!isNaN(f)&&f>=t;r.push({type:"assistant",text:o,thinking:a,tools:l,live:p})}let c=s.usage,d=c?(c.input??0)+(c.output??0)+(c.cacheRead??0)+(c.cacheWrite??0):0,u=c&&d>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:c.input??0,out:c.output??0,cached:c.cacheRead??0,cacheCreate:c.cacheWrite??0}:void 0;return{events:r,usage:u,model:s.model,cost:c?.cost?.total}}return{events:r}}chainWorking(e){let t;for(let a of e)Sy(a)&&(t=a);if(!t||t.type==="custom_message")return!1;let r=t.message.role;if(r==="user"||r==="toolResult"||r==="bashExecution")return!0;if(r!=="assistant")return!1;let i=(Array.isArray(t.message.content)?t.message.content:[]).filter(a=>a.type==="toolCall").map(a=>a.id);if(!i.length)return!1;let o=new Set;for(let a of e)a.type==="message"&&a.message?.role==="toolResult"&&a.message.toolCallId&&o.add(a.message.toolCallId);return i.some(a=>a&&!o.has(a))}sessionAlive(){}readPreview(e){let t;try{t=aO(e,"r")}catch{return""}try{let s=65536;try{s=oO(e).size}catch{}let i=(u,f)=>{let p=Buffer.alloc(f),m=lO(t,p,0,f,u);return p.subarray(0,m).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",l=u=>{let f="";for(let p of u.split(`
|
|
1582
1610
|
`))if(p.includes('"session_info"'))try{let m=JSON.parse(p);m?.type==="session_info"&&typeof m.name=="string"&&m.name&&(f=m.name)}catch{}return f},c="";for(let u of o.split(`
|
|
1583
1611
|
`))if(!(c||!u.includes('"type"')))try{let f=JSON.parse(u);f?.type==="message"&&f.message?.role==="user"&&(c=this.contentText(f.message.content).replace(/\s+/g," ").trim())}catch{}let d=l(a)||l(o)||c;return d?d.slice(0,200):""}finally{cO(t)}}searchText(e){if(e?.type!=="message")return"";let t=e.message?.role;if(t!=="user"&&t!=="assistant")return"";let r=e.message?.content,s="";return typeof r=="string"?s=r:Array.isArray(r)&&(s=r.filter(i=>i.type==="text"&&typeof i.text=="string").map(i=>i.text).join(" ")),s.replace(/\s+/g," ").trim()}contentText(e){return typeof e=="string"?we(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?we(t.text):t?.type==="image"&&t.data?Li(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1584
|
-
`):""}}});var qo,xy=v(()=>{qo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as mO}from"child_process";import{promisify as gO}from"util";import{readFile as yO}from"fs/promises";import{resolve as Ey,sep as bO}from"path";async function Je(n,e){let{stdout:t}=await wO("git",n,{cwd:e,maxBuffer:67108864});return t}async function an(){if(Jo)return Jo;try{Jo=(await Je(["rev-parse","--show-toplevel"],z)).trim()}catch{}return Jo}function vO(n,e){let t=e===" "?n:e;return t==="?"?"U":t}async function Uu(){let n=await an();if(!n)return{repo:!1,root:"",files:[]};try{let e=await Je(["status","--porcelain","-z"],n),t=[],r=e.split("\0");for(let s=0;s<r.length;s++){let i=r[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:vO(i[0],i[1])}))}try{let s=await Je(["diff","--numstat","-z","HEAD"],n),i=new Map,o=s.split("\0");for(let a=0;a<o.length;a++){let l=/^(\d+|-)\t(\d+|-)\t(.*)$/.exec(o[a]);if(!l)continue;let c=l[3]||o[a+=2];c&&i.set(c,{add:+l[1]||0,del:+l[2]||0,binary:l[1]==="-"})}for(let a of t){let l=i.get(a.path);l&&(l.binary?a.binary=!0:(a.add=l.add,a.del=l.del))}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:n,files:t}}catch(e){return{repo:!1,root:"",files:[],error:Y(e)}}}async function qu(n){let e=await an();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Je(["status","--porcelain","-z","--",n],e)).startsWith("??")){let s=Ey(e,n);if(!s.startsWith(Ey(e)+bO))return{ok:!1,error:"outside repository"};let i=await yO(s);return i.includes(0)?Fu("Binary file (not shown)",!1):Fu(i.toString("utf8"),!0)}let r;try{r=await Je(["diff","--no-color","--unified=999999","HEAD","--",n],e)}catch{r=await Je(["diff","--no-color","--unified=999999","--",n],e)}return Fu(r,!1)}catch(t){return{ok:!1,error:Y(t)}}}var wO,Ay,Jo,Fu,hs=v(()=>{
|
|
1612
|
+
`):""}}});var qo,xy=v(()=>{"use strict";qo=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as mO}from"child_process";import{promisify as gO}from"util";import{readFile as yO}from"fs/promises";import{resolve as Ey,sep as bO}from"path";async function Je(n,e){let{stdout:t}=await wO("git",n,{cwd:e,maxBuffer:67108864});return t}async function an(){if(Jo)return Jo;try{Jo=(await Je(["rev-parse","--show-toplevel"],z)).trim()}catch{}return Jo}function vO(n,e){let t=e===" "?n:e;return t==="?"?"U":t}async function Uu(){let n=await an();if(!n)return{repo:!1,root:"",files:[]};try{let e=await Je(["status","--porcelain","-z"],n),t=[],r=e.split("\0");for(let s=0;s<r.length;s++){let i=r[s];i.length<4||((i[0]==="R"||i[0]==="C")&&s++,t.push({path:i.slice(3),status:vO(i[0],i[1])}))}try{let s=await Je(["diff","--numstat","-z","HEAD"],n),i=new Map,o=s.split("\0");for(let a=0;a<o.length;a++){let l=/^(\d+|-)\t(\d+|-)\t(.*)$/.exec(o[a]);if(!l)continue;let c=l[3]||o[a+=2];c&&i.set(c,{add:+l[1]||0,del:+l[2]||0,binary:l[1]==="-"})}for(let a of t){let l=i.get(a.path);l&&(l.binary?a.binary=!0:(a.add=l.add,a.del=l.del))}}catch{}return t.sort((s,i)=>s.path.localeCompare(i.path)),{repo:!0,root:n,files:t}}catch(e){return{repo:!1,root:"",files:[],error:Y(e)}}}async function qu(n){let e=await an();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Je(["status","--porcelain","-z","--",n],e)).startsWith("??")){let s=Ey(e,n);if(!s.startsWith(Ey(e)+bO))return{ok:!1,error:"outside repository"};let i=await yO(s);return i.includes(0)?Fu("Binary file (not shown)",!1):Fu(i.toString("utf8"),!0)}let r;try{r=await Je(["diff","--no-color","--unified=999999","HEAD","--",n],e)}catch{r=await Je(["diff","--no-color","--unified=999999","--",n],e)}return Fu(r,!1)}catch(t){return{ok:!1,error:Y(t)}}}var wO,Ay,Jo,Fu,hs=v(()=>{"use strict";$t();wO=gO(mO),Ay=2e6;Fu=(n,e)=>({ok:!0,text:n.slice(0,Ay),untracked:e,truncated:n.length>Ay})});function Ko(n,e){let t=0,r="";for(let s of n){let i=s.lower.indexOf(e);if(!(i<0)&&(t++,!r)){let o=Math.max(0,i-110),a=Math.min(s.text.length,i+e.length+110);r=(o>0?"\u2026":"")+s.text.slice(o,a)+(a<s.text.length?"\u2026":"")}}return{hitCount:t,snippet:r}}var Ju=v(()=>{"use strict"});var Ho,Wo,Ty=v(()=>{"use strict";Ho=".typebulb/paste",Wo={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp"}});import{existsSync as SO,mkdirSync as kO,writeFileSync as xO,readFileSync as EO}from"fs";import{join as Yo}from"path";function Oy(){let n=new Date,e=t=>String(t).padStart(2,"0");return`${n.getFullYear()}${e(n.getMonth()+1)}${e(n.getDate())}-${e(n.getHours())}${e(n.getMinutes())}${e(n.getSeconds())}`}function PO(n){return n.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function CO(n){let e=AbortSignal.timeout(AO);for(let[t,r]of OO){let s=ot(t,r);if(typeof s!="string"){try{let i=await _t(s,{messages:[{role:"user",content:`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1585
1613
|
|
|
1586
|
-
${n.slice(0,TO)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=PO(await Zt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Py(n,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=Yo(n,Ho);try{kO(t,{recursive:!0})}catch(a){return{ok:!1,error:Y(a)}}let r,s,i;if(e.kind==="image"){if(r=`img-${Oy()}`,s=Object.keys(Wo).find(a=>Wo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else r=await CO(e.data)??`paste-${Oy()}`,s="md",i=e.data;let o=`${r}.${s}`;for(let a=2;SO(Yo(t,o));a++)o=`${r}-${a}.${s}`;try{xO(Yo(t,o),i)}catch(a){return{ok:!1,error:Y(a)}}return{ok:!0,path:`${Ho}/${o}`}}function Cy(n,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),r=Wo[t];if(!r)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:r,base64:EO(Yo(n,Ho,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var AO,TO,OO,Ry=v(()=>{tn();zn();$t();Ty();AO=4e3,TO=4e3,OO=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});function RO(n,...e){return n.slice().sort((t,r)=>{for(let{key:s,desc:i}of e){let o=s(t),a=s(r);if(o!==a)return o==null?i?-1:1:a==null||o<a?i?1:-1:i?-1:1}return 0})}var _y,Ny=v(()=>{_y=(n,e)=>RO(n,{key:e,desc:!0})});import{existsSync as Iy,openSync as _O,readSync as NO,closeSync as IO,statSync as Qn,readdirSync as $y,watchFile as $O,unwatchFile as Ly,mkdirSync as LO,writeFileSync as MO,readFileSync as Vo,unlinkSync as BO,rmSync as DO}from"fs";import{stat as jO}from"fs/promises";import{dirname as FO,join as ln,resolve as My}from"path";function KO(n){if(!Number.isInteger(n))return!0;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function Zn(n){let e={cwd:z,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,r,s=0;function i(){if(e.file){for(let g of t)if(g.file===e.file)return g;return}return r}function o(g){let k={d:n.createDriver(e.cwd,g),file:g,id:`new:${++s}`,startedAt:Date.now()};return t.add(k),e.file||(r=k),k}function a(){let g=[...t].filter(w=>w.file);if(!g.length)return[];let k=new Map(n.listSessionFiles(e.cwd).map(w=>[w.file,w.sessionId]));return g.map(w=>{let T=k.get(w.file);return{rec:w,sessionId:T??w.id,pending:T===void 0}})}let l=()=>a().filter(g=>g.pending&&g.rec.prompt!==void 0);async function c(g){t.delete(g),r===g&&(r=void 0);try{await g.d.dispose()}catch(k){console.error("[composer] dispose:",Y(k))}}function d(){let g=i(),k=new Set(l().map(w=>w.rec));for(let w of[...t])w!==g&&(k.has(w)||w.d.streaming||w.d.queue||w.d.error||c(w))}function u(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(r&&!e.file&&r.file){let g=n.listSessionFiles(e.cwd).find(k=>k.file===r.file);g&&x(g)}r&&!e.file&&r.prompt!==void 0&&e.sessionId!==r.id&&($(void 0,r.id),e.everAttached=!0)}let f=g=>ln(g,qO),p=(g,k)=>ln(f(g),`${k}.lock`);function m(g,k){try{let w=p(g,k);if(Date.now()-Qn(w).mtimeMs>=By)return!1;try{let T=parseInt(Vo(w,"utf8").trim(),10);if(T===process.pid||!KO(T))return!1}catch{}return!0}catch{return!1}}function h(g,k){if(k)try{LO(f(g),{recursive:!0}),MO(p(g,k),String(process.pid))}catch(w){console.error("[lock] claim failed:",Y(w))}}function b(g){try{DO(ln(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function A(g){let k=f(g);if(!Iy(k))return;let w;try{w=$y(k)}catch{return}let T=Date.now();for(let I of w){if(!I.endsWith(".lock"))continue;let B=ln(k,I);try{let F=Qn(B);T-F.mtimeMs>JO&&BO(B)}catch{}}}function S(g){try{return Qn(g),!1}catch(k){return k.code==="ENOENT"}}function P(){let g=e;if(g.file&&!S(g.file)){h(g.cwd,g.sessionId);return}let k=_(g);k&&x(k)}function _(g){if(!g.everAttached)return C(g.cwd)??R(g.cwd,()=>!0)}function C(g){let k=f(g);if(!Iy(k))return;let w;try{w=$y(k)}catch{return}let T;for(let B of w)if(B.endsWith(".lock"))try{let F=Qn(ln(k,B));if(Date.now()-F.mtimeMs>=By||parseInt(Vo(ln(k,B),"utf8").trim(),10)!==process.pid)continue;(!T||F.mtimeMs>T.mtime)&&(T={sessionId:B.slice(0,-5),mtime:F.mtimeMs})}catch{}if(!T)return;let I=n.listSessionFiles(g).find(B=>B.sessionId===T.sessionId);if(!(!I||S(I.file)))return I}function R(g,k){return n.listSessionFiles(g).sort((w,T)=>T.mtime-w.mtime).find(w=>!m(g,w.sessionId)&&k(w))}function $(g,k){let w=e;if(w.file)try{Ly(w.file)}catch{}w.file=g,w.sessionId=k,w.partial="",w.offset=0,w.latest={in:0,out:0,cached:0,cacheCreate:0},w.latestModel=null,w.entries=new Map,w.chainLastId=void 0,w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:k})}function x(g){let k=e;r=void 0,$(g.file,g.sessionId),k.everAttached=!0,h(k.cwd,g.sessionId),K();try{Ly(g.file)}catch{}$O(g.file,{interval:200},()=>K())}function D(){$(void 0,"")}function K(){let g=e;if(!g.file)return;let k;try{k=Qn(g.file).size}catch{return}if(k<=g.offset)return;let w;try{w=_O(g.file,"r")}catch{return}try{let W=k-g.offset,be=Buffer.alloc(W),ae=0;for(;ae<W;){let jd=NO(w,be,ae,W-ae,g.offset+ae);if(!jd)break;ae+=jd}g.offset+=ae,g.partial+=be.subarray(0,ae).toString("utf8")}finally{IO(w)}let T,I;for(;(I=g.partial.indexOf(`
|
|
1614
|
+
${n.slice(0,TO)}`}],effort:0,webSearch:!1,signal:e});if(!i.ok)continue;let o=PO(await Zt(i,s.protocol));if(o)return o}catch{}if(e.aborted)return}}}async function Py(n,e){if(!e||e.kind!=="image"&&e.kind!=="text")return{ok:!1,error:"bad paste kind"};if(typeof e.data!="string"||!e.data)return{ok:!1,error:"empty paste"};let t=Yo(n,Ho);try{kO(t,{recursive:!0})}catch(a){return{ok:!1,error:Y(a)}}let r,s,i;if(e.kind==="image"){if(r=`img-${Oy()}`,s=Object.keys(Wo).find(a=>Wo[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else r=await CO(e.data)??`paste-${Oy()}`,s="md",i=e.data;let o=`${r}.${s}`;for(let a=2;SO(Yo(t,o));a++)o=`${r}-${a}.${s}`;try{xO(Yo(t,o),i)}catch(a){return{ok:!1,error:Y(a)}}return{ok:!0,path:`${Ho}/${o}`}}function Cy(n,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),r=Wo[t];if(!r)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:r,base64:EO(Yo(n,Ho,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var AO,TO,OO,Ry=v(()=>{"use strict";tn();zn();$t();Ty();AO=4e3,TO=4e3,OO=[["openrouter","google/gemini-3.1-flash-lite-preview"],["gemini","gemini-3.1-flash-lite"]]});function RO(n,...e){return n.slice().sort((t,r)=>{for(let{key:s,desc:i}of e){let o=s(t),a=s(r);if(o!==a)return o==null?i?-1:1:a==null||o<a?i?1:-1:i?-1:1}return 0})}var _y,Ny=v(()=>{"use strict";_y=(n,e)=>RO(n,{key:e,desc:!0})});import{existsSync as Iy,openSync as _O,readSync as NO,closeSync as IO,statSync as Qn,readdirSync as $y,watchFile as $O,unwatchFile as Ly,mkdirSync as LO,writeFileSync as MO,readFileSync as Vo,unlinkSync as BO,rmSync as DO}from"fs";import{stat as jO}from"fs/promises";import{dirname as FO,join as ln,resolve as My}from"path";function KO(n){if(!Number.isInteger(n))return!0;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function Zn(n){let e={cwd:z,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,r,s=0;function i(){if(e.file){for(let g of t)if(g.file===e.file)return g;return}return r}function o(g){let k={d:n.createDriver(e.cwd,g),file:g,id:`new:${++s}`,startedAt:Date.now()};return t.add(k),e.file||(r=k),k}function a(){let g=[...t].filter(w=>w.file);if(!g.length)return[];let k=new Map(n.listSessionFiles(e.cwd).map(w=>[w.file,w.sessionId]));return g.map(w=>{let T=k.get(w.file);return{rec:w,sessionId:T??w.id,pending:T===void 0}})}let l=()=>a().filter(g=>g.pending&&g.rec.prompt!==void 0);async function c(g){t.delete(g),r===g&&(r=void 0);try{await g.d.dispose()}catch(k){console.error("[composer] dispose:",Y(k))}}function d(){let g=i(),k=new Set(l().map(w=>w.rec));for(let w of[...t])w!==g&&(k.has(w)||w.d.streaming||w.d.queue||w.d.error||c(w))}function u(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(r&&!e.file&&r.file){let g=n.listSessionFiles(e.cwd).find(k=>k.file===r.file);g&&x(g)}r&&!e.file&&r.prompt!==void 0&&e.sessionId!==r.id&&($(void 0,r.id),e.everAttached=!0)}let f=g=>ln(g,qO),p=(g,k)=>ln(f(g),`${k}.lock`);function m(g,k){try{let w=p(g,k);if(Date.now()-Qn(w).mtimeMs>=By)return!1;try{let T=parseInt(Vo(w,"utf8").trim(),10);if(T===process.pid||!KO(T))return!1}catch{}return!0}catch{return!1}}function h(g,k){if(k)try{LO(f(g),{recursive:!0}),MO(p(g,k),String(process.pid))}catch(w){console.error("[lock] claim failed:",Y(w))}}function b(g){try{DO(ln(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function A(g){let k=f(g);if(!Iy(k))return;let w;try{w=$y(k)}catch{return}let T=Date.now();for(let I of w){if(!I.endsWith(".lock"))continue;let B=ln(k,I);try{let F=Qn(B);T-F.mtimeMs>JO&&BO(B)}catch{}}}function S(g){try{return Qn(g),!1}catch(k){return k.code==="ENOENT"}}function P(){let g=e;if(g.file&&!S(g.file)){h(g.cwd,g.sessionId);return}let k=_(g);k&&x(k)}function _(g){if(!g.everAttached)return C(g.cwd)??R(g.cwd,()=>!0)}function C(g){let k=f(g);if(!Iy(k))return;let w;try{w=$y(k)}catch{return}let T;for(let B of w)if(B.endsWith(".lock"))try{let F=Qn(ln(k,B));if(Date.now()-F.mtimeMs>=By||parseInt(Vo(ln(k,B),"utf8").trim(),10)!==process.pid)continue;(!T||F.mtimeMs>T.mtime)&&(T={sessionId:B.slice(0,-5),mtime:F.mtimeMs})}catch{}if(!T)return;let I=n.listSessionFiles(g).find(B=>B.sessionId===T.sessionId);if(!(!I||S(I.file)))return I}function R(g,k){return n.listSessionFiles(g).sort((w,T)=>T.mtime-w.mtime).find(w=>!m(g,w.sessionId)&&k(w))}function $(g,k){let w=e;if(w.file)try{Ly(w.file)}catch{}w.file=g,w.sessionId=k,w.partial="",w.offset=0,w.latest={in:0,out:0,cached:0,cacheCreate:0},w.latestModel=null,w.entries=new Map,w.chainLastId=void 0,w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:k})}function x(g){let k=e;r=void 0,$(g.file,g.sessionId),k.everAttached=!0,h(k.cwd,g.sessionId),K();try{Ly(g.file)}catch{}$O(g.file,{interval:200},()=>K())}function D(){$(void 0,"")}function K(){let g=e;if(!g.file)return;let k;try{k=Qn(g.file).size}catch{return}if(k<=g.offset)return;let w;try{w=_O(g.file,"r")}catch{return}try{let W=k-g.offset,be=Buffer.alloc(W),ae=0;for(;ae<W;){let jd=NO(w,be,ae,W-ae,g.offset+ae);if(!jd)break;ae+=jd}g.offset+=ae,g.partial+=be.subarray(0,ae).toString("utf8")}finally{IO(w)}let T,I;for(;(I=g.partial.indexOf(`
|
|
1587
1615
|
`))>=0;){let W=g.partial.slice(0,I);if(g.partial=g.partial.slice(I+1),!W.trim())continue;let be=n.parseEntry(W);if(!be)continue;let ae=n.idOf(be);ae&&(g.entries.set(ae,be),!n.isSidechain(be)&&n.isLeafType(be)&&(T=ae))}if(!T)return;let B=[],F=g.entries.get(T),V=!1;for(;F;){if(B.push(F),n.idOf(F)===g.chainLastId){V=!0;break}let W=n.parentOf(F);F=W?g.entries.get(W):void 0}if(V)for(let W=B.length-2;W>=0;W--)N(B[W]);else{g.chainLastId!==void 0&&(g.buffer.push({type:"cleared"}),g.buffer.push({type:"session",sessionId:g.sessionId}),g.latest={in:0,out:0,cached:0,cacheCreate:0});let W=new Set(B.map(ae=>n.idOf(ae))),be=q(g.entries);for(let ae=B.length-1;ae>=0;ae--)N(B[ae]),y(n.idOf(B[ae]),be,W)}g.chainLastId=T}function q(g){let k=new Map;for(let w of g.values()){let T=n.parentOf(w);if(!T)continue;let I=k.get(T);I?I.push(w):k.set(T,[w])}return k}function y(g,k,w){if(!g)return;let T=k.get(g);if(!T)return;let I=T.filter(W=>!n.isSidechain(W));if(I.length<2)return;let B=I.filter(W=>!w.has(n.idOf(W)));if(!B.length)return;let F=[],V=0;for(let W of B){let be=E(W,k);F.push(...be.events),V+=be.count}V>0&&e.buffer.push({type:"fork",atId:g,count:V,events:F})}function E(g,k){let w=[],T=[g];for(;T.length;){let F=T.pop();if(n.isSidechain(F))continue;w.push(F);let V=k.get(n.idOf(F)??"");if(V)for(let W of V)T.push(W)}w.sort((F,V)=>(Date.parse(n.timestampOf(F)??"")||0)-(Date.parse(n.timestampOf(V)??"")||0));let I=[];for(let F of w)n.isRecoveryNoise(F)||I.push(...n.apply(F,e.sessionStartMs).events);return{count:I.reduce((F,V)=>F+(V.type==="user"||V.type==="assistant"?1:0),0),events:I}}function N(g){try{let{events:k,usage:w,model:T,cost:I}=n.apply(g,e.sessionStartMs);for(let B of k)e.buffer.push(B);k.some(B=>B.type==="assistant")&&i()?.d.clearCompletedDraft(),k.some(B=>B.type==="user")&&i()?.d.clearEcho(),T&&(e.latestModel=T),w&&(e.latest=w),(w||I)&&e.buffer.push({type:"usage",...e.latest,cost:I})}catch(k){console.error("[mirror] skipped malformed entry:",Y(k))}}async function L(){return{cwd:e.cwd,pid:process.pid,composer:!!n.createDriver,elsewhere:await M()}}async function M(){if(n.listSessionFiles(e.cwd).length)return;let g=await an();if(!g)return;let k=My(g).toLowerCase();for(let w=My(e.cwd);w.toLowerCase()!==k;){let T=FO(w);if(T===w)return;w=T;let I=n.listSessionFiles(w).length;if(I)return{dir:w,count:I}}}M().then(g=>{g&&console.log(`No sessions for ${e.cwd} \u2014 ${g.count} exist for ${g.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let H=new qo;async function G(g,k){H.accept(g,k)&&console.log(k)}function he(){let g=n.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-Qn(e.file).mtimeMs<1e4}catch{return!1}}function ee(){return n.chainWorking([...e.entries.values()])&&he()}function oe(){!n.createDriver||i()||e.latestModel||ee()||o(e.file)}async function ke(g){let k=e;P(),u(),oe(),d();let w=i();for(let B of t)B!==w&&B.d.dialog;let T=a().filter(B=>B.rec.d.streaming).map(B=>B.sessionId),I=n.createDriver?{streaming:!!w?.d.streaming,draft:w?.d.draft??null,echo:w?.d.echo??null,status:w?.d.status??null,dialog:w?.d.dialog??null,queue:w?.d.queue??null,stats:w?.d.stats??null,model:w?.d.model??null,error:w?.d.error}:void 0;return{events:k.buffer.slice(g),cursor:k.buffer.length,working:!!w?.d.streaming||ee(),latestModel:k.latestModel,composer:I,busy:T}}async function Re(){P(),u();let g=i();if(g?.d.error&&!g.d.streaming&&(await c(g),g=void 0),!g){if(ee())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};g=o(e.file)}let k=g;return{ok:!0,d:k.d,markSent:w=>{k.prompt===void 0&&(k.prompt=w)}}}async function ka(g,k){if(!n.createDriver)return{ok:!1,error:"not supported"};let w=String(g??"").trim();if(!w)return{ok:!1,error:"empty message"};let T=await Re();if(!T.ok)return T;let I=await T.d.send(w,k);return I.ok&&T.markSent(w),I}async function Rw(g,k){let w=i();return w?w.d.respondUi(String(g??""),k??{}):{ok:!1,error:"no dialog pending"}}async function _w(g,k){if(!n.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(k?.spawn){let T=await Re();return T.ok?T.d.rpc(g):T}let w=i();return!w||w.d.error?{ok:!1,error:"not running"}:w.d.rpc(g)}async function Nw(){let g=i();if(g)try{await g.d.stop()}catch(k){console.error("[composer] stop:",Y(k))}return{ok:!0}}async function Iw(){return n.createDriver?(u(),!e.file&&r&&r.prompt===void 0&&!r.d.streaming&&!r.d.error?{ok:!0}:(r?.d.error&&await c(r),r=void 0,D(),o(void 0),d(),{ok:!0})):{ok:!1,error:"not supported"}}async function $w(){if(!n.createDriver)return[];let g=await Je(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),k=g!==null?g.split(`
|
|
1588
1616
|
`).filter(Boolean):await n.walkFiles?.(e.cwd)??[];return(await Promise.all(k.map(async T=>{try{return{f:T,m:(await jO(ln(e.cwd,T))).mtimeMs}}catch{return{f:T,m:0}}}))).sort((T,I)=>I.m-T.m).map(T=>T.f)}function Lw(){for(let g of[...t])c(g)}async function Mw(g){return n.createDriver?Py(e.cwd,g):{ok:!1,error:"not supported"}}async function Bw(g){return Cy(e.cwd,String(g??""))}async function Dw(){let g=n.listSessionFiles(e.cwd).map(({sessionId:w,file:T,mtime:I})=>({sessionId:w,mtime:I,preview:n.readPreview(T)})),k=l().map(w=>({sessionId:w.sessionId,mtime:w.rec.startedAt,preview:w.rec.prompt??"",pending:!0}));return _y([...g,...k],w=>w.mtime)}let Md=new Map;function jw(g,k){let w=Md.get(g);if(w&&w.mtime===k)return w.turns;let T=[],I="";try{I=Vo(g,"utf8")}catch{return[]}for(let B of I.split(`
|
|
1589
1617
|
`)){if(!B.trim())continue;let F=n.parseEntry(B);if(!F)continue;let V=n.searchText(F);V&&T.push({text:V,lower:V.toLowerCase()})}return Md.set(g,{mtime:k,turns:T}),T}async function Fw(g){let k=g.toLowerCase(),w=[];for(let{sessionId:T,file:I,mtime:B}of n.listSessionFiles(e.cwd).sort((F,V)=>V.mtime-F.mtime)){let{hitCount:F,snippet:V}=Ko(jw(I,B),k);if(F&&(w.push({sessionId:T,mtime:B,preview:n.readPreview(I),hitCount:F,snippet:V}),w.length>=HO))break}return w}let Bd=800,Dd=new Map;function Uw(g,k){let w=Dd.get(g);if(w&&w.mtime===k)return w.text;let T="";try{T=Vo(g,"utf8")}catch{return""}let I="";for(let F of T.split(`
|
|
1590
|
-
`)){if(!F.trim())continue;let V=n.parseEntry(F);if(V)for(let W of n.apply(V,e.sessionStartMs).events)W.type==="assistant"&&W.text.trim()&&(I=W.text.trim())}let B=I.length>Bd?I.slice(0,Bd).trimEnd()+"\u2026":I;return Dd.set(g,{mtime:k,text:B}),B}async function qw(g){let k=n.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:k?Uw(k.file,k.mtime):""}}async function Jw(g){let k=e,w=n.listSessionFiles(k.cwd).find(T=>T.sessionId===g);if(!w){let T=l().find(I=>I.sessionId===g)?.rec;return T?((r!==T||k.sessionId!==T.id)&&(r=T,$(void 0,T.id),k.everAttached=!0,d()),{ok:!0}):{ok:!1,error:"session not found"}}return w.file===k.file?{ok:!0}:(x(w),u(),d(),{ok:!0})}return b(e.cwd),A(e.cwd),P(),{info:L,poll:ke,logInlineStatus:G,listSessions:Dw,searchSessions:Fw,sessionPeek:qw,attach:Jw,composerSend:ka,composerStop:Nw,composerNew:Iw,composerFiles:$w,composerUiRespond:Rw,composerRpc:_w,composerPaste:Mw,composerPasteRead:Bw,shutdownComposer:Lw}}var UO,qO,By,JO,HO,zo=v(()=>{
|
|
1618
|
+
`)){if(!F.trim())continue;let V=n.parseEntry(F);if(V)for(let W of n.apply(V,e.sessionStartMs).events)W.type==="assistant"&&W.text.trim()&&(I=W.text.trim())}let B=I.length>Bd?I.slice(0,Bd).trimEnd()+"\u2026":I;return Dd.set(g,{mtime:k,text:B}),B}async function qw(g){let k=n.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:k?Uw(k.file,k.mtime):""}}async function Jw(g){let k=e,w=n.listSessionFiles(k.cwd).find(T=>T.sessionId===g);if(!w){let T=l().find(I=>I.sessionId===g)?.rec;return T?((r!==T||k.sessionId!==T.id)&&(r=T,$(void 0,T.id),k.everAttached=!0,d()),{ok:!0}):{ok:!1,error:"session not found"}}return w.file===k.file?{ok:!0}:(x(w),u(),d(),{ok:!0})}return b(e.cwd),A(e.cwd),P(),{info:L,poll:ke,logInlineStatus:G,listSessions:Dw,searchSessions:Fw,sessionPeek:qw,attach:Jw,composerSend:ka,composerStop:Nw,composerNew:Iw,composerFiles:$w,composerUiRespond:Rw,composerRpc:_w,composerPaste:Mw,composerPasteRead:Bw,shutdownComposer:Lw}}var UO,qO,By,JO,HO,zo=v(()=>{"use strict";$t();xy();hs();Ju();Ry();Ny();UO=".typebulb",qO=`${UO}/locks`,By=5e3,JO=6e4;HO=50});import{existsSync as Yu,mkdirSync as WO,readFileSync as Dy,writeFileSync as YO}from"fs";import{join as cn,isAbsolute as VO}from"path";async function zu(n,e){let t=VO(n)?n:cn(z,n);return Yu(t)?(Tu(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Gu(n){let e=z,t=Au(n),r=cn(e,"typebulbs");WO(r,{recursive:!0});let s=Fc(t),i=`${s}.bulb.md`;for(let c=2;Yu(cn(r,i))&&Dy(cn(r,i),"utf8")!==t;c++)i=`${s}-${c}.bulb.md`;let o=cn(r,i);Yu(o)||YO(o,t);let a=cn("typebulbs",i),l=await Hi(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:l.pid,url:l.url}}async function Xu(){return Q(z)}async function Qu(n){return await Wt(n),{ok:!0}}async function Zu(){let n=await cs(z);return To(z).filter(e=>!e.serverOnly).map(e=>({...e,trusted:sn(e.path),batches:Su(e.path),lastRunAt:n(e.path)}))}async function ed(n){let e=n.toLowerCase(),t=[];for(let r of To(z).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Dy(r.path,"utf8")}catch{continue}let i=[];for(let l of s.split(`
|
|
1591
1619
|
`)){let c=l.replace(/\s+/g," ").trim();c&&i.push({text:c,lower:c.toLowerCase()})}let{hitCount:o,snippet:a}=Ko(i,e);o&&t.push({path:r.path,hitCount:o,snippet:a})}return t}async function td(n,e,t){let r=z;e!=null&&Wn(n,e);let s=await Hi(n,{cwd:r,open:!1,trust:e,batch:t??void 0});return{ok:!0,file:s.file,pid:s.pid,url:s.url,trust:!!s.trust}}async function nd(n){return{cap:await Eu(n)}}async function rd(n,e){return Wn(n,e),{ok:!0}}async function sd(n,e){return We(n,e)}async function id(){return ms&&Date.now()-ms.fetchedAt<=GO?ms.samples:(Ku??=XO().finally(()=>{Ku=null}),Ku)}async function XO(){try{let n=await fetch(`${zO}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Fy)});if(!n.ok)throw new Error(`HTTP ${n.status}`);let e=await n.json(),t=i=>i.order??Number.MAX_SAFE_INTEGER,r=i=>Date.parse(i.createdAt??"")||0,s=e.filter(i=>i.slug!=="welcome").sort((i,o)=>t(i)-t(o)||r(o)-r(i)).map(i=>({slug:i.slug,name:i.name,description:Na(i.config)}));return ms={samples:s,fetchedAt:Date.now()},s}catch{return ms?.samples??[]}}async function od(n){return Vu.test(n)?qy(jy,"samples",n,!0):{ok:!1,error:"bad slug"}}async function ld(){let n=ad();if(!n)return{bulbs:[]};let e=`${Go()}
|
|
1592
|
-
${n}`;return Lt?.key===e&&Date.now()-Lt.fetchedAt<=QO?{user:Lt.user,bulbs:Lt.bulbs}:(Hu??=ZO(e,n).finally(()=>{Hu=null}),Hu)}async function Wu(n,e,t){let r=await fetch(`${n}${e}`,{headers:t,signal:AbortSignal.timeout(Fy)});if(!r.ok)throw new Error(`HTTP ${r.status}`);if(!r.headers.get("content-type")?.includes("json"))throw new Error("not json");return r.json()}async function ZO(n,e){let t={Authorization:`Bearer ${e}`};try{let r=Go(),s;try{s=await Wu(r,"/api/me",t)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await Wu(r,"/api/me",t)}let o=(await Wu(r,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Na(a.config)}));return Lt={key:n,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return Lt?.key===n?{user:Lt.user,bulbs:Lt.bulbs}:{bulbs:[]}}}async function cd(n,e,t=!1){return!Vu.test(e)||!Vu.test(n)?{ok:!1,error:"bad slug"}:qy(Go(),n,e,t)}async function qy(n,e,t,r){let s=Io(e,t);try{let i=await Mo({origin:n,userSlug:e,slug:t,dest:cn(z,s)},{force:r,token:ad(),timeoutMs:Uy});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="asset-conflict"?{ok:!1,conflict:!0,error:`local assets differ from the site copies (${i.paths.join(", ")})`}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function ud(n,e=!1){let t=ad();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=Lo(n,z,Go()),s=await Do(r,{token:t,force:e,timeoutMs:Uy});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="asset-error"?{ok:!1,error:`assets sync failed: ${s.message}`}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(r){return{ok:!1,error:r?.message??String(r)}}}var zO,jy,GO,Fy,Uy,ms,Ku,Vu,QO,Lt,Hu,Go,ad,Xo=v(()=>{zn();$t();Ju();ne();zO="https://api.typebulb.com",jy="https://typebulb.com",GO=3600*1e3,Fy=5e3,Uy=15e3,ms=null,Ku=null;Vu=/^[a-z0-9][a-z0-9-]*$/,QO=300*1e3,Lt=null,Hu=null,Go=()=>wo("TYPEBULB_ORIGIN",z)||jy,ad=()=>wo("TYPEBULB_TOKEN",z)});import{readFileSync as pd,writeFileSync as Ky,mkdirSync as eP,appendFileSync as Hy,rmSync as Jy}from"fs";import{join as ea,dirname as tP}from"path";import{createServer as nP}from"http";function Mt(n){try{return JSON.parse(pd(n,"utf8"))}catch{return null}}function Zo(n,e){eP(tP(n),{recursive:!0}),Ky(n,JSON.stringify(e,null,2)+`
|
|
1620
|
+
${n}`;return Lt?.key===e&&Date.now()-Lt.fetchedAt<=QO?{user:Lt.user,bulbs:Lt.bulbs}:(Hu??=ZO(e,n).finally(()=>{Hu=null}),Hu)}async function Wu(n,e,t){let r=await fetch(`${n}${e}`,{headers:t,signal:AbortSignal.timeout(Fy)});if(!r.ok)throw new Error(`HTTP ${r.status}`);if(!r.headers.get("content-type")?.includes("json"))throw new Error("not json");return r.json()}async function ZO(n,e){let t={Authorization:`Bearer ${e}`};try{let r=Go(),s;try{s=await Wu(r,"/api/me",t)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await Wu(r,"/api/me",t)}let o=(await Wu(r,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Na(a.config)}));return Lt={key:n,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return Lt?.key===n?{user:Lt.user,bulbs:Lt.bulbs}:{bulbs:[]}}}async function cd(n,e,t=!1){return!Vu.test(e)||!Vu.test(n)?{ok:!1,error:"bad slug"}:qy(Go(),n,e,t)}async function qy(n,e,t,r){let s=Io(e,t);try{let i=await Mo({origin:n,userSlug:e,slug:t,dest:cn(z,s)},{force:r,token:ad(),timeoutMs:Uy});return i.kind==="conflict"?{ok:!1,conflict:!0,error:"local file differs from the site copy"}:i.kind==="asset-conflict"?{ok:!1,conflict:!0,error:`local assets differ from the site copies (${i.paths.join(", ")})`}:i.kind==="http-error"?{ok:!1,error:`HTTP ${i.status}`}:i.kind==="not-markdown"?{ok:!1,error:`not a bulb (${i.contentType??"no content-type"})`}:{ok:!0,file:s,upToDate:i.kind==="up-to-date"}}catch(i){return{ok:!1,error:i?.message??String(i)}}}async function ud(n,e=!1){let t=ad();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=Lo(n,z,Go()),s=await Do(r,{token:t,force:e,timeoutMs:Uy});return s.kind==="conflict"?{ok:!1,conflict:!0,error:s.message}:s.kind==="asset-error"?{ok:!1,error:`assets sync failed: ${s.message}`}:s.kind==="http-error"?{ok:!1,error:`HTTP ${s.status}: ${s.message}`}:{ok:!0,created:s.created,serverStripped:s.serverStripped}}catch(r){return{ok:!1,error:r?.message??String(r)}}}var zO,jy,GO,Fy,Uy,ms,Ku,Vu,QO,Lt,Hu,Go,ad,Xo=v(()=>{"use strict";zn();$t();Ju();ne();zO="https://api.typebulb.com",jy="https://typebulb.com",GO=3600*1e3,Fy=5e3,Uy=15e3,ms=null,Ku=null;Vu=/^[a-z0-9][a-z0-9-]*$/,QO=300*1e3,Lt=null,Hu=null,Go=()=>wo("TYPEBULB_ORIGIN",z)||jy,ad=()=>wo("TYPEBULB_TOKEN",z)});import{readFileSync as pd,writeFileSync as Ky,mkdirSync as eP,appendFileSync as Hy,rmSync as Jy}from"fs";import{join as ea,dirname as tP}from"path";import{createServer as nP}from"http";function Mt(n){try{return JSON.parse(pd(n,"utf8"))}catch{return null}}function Zo(n,e){eP(tP(n),{recursive:!0}),Ky(n,JSON.stringify(e,null,2)+`
|
|
1593
1621
|
`)}function Yy(n,e,t){let r=ea(n,".gitignore"),s="";try{s=pd(r,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(l=>l.trim())),o=e.filter(l=>!i.has(l));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
1594
1622
|
`)?`
|
|
1595
1623
|
`:"";try{Hy(r,a+t+`
|
|
@@ -1606,8 +1634,8 @@ data: ${JSON.stringify(a)}
|
|
|
1606
1634
|
`))!==-1;){let l=n.slice(0,a);if(n=n.slice(a+2),!l.trim())continue;let c=s(l);c!==null&&(o+=c)}return o}}function uP(n){return new Promise(e=>{let t=[];n.on("data",r=>t.push(r)),n.on("end",()=>e(Buffer.concat(t).toString("utf8"))),n.on("error",()=>e(Buffer.concat(t).toString("utf8")))})}function gs(n,e,t,r){n.writableEnded||(n.writeHead(e,{"content-type":"application/json"}),n.end(JSON.stringify({type:"error",error:{type:t,message:r}})))}async function dP(n,e,t){if(!Ge){gs(e,400,"invalid_request_error",iP);return}let r=process.env.OPENROUTER_API_KEY;if(!r){gs(e,401,"authentication_error","OPENROUTER_API_KEY not set in the typebulb proxy");return}let s=new AbortController;e.on("close",()=>{e.writableEnded||s.abort()});let i;try{i=await fetch(hd,{method:"POST",headers:zy(n,r),body:Gy(t),signal:s.signal})}catch(u){gs(e,502,"api_error",`proxy upstream failed: ${Y(u)}`);return}let o=i.headers.get("content-type")||"application/json";if(e.writeHead(i.status,{"content-type":o}),!i.body){e.end();return}let a=o.includes("event-stream"),l=i.body.getReader(),c=new TextDecoder,d=a?cP():null;try{for(;;){let{done:u,value:f}=await l.read();if(u)break;if(f)if(d){let p=c.decode(f,{stream:!0});aP(p);let m=d(p);m&&e.write(m)}else e.write(Buffer.from(f))}}catch{}finally{e.writableEnded||e.end()}}async function fP(n,e,t){let r=process.env.OPENROUTER_API_KEY,s=()=>{e.writeHead(200,{"content-type":"application/json"}),e.end(JSON.stringify({input_tokens:Math.max(1,Math.ceil(t.length/4))}))};if(!Ge||!r)return s();try{let i=await fetch(`${hd}/count_tokens`,{method:"POST",headers:zy(n,r),body:Gy(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function pP(n,e){let t=n.url||"/";if(n.method==="HEAD"){e.writeHead(200),e.end();return}if(n.method!=="POST"){gs(e,404,"not_found_error",t);return}uP(n).then(r=>{if(t.includes("count_tokens"))return fP(n,e,r);if(t.includes("/v1/messages"))return dP(n,e,r);gs(e,404,"not_found_error",t)})}function hP(){return er&&un?Promise.resolve(un):new Promise((n,e)=>{let t=nP(pP);t.on("error",e),t.listen(0,"127.0.0.1",()=>{er=t,un=t.address().port,console.log(`[switcher] wire proxy listening on ${Qo(un)}`),n(un)})})}function mP(){try{er?.close()}catch{}er=null,un=null}function gP(n,e){let t=ta(n),r=Mt(t),s=r||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===Qo(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=na(n);if(!Mt(i)){let a={};for(let l of Wy)a[l]=l in s.env?s.env[l]:null;Zo(i,{managedBy:"agent-switcher",fileExisted:r!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=Qo(e),s.env.ANTHROPIC_AUTH_TOKEN=sP,Zo(t,s),Yy(n,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function yP(n,e,t){let r=na(n),s=Mt(r)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},Zo(r,s)}function Xy(n){let e=ta(n),t=na(n),r=Mt(t),s=Mt(e);if(s?.env){let i=r?.snapshot||{};for(let o of Wy){let a=i[o];a==null?delete s.env[o]:s.env[o]=a}if(Object.keys(s.env).length===0&&delete s.env,r?.fileExisted===!1&&Object.keys(s).length===0)try{Jy(e,{force:!0})}catch{}else Zo(e,s)}try{Jy(t,{force:!0})}catch{}}async function bP(){let n=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await it()).filter(r=>r.provider==="openrouter"&&!md(r.name)).map(r=>({id:r.name,label:r.friendlyName||r.name}))}catch(r){console.error("[switcher] model list failed",Y(r))}let t=e.length?void 0:gu()??void 0;return{hasKey:n,models:e,error:t}}async function wP(){if(er&&Ge)return{active:!0,managed:!0,model:Ge,port:un,provider:dn,routedModel:ys,caching:bs,reasoning:ws,externalBaseUrl:null};let n=Mt(ta(z))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:ws,externalBaseUrl:n.ANTHROPIC_BASE_URL||null}}async function Qy(n,e){let t=await hP();return Ge=n,dn=e,gP(z,t),t}async function vP({model:n}){if(!process.env.OPENROUTER_API_KEY)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!n)return{ok:!1,error:"no model given"};if(md(n))return{ok:!1,error:"Refusing to route an Anthropic model through OpenRouter \u2014 that bills full API rate with no caching. Use it on your Anthropic subscription instead."};try{await Qy(n,gd[n]??null),ys=null,bs="unknown",yP(z,n,dn)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${Y(e)}`}}return{ok:!0}}async function SP({level:n}){return n!=null&&(!Number.isInteger(n)||n<0||n>=dd.length)?{ok:!1,error:`reasoning level must be 0\u2013${dd.length-1} or null`}:(ws=n,{ok:!0,level:n})}async function kP(){return Xy(z),Ge=null,dn=null,ys=null,bs="unknown",{ok:!0}}async function xP({key:n}){let e=(n||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=z,r=ea(t,".env"),s="";try{s=pd(r,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Ky(r,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
1607
1635
|
`)?`
|
|
1608
1636
|
`:"";Hy(r,i+`OPENROUTER_API_KEY=${e}
|
|
1609
|
-
`)}}catch(i){return{ok:!1,error:Y(i)}}return process.env.OPENROUTER_API_KEY=e,Yy(t,[".env"],"# secrets"),{ok:!0}}function EP(){if(!(!er&&!Ge)){try{Xy(z)}catch{}mP()}}function AP(n,e){return Zy.test(e)?"blocked by your OpenRouter data policy":n===401||n===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":n===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":n===429||/rate limit/i.test(e)?"rate limited":n===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function TP(n){if(Zy.test(n))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function OP(n,e,t){if(!n)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let r=fd(e?.cache_read_input_tokens)||fd(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return r>0?{works:!0,read:r,note:`${r} tokens read from cache on the 2nd call`}:s?{works:!1,read:r,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:r,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function PP({model:n}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!n)return{ok:!1,error:"no model given"};if(md(n))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),r=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:n,max_tokens:64,system:[{type:"text",text:r,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let l=new AbortController,c=setTimeout(()=>l.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:Vy(a)}:i),u=await fetch(hd,{method:"POST",signal:l.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(c)}};try{let{r:a,j:l}=await o();if(!a.ok){let A=l?.error?.message||l?.message||JSON.stringify(l).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:AP(a.status,A),restriction:TP(A)}}let c=typeof l?.provider=="string"?l.provider:void 0,d=l?.content?.find?.(A=>A.type==="text")?.text??l?.content?.[0]?.text??"ok",u=fd(l?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(c),{works:m,read:h,note:b}=OP(f.ok,p?.usage,c);return m===!0&&c&&(gd[n]=c,Ge===n&&(dn=c)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:c,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:b}}}catch(a){let l=Y(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(l)?"timed out (20s)":l}}}var rP,hd,sP,iP,Wy,oP,dd,ta,na,Qo,md,er,un,Ge,dn,ys,bs,ws,gd,fd,Vy,Zy,eb=v(()=>{zn();$t();rP="https://openrouter.ai/api",hd=`${rP}/v1/messages`,sP="typebulb-proxy-managed",iP="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",Wy=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],oP=5e3,dd=["low","medium","high"],ta=n=>ea(n,".claude","settings.local.json"),na=n=>ea(n,".claude",".cc-switcher.json"),Qo=n=>`http://127.0.0.1:${n}`;md=n=>/^anthropic\//i.test(n)||/claude/i.test(n),er=null,un=null,Ge=null,dn=null,ys=null,bs="unknown",ws=1,gd={},fd=n=>typeof n=="number"?n:0,Vy=n=>({order:[n],allow_fallbacks:!1});Zy=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=Mt(na(z)),t=e?.active?.model;if(!t)return;let s=(Mt(ta(z))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Qy(t,e.active.provider??gd[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Qo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",Y(e))}})()});var nb={};Ea(nb,{attach:()=>MP,blockToMarkdown:()=>Di,breakout:()=>Gu,capText:()=>we,cleanUserText:()=>kt,clearSwitchModel:()=>kP,composerPasteRead:()=>BP,displayName:()=>CP,downloadSample:()=>od,firstLineDigest:()=>$e,git:()=>Je,gitChangedFiles:()=>Uu,gitDiff:()=>qu,info:()=>RP,isHiddenTurn:()=>Ur,launchBulb:()=>td,listBreakouts:()=>Xu,listBulbFiles:()=>Zu,listMyBulbs:()=>ld,listSamples:()=>id,listSessions:()=>IP,listSwitchModels:()=>bP,logInlineStatus:()=>NP,openFile:()=>zu,poll:()=>_P,predictTrustOf:()=>nd,probeModel:()=>PP,pullRemoteBulb:()=>cd,pushLocalBulb:()=>ud,readBulbLog:()=>sd,repoRoot:()=>an,saveOpenRouterKey:()=>xP,searchBulbs:()=>ed,searchSessions:()=>$P,sessionPeek:()=>LP,setBulbTrust:()=>rd,setReasoning:()=>SP,setSwitchModel:()=>vP,shutdownSwitcher:()=>EP,stopBreakout:()=>Qu,switchState:()=>wP,toolResultDigest:()=>Pc});var tb,CP,RP,_P,NP,IP,$P,LP,MP,BP,rb=v(()=>{zo();ji();Xo();hs();eb();ji();Fr();tb=new On,CP=tb.displayName,{info:RP,poll:_P,logInlineStatus:NP,listSessions:IP,searchSessions:$P,sessionPeek:LP,attach:MP,composerPasteRead:BP}=Zn(tb)});var ib={};Ea(ib,{attach:()=>HP,breakout:()=>Gu,composerPasteRead:()=>WP,displayName:()=>DP,downloadSample:()=>od,git:()=>Je,gitChangedFiles:()=>Uu,gitDiff:()=>qu,info:()=>jP,launchBulb:()=>td,listBreakouts:()=>Xu,listBulbFiles:()=>Zu,listMyBulbs:()=>ld,listSamples:()=>id,listSessions:()=>qP,logInlineStatus:()=>UP,openFile:()=>zu,poll:()=>FP,predictTrustOf:()=>nd,pullRemoteBulb:()=>cd,pushLocalBulb:()=>ud,readBulbLog:()=>sd,repoRoot:()=>an,searchBulbs:()=>ed,searchSessions:()=>JP,sessionPeek:()=>KP,setBulbTrust:()=>rd,stopBreakout:()=>Qu});var sb,DP,jP,FP,UP,qP,JP,KP,HP,WP,ob=v(()=>{zo();Rc();Xo();hs();sb=new Pn,DP=sb.displayName,{info:jP,poll:FP,logInlineStatus:UP,listSessions:qP,searchSessions:JP,sessionPeek:KP,attach:HP,composerPasteRead:WP}=Zn(sb)});import{readFileSync as YP,writeFileSync as VP,mkdirSync as zP}from"fs";import{homedir as GP}from"os";import*as ra from"path";async function cb(){try{let n=await fetch(new URL("/api/tags",lb()).toString(),{signal:AbortSignal.timeout(XP)});return n.ok?((await n.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function ub(n){let e;try{e=YP(n,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;return{json:r,unreadable:"providers"in r&&!yd(r)}}}catch{}return{json:void 0,unreadable:!0}}function yd(n){let e=n?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function QP(n){let e=yd(n);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(r=>r?.id).filter(r=>typeof r=="string"):[]}async function db(){let{json:n,unreadable:e}=ub(ab());return e?{installed:[],configured:null}:{installed:await cb(),configured:QP(n)}}async function fb(){let n=await cb();return n.length?ZP(ab(),n,lb()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function ZP(n,e,t){let{json:r,unreadable:s}=ub(n);if(s)return{ok:!1,error:`could not parse ${n} \u2014 edit the ollama provider there yourself`};let i={...r??{},providers:{...yd(r)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{zP(ra.dirname(n),{recursive:!0}),VP(n,JSON.stringify(i,null,2)+`
|
|
1610
|
-
`)}catch(o){return{ok:!1,error:`could not write ${n}: ${Y(o)}`}}return{ok:!0,count:e.length}}var XP,ab,lb,pb=v(()=>{
|
|
1637
|
+
`)}}catch(i){return{ok:!1,error:Y(i)}}return process.env.OPENROUTER_API_KEY=e,Yy(t,[".env"],"# secrets"),{ok:!0}}function EP(){if(!(!er&&!Ge)){try{Xy(z)}catch{}mP()}}function AP(n,e){return Zy.test(e)?"blocked by your OpenRouter data policy":n===401||n===403||/unauthor|invalid api key|no auth|forbidden/i.test(e)?"auth rejected \u2014 check your OpenRouter key":n===404||/not a valid model|no such model|unknown model|model not found/i.test(e)?"model not found on this route":n===429||/rate limit/i.test(e)?"rate limited":n===402||/insufficient|credit|quota|balance/i.test(e)?"out of credits / quota":e.slice(0,160)}function TP(n){if(Zy.test(n))return"This model's only provider(s) require prompt logging/training, which your OpenRouter account disallows by default. Allow it (or that provider) at openrouter.ai/settings/privacy, then probe again."}function OP(n,e,t){if(!n)return{works:null,read:0,note:t?`couldn't re-test on ${t} \u2014 caching unconfirmed`:"caching unconfirmed"};let r=fd(e?.cache_read_input_tokens)||fd(e?.prompt_tokens_details?.cached_tokens),s=e?.cache_read_input_tokens!==void 0||e?.cache_creation_input_tokens!==void 0||e?.prompt_tokens_details!==void 0;return r>0?{works:!0,read:r,note:`${r} tokens read from cache on the 2nd call`}:s?{works:!1,read:r,note:"no cache reads after a warm call \u2014 every turn re-bills the full context"}:{works:null,read:r,note:"route doesn't report cache usage \u2014 caching almost certainly not honored"}}async function PP({model:n}){let e=process.env.OPENROUTER_API_KEY;if(!e)return{ok:!1,error:"OPENROUTER_API_KEY not set \u2014 add a key first"};if(!n)return{ok:!1,error:"no model given"};if(md(n))return{ok:!1,error:"Anthropic model \u2014 not offered or probed via OpenRouter"};let t=Date.now(),r=Array(350).fill("Caching probe filler sentence; its only purpose is to exceed the prompt-cache minimum token threshold.").join(" "),s={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":"2023-06-01"},i={model:n,max_tokens:64,system:[{type:"text",text:r,cache_control:{type:"ephemeral"}}],messages:[{role:"user",content:"Reply with exactly: ok"}]},o=async a=>{let l=new AbortController,c=setTimeout(()=>l.abort(),2e4);try{let d=JSON.stringify(a?{...i,provider:Vy(a)}:i),u=await fetch(hd,{method:"POST",signal:l.signal,headers:s,body:d}),f=await u.json().catch(()=>({}));return{r:u,j:f}}finally{clearTimeout(c)}};try{let{r:a,j:l}=await o();if(!a.ok){let A=l?.error?.message||l?.message||JSON.stringify(l).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:AP(a.status,A),restriction:TP(A)}}let c=typeof l?.provider=="string"?l.provider:void 0,d=l?.content?.find?.(A=>A.type==="text")?.text??l?.content?.[0]?.text??"ok",u=fd(l?.usage?.cache_creation_input_tokens),{r:f,j:p}=await o(c),{works:m,read:h,note:b}=OP(f.ok,p?.usage,c);return m===!0&&c&&(gd[n]=c,Ge===n&&(dn=c)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:c,sample:String(d).trim().slice(0,60),cache:{works:m,created:u,read:h,note:b}}}catch(a){let l=Y(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(l)?"timed out (20s)":l}}}var rP,hd,sP,iP,Wy,oP,dd,ta,na,Qo,md,er,un,Ge,dn,ys,bs,ws,gd,fd,Vy,Zy,eb=v(()=>{"use strict";zn();$t();rP="https://openrouter.ai/api",hd=`${rP}/v1/messages`,sP="typebulb-proxy-managed",iP="The typebulb model override was reverted to Anthropic, but this Claude Code session still points at the now-idle proxy. Reload the window (VS Code/Cursor: \u201CDeveloper: Reload Window\u201D) or relaunch `claude` in a terminal to return to your Anthropic subscription.",Wy=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],oP=5e3,dd=["low","medium","high"],ta=n=>ea(n,".claude","settings.local.json"),na=n=>ea(n,".claude",".cc-switcher.json"),Qo=n=>`http://127.0.0.1:${n}`;md=n=>/^anthropic\//i.test(n)||/claude/i.test(n),er=null,un=null,Ge=null,dn=null,ys=null,bs="unknown",ws=1,gd={},fd=n=>typeof n=="number"?n:0,Vy=n=>({order:[n],allow_fallbacks:!1});Zy=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=Mt(na(z)),t=e?.active?.model;if(!t)return;let s=(Mt(ta(z))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Qy(t,e.active.provider??gd[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${Qo(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",Y(e))}})()});var nb={};Ea(nb,{attach:()=>MP,blockToMarkdown:()=>Di,breakout:()=>Gu,capText:()=>we,cleanUserText:()=>kt,clearSwitchModel:()=>kP,composerPasteRead:()=>BP,displayName:()=>CP,downloadSample:()=>od,firstLineDigest:()=>$e,git:()=>Je,gitChangedFiles:()=>Uu,gitDiff:()=>qu,info:()=>RP,isHiddenTurn:()=>Ur,launchBulb:()=>td,listBreakouts:()=>Xu,listBulbFiles:()=>Zu,listMyBulbs:()=>ld,listSamples:()=>id,listSessions:()=>IP,listSwitchModels:()=>bP,logInlineStatus:()=>NP,openFile:()=>zu,poll:()=>_P,predictTrustOf:()=>nd,probeModel:()=>PP,pullRemoteBulb:()=>cd,pushLocalBulb:()=>ud,readBulbLog:()=>sd,repoRoot:()=>an,saveOpenRouterKey:()=>xP,searchBulbs:()=>ed,searchSessions:()=>$P,sessionPeek:()=>LP,setBulbTrust:()=>rd,setReasoning:()=>SP,setSwitchModel:()=>vP,shutdownSwitcher:()=>EP,stopBreakout:()=>Qu,switchState:()=>wP,toolResultDigest:()=>Pc});var tb,CP,RP,_P,NP,IP,$P,LP,MP,BP,rb=v(()=>{"use strict";zo();ji();Xo();hs();eb();ji();Fr();tb=new On,CP=tb.displayName,{info:RP,poll:_P,logInlineStatus:NP,listSessions:IP,searchSessions:$P,sessionPeek:LP,attach:MP,composerPasteRead:BP}=Zn(tb)});var ib={};Ea(ib,{attach:()=>HP,breakout:()=>Gu,composerPasteRead:()=>WP,displayName:()=>DP,downloadSample:()=>od,git:()=>Je,gitChangedFiles:()=>Uu,gitDiff:()=>qu,info:()=>jP,launchBulb:()=>td,listBreakouts:()=>Xu,listBulbFiles:()=>Zu,listMyBulbs:()=>ld,listSamples:()=>id,listSessions:()=>qP,logInlineStatus:()=>UP,openFile:()=>zu,poll:()=>FP,predictTrustOf:()=>nd,pullRemoteBulb:()=>cd,pushLocalBulb:()=>ud,readBulbLog:()=>sd,repoRoot:()=>an,searchBulbs:()=>ed,searchSessions:()=>JP,sessionPeek:()=>KP,setBulbTrust:()=>rd,stopBreakout:()=>Qu});var sb,DP,jP,FP,UP,qP,JP,KP,HP,WP,ob=v(()=>{"use strict";zo();Rc();Xo();hs();sb=new Pn,DP=sb.displayName,{info:jP,poll:FP,logInlineStatus:UP,listSessions:qP,searchSessions:JP,sessionPeek:KP,attach:HP,composerPasteRead:WP}=Zn(sb)});import{readFileSync as YP,writeFileSync as VP,mkdirSync as zP}from"fs";import{homedir as GP}from"os";import*as ra from"path";async function cb(){try{let n=await fetch(new URL("/api/tags",lb()).toString(),{signal:AbortSignal.timeout(XP)});return n.ok?((await n.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function ub(n){let e;try{e=YP(n,"utf-8")}catch{return{json:void 0,unreadable:!1}}try{let t=JSON.parse(e);if(t&&typeof t=="object"&&!Array.isArray(t)){let r=t;return{json:r,unreadable:"providers"in r&&!yd(r)}}}catch{}return{json:void 0,unreadable:!0}}function yd(n){let e=n?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function QP(n){let e=yd(n);if(!e||!("ollama"in e))return null;let t=e.ollama?.models;return Array.isArray(t)?t.map(r=>r?.id).filter(r=>typeof r=="string"):[]}async function db(){let{json:n,unreadable:e}=ub(ab());return e?{installed:[],configured:null}:{installed:await cb(),configured:QP(n)}}async function fb(){let n=await cb();return n.length?ZP(ab(),n,lb()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function ZP(n,e,t){let{json:r,unreadable:s}=ub(n);if(s)return{ok:!1,error:`could not parse ${n} \u2014 edit the ollama provider there yourself`};let i={...r??{},providers:{...yd(r)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{zP(ra.dirname(n),{recursive:!0}),VP(n,JSON.stringify(i,null,2)+`
|
|
1638
|
+
`)}catch(o){return{ok:!1,error:`could not write ${n}: ${Y(o)}`}}return{ok:!0,count:e.length}}var XP,ab,lb,pb=v(()=>{"use strict";$t();zn();XP=1500,ab=()=>ra.join(GP(),".pi","agent","models.json"),lb=()=>Fn(process.env.OLLAMA_HOST??"http://localhost:11434")});var mb={};Ea(mb,{attach:()=>aC,breakout:()=>Gu,composerFiles:()=>dC,composerNew:()=>uC,composerPaste:()=>hC,composerPasteRead:()=>mC,composerRpc:()=>pC,composerSend:()=>lC,composerStop:()=>cC,composerUiRespond:()=>fC,displayName:()=>eC,downloadSample:()=>od,git:()=>Je,gitChangedFiles:()=>Uu,gitDiff:()=>qu,info:()=>tC,launchBulb:()=>td,listBreakouts:()=>Xu,listBulbFiles:()=>Zu,listMyBulbs:()=>ld,listSamples:()=>id,listSessions:()=>sC,logInlineStatus:()=>rC,ollamaOffer:()=>db,ollamaSync:()=>fb,openFile:()=>zu,poll:()=>nC,predictTrustOf:()=>nd,pullRemoteBulb:()=>cd,pushLocalBulb:()=>ud,readBulbLog:()=>sd,repoRoot:()=>an,searchBulbs:()=>ed,searchSessions:()=>iC,sessionPeek:()=>oC,setBulbTrust:()=>rd,shutdownComposer:()=>gC,stopBreakout:()=>Qu});var hb,eC,tC,nC,rC,sC,iC,oC,aC,lC,cC,uC,dC,fC,pC,hC,mC,gC,gb=v(()=>{"use strict";zo();ju();Xo();hs();pb();hb=new Xn,eC=hb.displayName,{info:tC,poll:nC,logInlineStatus:rC,listSessions:sC,searchSessions:iC,sessionPeek:oC,attach:aC,composerSend:lC,composerStop:cC,composerNew:uC,composerFiles:dC,composerUiRespond:fC,composerRpc:pC,composerPaste:hC,composerPasteRead:mC,shutdownComposer:gC}=Zn(hb)});import*as Cw from"fs/promises";import*as ut from"path";Rs();ne();function xc(n){if(!_e.includes(n))throw new Error(`Unknown block kind '${n}' (one of: ${_e.join(", ")})`);return n}function km(n){let e=[];for(let t of n){let r=t.indexOf("=");if(r<=0||r===t.length-1)throw new Error(`Expected <kind>=<source>, got '${t}' (e.g. data=results.json, or data=- for stdin)`);let s=xc(t.slice(0,r));if(e.some(i=>i.kind===s))throw new Error(`Duplicate block kind '${s}' \u2014 each block can be written once per invocation`);e.push({kind:s,source:t.slice(r+1)})}if(e.filter(t=>t.source==="-").length>1)throw new Error("Only one <kind>=- can read stdin");return e}ji();Rc();ju();var sa={claude:{adapter:()=>new On,server:()=>Promise.resolve().then(()=>(rb(),nb))},codex:{adapter:()=>new Pn,server:()=>Promise.resolve().then(()=>(ob(),ib))},pi:{adapter:()=>new Xn,server:()=>Promise.resolve().then(()=>(gb(),mb))}};function yb(n){return n in sa}function tr(){return Object.keys(sa)}function bb(){return Object.fromEntries(Object.entries(sa).map(([n,e])=>[n,e.adapter]))}function wb(n){return sa[n].server()}var vs=bb();function vb(){for(let n of Object.values(vs))try{n().ensureHarnessSupport()}catch{}}function fn(){for(let n of Object.keys(vs))try{if(vs[n]().detectsSelf())return n}catch{}}function Sb(n){let e=tr(),t=new Map(e.filter(i=>vs[i]).map(i=>[i,vs[i]()]));for(let[i,o]of t)if(o.detectsSelf())return{name:i};let r=[...t].filter(([,i])=>i.detectsInstalled()).map(([i])=>i);if(r.length===0)return{name:e[0]};if(r.length===1)return{name:r[0]};let s=i=>t.get(i).listSessionFiles(n).length>0;return{ambiguous:[...r].sort((i,o)=>Number(s(o))-Number(s(i)))}}var wd=5e3;function bd(n){try{return n()}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}}function kb(n){let t={subcommand:"run",file:"",watch:!0,open:!(process.env.TERM_PROGRAM==="vscode"||fn()!==void 0),server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},r=["call","check","predict","logs","wait","stop","trust","untrust","models","slug","send","pull","push","get","put"],s=n[0];if(s==="agent"||s?.startsWith("agent:")){t.subcommand="agent";let o=s.indexOf(":");if(o!==-1){let a=s.slice(o+1);a&&(t.agentTarget=a)}n=n.slice(1)}else s&&r.includes(s)&&(t.subcommand=s,n=n.slice(1));let i=[];for(let o=0;o<n.length;o++){let a=n[o];if(a==="--help"||a==="-h")t.help=!0;else if(a==="--version"||a==="-V")t.version=!0;else if(a==="--no-watch")t.watch=!1;else if(a==="--open")t.open=!0;else if(a==="--no-open")t.open=!1;else if(a==="--server")t.server=!0;else if(a==="--trust")t.trust=!0;else if(a==="--no-trust")t.noTrust=!0;else if(a==="--force")t.force=!0;else if(a==="--mode"){let l=n[++o];(!l||l.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=l}else if(a==="--batch"){let l=n[++o];(!l||l.startsWith("-"))&&(console.error("Missing value for --batch (a batch name, e.g. --batch pilot)"),process.exit(1));let c=l.replace(/[\\/]+$/,"");(!c||/[\\/]/.test(c)||c==="."||c==="..")&&(console.error(`Invalid --batch value: ${l} (a single folder name \u2014 no path separators or dot segments)`),process.exit(1)),t.batch=c}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let l=n[++o];if(l==="latest")t.run="latest";else{let c=parseInt(l,10);(isNaN(c)||c<1)&&(console.error(`Invalid --run value: ${l} (a run number, or 'latest')`),process.exit(1)),t.run=c}}else if(a==="--bulbs")t.stopScope="bulbs";else if(a==="--agent")t.stopScope="agent";else if(a==="--global")t.stopScope="global";else if(a==="--match"){let l=n[++o];l===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=l}else if(a==="--timeout"){let l=parseInt(n[++o],10);(isNaN(l)||l<=0)&&(console.error(`Invalid --timeout value: ${n[o]} (seconds)`),process.exit(1)),t.timeoutSec=l}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let l=parseInt(a.slice(7),10);(isNaN(l)||l<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=l}else t.sendWaitMs=wd;else if(a==="--lines"||a==="-n"){let l=parseInt(n[++o],10);(isNaN(l)||l<0)&&(console.error(`Invalid --lines value: ${n[o]}`),process.exit(1)),t.lines=l}else if(a==="--port"||a==="-p"){let l=n[++o],c=parseInt(l,10);isNaN(c)&&(console.error(`Invalid port: ${l}`),process.exit(1)),t.port=c}else if(a==="--replace"||a.startsWith("--replace=")){let l=a.startsWith("--replace=")?a.slice(10):n[++o]??"",c=bd(()=>Hd(l));t.local&&(console.error(`--replace can only be used once (got '${t.local.name}' and '${c.name}')`),process.exit(1)),t.local=c}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let l=a.startsWith("--args=")?a.slice(7):n[++o];l===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=l}else if(!a.startsWith("-"))["call","send","get","put","slug"].includes(t.subcommand)?i.push(a):t.file=a;else{let l=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${l}`),process.exit(1)}}return t.subcommand==="call"&&(i.length<2&&(console.error("Usage: typebulb call <file> <fn> [arg\u2026]"),process.exit(1)),t.file=i[0],t.fn=i[1],t.callArgs=i.slice(2)),t.subcommand==="send"&&(i.length<1&&(console.error("Usage: typebulb send <file> [message]"),process.exit(1)),t.file=i[0],t.sendMessage=i[1]),t.subcommand==="slug"&&(i.length||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1)),t.slugName=i.join(" ")),t.subcommand==="get"&&(i.length!==2&&(console.error("Usage: typebulb get <file> <kind>"),process.exit(1)),t.file=i[0],t.blockKind=bd(()=>xc(i[1]))),t.subcommand==="put"&&(i.length<2&&(console.error("Usage: typebulb put <file> <kind>=<source> [<kind>=<source> \u2026]"),process.exit(1)),t.file=i[0],t.blockPairs=bd(()=>km(i.slice(1)))),t}function xb(){console.log(`
|
|
1611
1639
|
typebulb - Local bulb runner for Typebulb
|
|
1612
1640
|
|
|
1613
1641
|
Usage:
|
|
@@ -1653,6 +1681,8 @@ Usage:
|
|
|
1653
1681
|
the outline names; 'tb:set \u2026 = <value>' fills
|
|
1654
1682
|
a form control. Both gestures reply with a
|
|
1655
1683
|
fresh snapshot and need exactly one page open.
|
|
1684
|
+
'tb:theme dark|light' flips the theme for a
|
|
1685
|
+
probe (bare clears); transient, never saved.
|
|
1656
1686
|
typebulb get <file> <kind> Print one block's content to stdout (kind: code,
|
|
1657
1687
|
css, html, data, infer, insight, config, notes).
|
|
1658
1688
|
No content (absent or empty): exit 2;
|
|
@@ -1801,11 +1831,11 @@ Examples:
|
|
|
1801
1831
|
insight<T = unknown>(): T | undefined;`,Eb=`options: {
|
|
1802
1832
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
1803
1833
|
system?: string;
|
|
1804
|
-
/** Reasoning effort: 0=minimal, 1=low, 2=med, 3=high. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking level, Anthropic adaptive thinking). 0 reaches the vendor's explicit off switch, and floors to a little thinking only on always-thinking models. Pin 1 (low) for most work; pick 0 deliberately, when you want the raw model or latency is the constraint. Omitting is NOT off \u2014 it buys the model's own default (medium on GPT-5.6), which reasons and bills invisibly. Ignored on the courtesy model, which runs at the level Typebulb sets. */
|
|
1805
|
-
effort?: 0 | 1 | 2 | 3;
|
|
1834
|
+
/** Reasoning effort: 0=minimal, 1=low, 2=med, 3=high, 4=xhigh. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking level, Anthropic adaptive thinking). 0 reaches the vendor's explicit off switch, and floors to a little thinking only on always-thinking models. 4 reaches the rung above high where the vendor has one (OpenAI/OpenRouter xhigh, Anthropic max) and clamps to high where it doesn't (Gemini) \u2014 never an error. Pin 1 (low) for most work; pick 0 deliberately, when you want the raw model or latency is the constraint. Omitting is NOT off \u2014 it buys the model's own default (medium on GPT-5.6), which reasons and bills invisibly. Ignored on the courtesy model, which runs at the level Typebulb sets. */
|
|
1835
|
+
effort?: 0 | 1 | 2 | 3 | 4;
|
|
1806
1836
|
provider?: string;
|
|
1807
1837
|
model?: string;
|
|
1808
|
-
/**
|
|
1838
|
+
/** Give the model a web-search tool, billed to the user's key. Off by default; the free model never searches. */
|
|
1809
1839
|
webSearch?: boolean;
|
|
1810
1840
|
/** Abort the request. On abort the promise rejects / the stream ends. */
|
|
1811
1841
|
signal?: AbortSignal;
|
|
@@ -1831,7 +1861,7 @@ type AiAccess = "own" | "courtesy" | "none";
|
|
|
1831
1861
|
* Streaming counterpart of \`tb.ai()\`. Yields \`{ kind: "text" | "reasoning", text }\` deltas
|
|
1832
1862
|
* as they arrive; break the loop (or abort \`signal\`) to cancel and stop the upstream.
|
|
1833
1863
|
*
|
|
1834
|
-
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-
|
|
1864
|
+
* \`kind: "reasoning"\` deltas only arrive when you pass \`effort: 1-4\` AND use a
|
|
1835
1865
|
* thinking-capable model; otherwise the stream is \`text\`-only.
|
|
1836
1866
|
*
|
|
1837
1867
|
* @example
|