typebulb 0.56.0 → 0.56.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/SKILL.md +2 -2
- package/dist/agents/claude/client.js +42 -42
- package/dist/agents/codex/client.js +41 -41
- package/dist/agents/pi/client.js +198 -198
- package/dist/index.js +78 -78
- package/dist/render.js +21 -21
- package/dist/resolver/semver.d.ts +2 -0
- package/dist/resolver/semver.d.ts.map +1 -1
- package/dist/resolver/semver.js +5 -1
- package/dist/resolver/semver.js.map +1 -1
- package/dist/resolver/versionResolver.d.ts.map +1 -1
- package/dist/resolver/versionResolver.js +6 -4
- package/dist/resolver/versionResolver.js.map +1 -1
- package/dist/servers.js +11 -11
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -248,7 +248,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
248
248
|
`),c=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||c.length){let u=Date.parse(e.timestamp??""),d=!isNaN(u)&&u>=t;r.push({type:"assistant",text:o,thinking:a,tools:c,live:d})}let l=e.message?.usage??e.usage,f=l&&{in:l.input_tokens??0,out:l.output_tokens??0,cached:l.cache_read_input_tokens??0,cacheCreate:l.cache_creation_input_tokens??0};return{events:r,usage:f,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(l=>l&&l.type==="text").map(l=>l.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(l=>l&&l.type==="tool_result"))&&a.trim()&&Tt(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 c of a)c.type==="tool_result"&&c.tool_use_id&&i.add(c.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return tA(e)}readPreview(e){return eA(e)}searchText(e){if(!e||Qr(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,r="";if(typeof t=="string")r=Tt(t);else if(Array.isArray(t)){let s=t;r=e.type==="user"?s.map(ql).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 nA,readdirSync as rA,openSync as sA,readSync as iA,closeSync as oA,existsSync as aA}from"fs";import{basename as cA,join as Wl,resolve as lA}from"path";import{homedir as Xm}from"os";function dA(n){let e=n.trimStart();return uA.some(t=>e.startsWith(t))}function es(n,e){return Array.isArray(n)?n.map(t=>typeof t?.text=="string"?e&&dA(t.text)?"":ve(t.text):t?.type==="input_image"&&typeof t.image_url=="string"&&t.image_url.startsWith("data:")?``:"").filter(Boolean).join(`
|
|
249
249
|
`):""}function fA(n){return typeof n=="string"?ve(n):es(n,!1)}function pA(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 hA(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 Zm(n,e){let t;try{t=sA(n,"r")}catch{return}try{let r=Buffer.alloc(e),s=iA(t,r,0,e,0);return{text:r.subarray(0,s).toString("utf8"),bytes:s}}finally{oA(t)}}function mA(n){let t=Zm(n,65536);if(t===void 0)return;let r=t.text.indexOf(`
|
|
250
250
|
`);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 uA,Qm,Ln,Hl=S(()=>{"use strict";Xr();Xi();uA=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<user_instructions>"];Qm=n=>{let e=lA(n);return process.platform==="win32"?e.toLowerCase():e},Ln=class extends At{constructor(t=Wl(Xm(),".codex","sessions")){super();this.root=t}displayName="Codex Mirror";#e=0;#s;#t=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}detectsInstalled(){return aA(Wl(Xm(),".codex"))}sessionsDir(t){return this.root}listSessionFiles(t){let r=Qm(t),s=[];for(let i of this.#r()){let o;try{let c=nA(i);if(!c.isFile())continue;o=c.mtimeMs}catch{continue}let a=this.#t.get(i);if(a===void 0){if(a=mA(i),a===void 0)continue;this.#t.set(i,a)}Qm(a)===r&&s.push({sessionId:cA(i,".jsonl"),file:i,mtime:o})}return s}#r(){let t=[],r=s=>{try{return rA(s).map(i=>Wl(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.#s,this.#s=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=es(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=es(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=es(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"?pA(i.input):hA(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=fA(i.output);return s.push({type:"tool_result",id:i.call_id??"",content:a,isError:!1,digest:Le(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 c={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:c}}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(Zm(t,256*1024)?.text??"").split(`
|
|
251
|
-
`))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"?"":es(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as gA}from"fs";import{createHash as yA}from"crypto";import{join as eo,resolve as bA}from"path";import{homedir as wA}from"os";function Ot(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?eo(n,".."):eo(wA(),".typebulb")}function nt(){eg||(eg=!0,console.error(`${Ot()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function rt(){return process.env.TYPEBULB_SERVERS_DIR||eo(Ot(),"servers")}function tg(n){let e=ae(n),t=yA("sha1").update(e).digest("hex").slice(0,8),r=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return eo(Ot(),"canvas",`${r}-${t}.png`)}function ae(n){let e=bA(n),t=e;try{t=gA.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function ng(n,e){let t=ae(n),r=ae(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var eg,Pt=S(()=>{"use strict";eg=!1});var Be,to=S(()=>{"use strict";Be="0.56.
|
|
251
|
+
`))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"?"":es(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as gA}from"fs";import{createHash as yA}from"crypto";import{join as eo,resolve as bA}from"path";import{homedir as wA}from"os";function Ot(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?eo(n,".."):eo(wA(),".typebulb")}function nt(){eg||(eg=!0,console.error(`${Ot()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function rt(){return process.env.TYPEBULB_SERVERS_DIR||eo(Ot(),"servers")}function tg(n){let e=ae(n),t=yA("sha1").update(e).digest("hex").slice(0,8),r=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return eo(Ot(),"canvas",`${r}-${t}.png`)}function ae(n){let e=bA(n),t=e;try{t=gA.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function ng(n,e){let t=ae(n),r=ae(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var eg,Pt=S(()=>{"use strict";eg=!1});var Be,to=S(()=>{"use strict";Be="0.56.1"});import{spawn as rg}from"child_process";import{readdir as vA,readFile as ig,writeFile as og,unlink as Yl,mkdir as SA}from"fs/promises";import{mkdirSync as ag,writeFileSync as no,appendFileSync as kA,readFileSync as Vl}from"fs";import*as Se from"path";import{fileURLToPath as xA}from"url";function zl(n){return Se.join(rt(),`${n}.json`)}function ns(n){return Se.join(rt(),`${n}.log`)}function Gl(n){return Se.join(rt(),`${n}.wait.json`)}function cg(n){try{let e=JSON.parse(Vl(Gl(n),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function Xl(n,e=""){let t=cg(n)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ro(n,e,t=""){try{ag(rt(),{recursive:!0});let r=cg(n);r[t]=e,no(Gl(n),JSON.stringify({cursors:r}))}catch{}}function so(n){let e=ns(n);try{ag(rt(),{recursive:!0}),no(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 c=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(kA(e,c),s+=c.length,s>2*sg){let l=Vl(e),f=l.subarray(Math.max(0,l.length-sg));no(e,f),s=f.length}}catch{i=!0}};return process.stdout.write=((a,...c)=>(o(a),t(a,...c))),process.stderr.write=((a,...c)=>(o(a),r(a,...c))),()=>{process.stdout.write=t,process.stderr.write=r}}function lg(n){try{no(ns(n),"")}catch{}}function Ye(n,e=0){try{let t=Vl(ns(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 Ql(n){return`\u2500\u2500 run ${n} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function AA(n){let e=EA.exec(n);return e?Number(e[1]):void 0}function ug(n,e){let t=n.split(`
|
|
252
252
|
`),r=[];if(t.forEach((o,a)=>{let c=AA(o);c!==void 0&&r.push({id:c,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(`
|
|
253
253
|
`)}function Zl(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function dg(n){try{await SA(rt(),{recursive:!0}),await og(zl(n.pid),JSON.stringify({version:Be,...n}))}catch{nt()}}async function fg(n,e){let t=zl(n);try{let r=JSON.parse(await ig(t,"utf8"));if(r.denied===e)return;r.denied=e,await og(t,JSON.stringify(r))}catch{}}async function ts(n){await Yl(zl(n)).catch(()=>{}),await Yl(ns(n)).catch(()=>{}),await Yl(Gl(n)).catch(()=>{})}function rs(n,e){return n.agent!=null&&n.cwd!=null&&ae(n.cwd)===ae(e)}function pg(n,e){return n.agent==null&&ng(n.file,e)}async function Q(n){let e;try{e=await vA(rt())}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 ig(Se.join(rt(),s),"utf8"))}catch{await ts(i);return}o&&typeof o.pid=="number"&&Zl(o.pid)?t.push(o):await ts(i)})),(n?t.filter(s=>pg(s,n)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function eu(n,e){return(await Q()).find(t=>rs(t,n)&&(e?t.agent===e:!0))}async function hg(n,e){let t=new URL(n).port,r=(await Q()).filter(a=>String(a.port)!==t),s=r.filter(a=>rs(a,e)),i=r.filter(a=>pg(a,e)),o=0;for(let a of[...s,...i])try{let c=await fetch(`${a.url}/__open`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n}),signal:AbortSignal.timeout(2e3)});if(!c.ok)continue;let{opened:l,pages:f}=await c.json();if(l)return{where:"editor",via:a.agent?"the agent mirror":`${Se.basename(a.file)}'s page`};a.agent!=null&&(o+=f??0)}catch{}return o>0?{where:"external"}:void 0}async function Xt(n){try{process.kill(n,"SIGTERM")}catch{}await ts(n)}function Mn(n,e){let t=ae(e);return n.filter(r=>r.agent==null&&r.pid!==process.pid&&ae(r.file)===t)}async function tu(n){let e=Mn(await Q(),n);for(let t of e)await Xt(t.pid);return e}function OA(n,e,t){(process.platform==="win32"?rg("cmd",["/c","start","","/b",n,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):rg(n,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function ss(){return Se.join(Se.dirname(xA(import.meta.url)),"index.js")}function PA(n,e={}){return{command:process.execPath,args:[ss(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],n,...e.open===!1?["--no-open"]:[]]}}function CA(n){return{command:process.execPath,args:[ss(),`agent:${n}`,"--no-open"]}}async function mg(n,e,t,r){let s=await n();if(s)return s;OA(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await TA(150);let o=await n();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function io(n,e={}){let t=e.cwd??process.cwd(),r=Se.resolve(t,n),[s]=await tu(r),i={...e,batch:e.batch??s?.batch,mode:e.mode??s?.mode};return mg(async()=>Mn(await Q(),r)[0],PA(n,i),t,Se.basename(n))}async function gg(n,e=process.cwd()){return mg(()=>eu(e,n),CA(n),e,`the ${n} mirror`)}var sg,EA,TA,Ae=S(()=>{"use strict";Pt();to();sg=1e6;EA=/^── run (\d+) ── /;TA=n=>new Promise(e=>setTimeout(e,n))});function Bn(n){return{...kf(n),server:n.files.get("server.ts")??""}}function oo(n){return!!n.server&&!n.code}var is=S(()=>{"use strict";ee();ee()});function ao(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 nu(n){return In(ao(n)??"bulb")||"bulb"}var ru=S(()=>{"use strict";ee()});import{transform as _A}from"sucrase";function su(n,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=_A(n,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var yg=S(()=>{});function iu(n){let e=n.split(""),t=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
|
|
254
254
|
`&&(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]!==`
|
|
@@ -429,8 +429,8 @@ const something = require('module-name') // NOT SUPPORTED!
|
|
|
429
429
|
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var Qt,Zt,IA,NA,co=S(()=>{wg();Qt=["client"],Zt=["client","server"],IA=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:Qt},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:Zt},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:Qt},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:Qt},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:Qt},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:Zt},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:Zt},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:Zt},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:Zt},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:Zt},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:Zt},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:Qt},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:Qt},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:Qt}],NA=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function DA(n){return n.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
430
430
|
`)[0]}`).join(`
|
|
431
431
|
`)}function kg(n,e){let t=os(n,{target:"client",dependencies:e}).filter(r=>r.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
432
|
-
${DA(t)}`)}var xg=S(()=>{"use strict";co()});var Ct,as,ou,cs=S(()=>{Ct="https://esm.sh",as="https://cdn.jsdelivr.net/npm/",ou="https://data.jsdelivr.com/v1/package/npm/"});function Eg(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D,Dn,Ag,ls=S(()=>{cs();D=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=Dn(t??s.version),this.subpath=Dn(r??s.subpath)}static parse(e){let t=Eg(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Ag(t[1]??""),a=Dn(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Ag(t[0]),o=Dn(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(Ct).host,s=new URL(as).host;if(t.host===r){let i=Eg(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:Dn(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},Dn=n=>n&&n.length?n:void 0,Ag=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),Dn(n.slice(e+1))]}});async function be(n){try{return await n()}catch{return}}var lo=S(()=>{});function en(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function au(n){return n.startsWith("./")?n:`./${n}`}var us,cu=S(()=>{ls();lo();cs();us=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 D(e):e;return`${as}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(en(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(",")),`${Ct}/${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),`${Ct}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await be(()=>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 be(()=>this.http.getJson(`${ou}${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=D.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:f,peerDependencies:u,peerDependenciesMeta:d}=r;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await be(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var Tg,ds,lu,jA,fs,uo=S(()=>{Tg=n=>n.startsWith("@types/"),ds=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!Tg(e)),lu=n=>Object.keys(n?.dependencies||{}).filter(e=>!Tg(e)),jA=n=>ds(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),fs=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 jA(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),c=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>ds(i.meta))),r=new Map;for(let i of e)for(let o of lu(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:ds(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var ps,uu=S(()=>{ls();lo();ps=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await be(()=>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 be(()=>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 be(()=>this.cdn.fetchVersionsIndex(e));if(a?.versions?.length){let c=await s(this.semver.selectBestVersion(a.versions,{range:t,distTags:a.distTags}));if(c)return c}}}return s(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let r=new D(e),s=r.root(),i=t[s],o=i?await be(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as FA,parse as UA}from"es-module-lexer";var jn,du=S(()=>{ls();cs();uo();jn=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))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,r=s=>{D.isBare(s)&&t.add(s)};try{await FA;let[s]=UA(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(D.rootOf(u))),i=[...new Set(s.map(D.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,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 y=s.get(D.rootOf(p));return new D(p).withVersion(y.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),h=s.get(y),{isPeerRoot:g,hasPeers:x,isSharedDep:v}=r.get(y),P=a.has(y),_=p!==y,I=!(g||v)&&(P||!x),M=this.singletonDepsOf(h,o),A=_&&f.has(y);A&&u.add(y);let j=A?[...M,y]:M.length?M:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:I,external:j})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${Ct}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...ds(e.meta),...lu(e.meta)])].filter(r=>t.has(r))}};jn.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as Og,satisfies as qA,maxSatisfying as Pg,major as JA,valid as KA}from"semver";var fo,tn,fu=S(()=>{fo=class{cmp(e,t){return e===t?0:Og(e,t)?1:Og(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!qA(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=Pg(e,r,{includePrerelease:!1});if(a)return a}return Pg(e,r,{includePrerelease:!0})??void 0}majorOf(e){return JA(e)}isExactVersion(e){return KA(e)!==null}},tn=new fo});function WA(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var nn,Cg=S(()=>{lo();nn=class{constructor(e){this.store=e}async isNegative(e){let t=await be(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await be(()=>this.store.get(e)))?.attempts||0)+1;await be(()=>this.store.set(e,{until:Date.now()+WA(r),attempts:r}))}async clearNegative(e){await be(()=>this.store.delete(e))}}});function _g(n,e){let t=new us(n,e),r=new fs(t),s=new ps(n,t,tn);return{packageService:new jn(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var st=S(()=>{cu();uo();uu();du();fu();ls();fu();cs();cu();uo();uu();du();Cg()});import*as pu from"fs/promises";import*as Rg from"crypto";function De(n){return Rg.createHash("sha1").update(n).digest("hex")}async function it(n){try{return JSON.parse(await pu.readFile(n,"utf8"))}catch{return}}async function po(n){try{return await pu.readFile(n,"utf8")}catch{return}}var Fn=S(()=>{"use strict"});import*as Rt from"fs/promises";import*as ot from"path";import*as Ng from"os";function te(){return hu||(hu=YA().catch(()=>nt())),hu}function mo(n,e){return ot.join(HA,De(n),e)}async function YA(){await Rt.mkdir(_t,{recursive:!0});let n=ot.join(_t,"version.json");if((await it(n))?.version===Ig)return;let t=await Rt.readdir(_t).catch(()=>[]);await Promise.all(t.map(r=>Rt.rm(ot.join(_t,r),{recursive:!0,force:!0}))),await Rt.writeFile(n,JSON.stringify({version:Ig})+`
|
|
433
|
-
`,"utf8")}var Ig,_t,hs,ms,ho,
|
|
432
|
+
${DA(t)}`)}var xg=S(()=>{"use strict";co()});var Ct,as,ou,cs=S(()=>{Ct="https://esm.sh",as="https://cdn.jsdelivr.net/npm/",ou="https://data.jsdelivr.com/v1/package/npm/"});function Eg(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D,Dn,Ag,ls=S(()=>{cs();D=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=Dn(t??s.version),this.subpath=Dn(r??s.subpath)}static parse(e){let t=Eg(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Ag(t[1]??""),a=Dn(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Ag(t[0]),o=Dn(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(Ct).host,s=new URL(as).host;if(t.host===r){let i=Eg(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:Dn(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},Dn=n=>n&&n.length?n:void 0,Ag=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),Dn(n.slice(e+1))]}});async function be(n){try{return await n()}catch{return}}var lo=S(()=>{});function en(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function au(n){return n.startsWith("./")?n:`./${n}`}var us,cu=S(()=>{ls();lo();cs();us=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 D(e):e;return`${as}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(en(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(",")),`${Ct}/${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),`${Ct}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await be(()=>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 be(()=>this.http.getJson(`${ou}${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=D.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:f,peerDependencies:u,peerDependenciesMeta:d}=r;return{name:e,version:t,dependencies:f,peerDependencies:u,peerDependenciesMeta:d}}let s=this.packageJson(new D(`${e}@${t}`)),i=await be(()=>this.http.getJson(s));if(!i)return;let o=f=>f&&Object.keys(f).length?f:void 0,a=o(i.dependencies),c=o(i.peerDependencies),l=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,c,l),{name:e,version:t,dependencies:a,peerDependencies:c,peerDependenciesMeta:l}}}});var Tg,ds,lu,jA,fs,uo=S(()=>{Tg=n=>n.startsWith("@types/"),ds=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!Tg(e)),lu=n=>Object.keys(n?.dependencies||{}).filter(e=>!Tg(e)),jA=n=>ds(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),fs=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 jA(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),c=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:c})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>ds(i.meta))),r=new Map;for(let i of e)for(let o of lu(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:ds(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var ps,uu=S(()=>{ls();lo();ps=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await be(()=>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=a=>!this.semver.isRange(t)||this.semver.satisfies(t,a),s=await this.cache.getPinnedExact(e,t);if(s){if(this.semver.isExactVersion(s)&&r(s))return s;console.debug("[typebulb] cached version for",e,"is not exact or not in",t,"(",s,"); re-resolving from registry")}let i=async a=>{if(a&&this.semver.isExactVersion(a)&&r(a))return await this.cache.setPinnedExact(e,t,a),a},o=await be(()=>this.cdn.fetchVersionsIndex(e));if(o?.versions?.length){let a=this.semver.selectBestVersion(o.versions,{range:t,distTags:o.distTags});if(a){let c=await i(a);if(c)return c}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 c=await be(()=>this.cdn.fetchVersionsIndex(e));if(c?.versions?.length){let l=await i(this.semver.selectBestVersion(c.versions,{range:t,distTags:c.distTags}));if(l)return l}}}return i(await this.cdn.resolveExactVersion(`${e}@${t}`))}async effectivePackage(e,t){let r=new D(e),s=r.root(),i=t[s],o=i?await be(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as FA,parse as UA}from"es-module-lexer";var jn,du=S(()=>{ls();cs();uo();jn=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))D.isBare(s[1])&&t.add(s[1])}return Array.from(t)}async extractImports(e){let t=new Set,r=s=>{D.isBare(s)&&t.add(s)};try{await FA;let[s]=UA(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(D.rootOf(u))),i=[...new Set(s.map(D.rootOf))],o=await Promise.all(i.map(async u=>({name:u,version:await this.resolveVersion(u,t)}))),{allRoots:a,flags:c,autoAddedPeers:l}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),f=this.buildEntries([...s,...l.map(u=>u.name)],a,c);return{importMap:{imports:Object.fromEntries(f)},prefetchUrls:f.map(([,u])=>u)}}async resolveVersion(e,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 y=s.get(D.rootOf(p));return new D(p).withVersion(y.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),c=[],l=new Set,f=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let y=D.rootOf(p),h=s.get(y),{isPeerRoot:g,hasPeers:x,isSharedDep:v}=r.get(y),P=a.has(y),_=p!==y,I=!(g||v)&&(P||!x),M=this.singletonDepsOf(h,o),A=_&&f.has(y);A&&u.add(y);let j=A?[...M,y]:M.length?M:void 0;c.push([p,this.cdn.buildEsmUrl(i(p),{bundle:I,external:j})]),l.add(p)}let d=new Set([...o,...u]);for(let p of d)s.has(p)&&(l.has(p)||c.push([p,this.cdn.buildEsmUrl(i(p),{})]),c.push([`${p}/`,`${Ct}/${i(p)}/`]));return c}singletonDepsOf(e,t){return[...new Set([...ds(e.meta),...lu(e.meta)])].filter(r=>t.has(r))}};jn.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as Og,satisfies as qA,maxSatisfying as Pg,major as JA,valid as KA,validRange as WA}from"semver";var fo,tn,fu=S(()=>{fo=class{cmp(e,t){return e===t?0:Og(e,t)?1:Og(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!qA(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=Pg(e,r,{includePrerelease:!1});if(a)return a}return Pg(e,r,{includePrerelease:!0})??void 0}majorOf(e){return JA(e)}isExactVersion(e){return KA(e)!==null}isRange(e){return WA(e)!==null}},tn=new fo});function HA(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var nn,Cg=S(()=>{lo();nn=class{constructor(e){this.store=e}async isNegative(e){let t=await be(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await be(()=>this.store.get(e)))?.attempts||0)+1;await be(()=>this.store.set(e,{until:Date.now()+HA(r),attempts:r}))}async clearNegative(e){await be(()=>this.store.delete(e))}}});function _g(n,e){let t=new us(n,e),r=new fs(t),s=new ps(n,t,tn);return{packageService:new jn(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var st=S(()=>{cu();uo();uu();du();fu();ls();fu();cs();cu();uo();uu();du();Cg()});import*as pu from"fs/promises";import*as Rg from"crypto";function De(n){return Rg.createHash("sha1").update(n).digest("hex")}async function it(n){try{return JSON.parse(await pu.readFile(n,"utf8"))}catch{return}}async function po(n){try{return await pu.readFile(n,"utf8")}catch{return}}var Fn=S(()=>{"use strict"});import*as Rt from"fs/promises";import*as ot from"path";import*as Ng from"os";function te(){return hu||(hu=VA().catch(()=>nt())),hu}function mo(n,e){return ot.join(YA,De(n),e)}async function VA(){await Rt.mkdir(_t,{recursive:!0});let n=ot.join(_t,"version.json");if((await it(n))?.version===Ig)return;let t=await Rt.readdir(_t).catch(()=>[]);await Promise.all(t.map(r=>Rt.rm(ot.join(_t,r),{recursive:!0,force:!0}))),await Rt.writeFile(n,JSON.stringify({version:Ig})+`
|
|
433
|
+
`,"utf8")}var Ig,_t,hs,ms,ho,YA,hu,Un=S(()=>{"use strict";Fn();Pt();Ig=1,_t=ot.join(Ng.homedir(),".typebulb","cache"),hs=ot.join(_t,"packages"),ms=ot.join(_t,"proxy"),ho=ot.join(_t,"dts"),YA=ot.join(_t,"emit")});import*as It from"fs/promises";import*as $g from"path";async function Te(n,e){let t=`${n}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await It.mkdir($g.dirname(n),{recursive:!0}),await It.writeFile(t,e,"utf8")}catch{nt();return}await It.rename(t,n).catch(async()=>{await It.rm(t,{force:!0}).catch(()=>{})})}var gs=S(()=>{"use strict";Pt()});var qn,mu=S(()=>{"use strict";gs();Fn();qn=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=it(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 Te(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as Bg from"fs/promises";import*as je from"path";function Mg(n,e){return je.join(zA,go(n),encodeURIComponent(e)+".json")}function go(n){return n.replace(/\//g,"__")}var gu,Lg,zA,GA,yo,Dg=S(()=>{"use strict";st();Un();gs();mu();Fn();gu=je.join(hs,"indexes"),Lg=je.join(hs,"pinned"),zA=je.join(hs,"meta"),GA=je.join(hs,"negative.json"),yo=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new nn(new qn(GA));async getPinnedExact(e,t){let r=`${e}@${t}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await te();let s=await po(je.join(Lg,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 te(),await Te(je.join(Lg,De(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await te();let t=await it(je.join(gu,go(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 te(),await Te(je.join(gu,go(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await Bg.rm(je.join(gu,go(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await te(),this.negativeCache.isNegative(e)}async recordNegative(e){await te(),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 te();let s=await it(Mg(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 te(),await Te(Mg(e,t),JSON.stringify(o))}}});var jg,Fg=S(()=>{"use strict";jg={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 XA,bo,Ug,qg,sL,yu=S(()=>{"use strict";st();Dg();Fg();XA=new yo,{packageService:bo,versionResolver:Ug,cdnClient:qg,peerResolver:sL}=_g(XA,jg)});function wo(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function Jg(){return` <script>
|
|
434
434
|
${Km}
|
|
435
435
|
(function () {
|
|
436
436
|
try {
|
|
@@ -1354,7 +1354,7 @@ ${So}
|
|
|
1354
1354
|
}
|
|
1355
1355
|
})();
|
|
1356
1356
|
`});function Yg(n){let{name:e,code:t,css:r,html:s,data:i,insight:o,importMap:a,theme:c,inline:l,dir:f,source:u,compileError:d}=n,p=s.trim()||'<div id="app"></div>',y=l?"":`
|
|
1357
|
-
`+Dl,h={imports:
|
|
1357
|
+
`+Dl,h={imports:nT(a.imports)};return`<!DOCTYPE html>
|
|
1358
1358
|
<html>
|
|
1359
1359
|
<head>
|
|
1360
1360
|
<meta charset="utf-8">
|
|
@@ -1384,16 +1384,16 @@ ${d?`<script>window.__TB_COMPILE_ERROR__ = ${Nt(JSON.stringify(d))};</script>`:"
|
|
|
1384
1384
|
${Wg}
|
|
1385
1385
|
</script>
|
|
1386
1386
|
|
|
1387
|
-
${
|
|
1387
|
+
${tT}
|
|
1388
1388
|
|
|
1389
|
-
${
|
|
1389
|
+
${ZA(t,u)}
|
|
1390
1390
|
</body>
|
|
1391
|
-
</html>`}function
|
|
1392
|
-
`);return`<script type="module">${s}${
|
|
1393
|
-
</script>`}function
|
|
1391
|
+
</html>`}function ZA(n,e){let t=["",...QA],r=e?Array(Math.max(0,e.codeLine-t.length-1)).fill(""):[],s=[...t,...r,Nt(n)].join(`
|
|
1392
|
+
`);return`<script type="module">${s}${eT(e,s)}
|
|
1393
|
+
</script>`}function eT(n,e){if(!n)return"";let t=e.split(`
|
|
1394
1394
|
`).length,r={version:3,file:n.file,sources:[`/__source/${n.file}`],names:[],mappings:["AAAA",...Array(Math.max(0,t-1)).fill("AACA")].join(";")};return`
|
|
1395
1395
|
//# sourceURL=${n.file.replace(/\s/g,"%20")}
|
|
1396
|
-
//# sourceMappingURL=data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(r))}`}function
|
|
1396
|
+
//# sourceMappingURL=data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(r))}`}function nT(n){let e={};for(let[t,r]of Object.entries(n))e[t]=r.startsWith("https://")?"/proxy/"+r:r;return e}var QA,tT,Vg=S(()=>{"use strict";Hg();Jn();QA=["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) */"];tT=`<script>
|
|
1397
1397
|
(function () {
|
|
1398
1398
|
var framed = window.parent !== window;
|
|
1399
1399
|
var post = function (m) { try { parent.postMessage(m, '*'); } catch (e) {} }; /* framed only */
|
|
@@ -1492,8 +1492,8 @@ ${QA(t,u)}
|
|
|
1492
1492
|
}
|
|
1493
1493
|
});
|
|
1494
1494
|
})();
|
|
1495
|
-
</script>`});import*as xo from"fs/promises";import*as ko from"path";import{existsSync as zg,readFileSync as
|
|
1496
|
-
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await xo.mkdir(e,{recursive:!0});let a=ko.join(e,"package.json");zg(a)||await xo.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let c=["--no-audit","--no-fund",...r?.ignoreScripts?["--ignore-scripts"]:[]];await
|
|
1495
|
+
</script>`});import*as xo from"fs/promises";import*as ko from"path";import{existsSync as zg,readFileSync as rT}from"fs";import{execFile as sT}from"child_process";import{promisify as iT}from"util";import{builtinModules as oT}from"node:module";import{satisfies as aT}from"semver";async function Eo(n,e,t,r){let i=n.map(l=>dT(l,t)).filter(l=>!fT(l,e));if(i.length===0)return;let o=i.filter(l=>!uT.test(l));if(o.length)throw new Error(`Refusing to install npm spec(s) with unsupported characters: ${o.join(", ")}
|
|
1496
|
+
Use a plain name with an exact / caret / tilde range (e.g. three@^0.160.0).`);await xo.mkdir(e,{recursive:!0});let a=ko.join(e,"package.json");zg(a)||await xo.writeFile(a,JSON.stringify({name:"typebulb-server",private:!0})),console.log(` Installing: ${i.join(", ")}`);let c=["--no-audit","--no-fund",...r?.ignoreScripts?["--ignore-scripts"]:[]];await cT("npm",["install",...c,...i],{cwd:e,shell:!0})}function dT(n,e){if(!e||D.parse(n).version)return n;let t=e[n];return t?`${n}@${t}`:n}function fT(n,e){let{name:t,version:r}=D.parse(n),s=ko.join(e,"node_modules",t);if(!zg(s))return!1;if(!r)return!0;try{let i=JSON.parse(rT(ko.join(s,"package.json"),"utf-8")).version;return aT(i,r)}catch{return!1}}function Ao(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=D.rootOf(s);lT.has(i)||e.add(i)}return[...e]}var cT,lT,uT,wu=S(()=>{"use strict";st();cT=iT(sT),lT=new Set(oT),uT=/^(@[a-z0-9._-]+\/)?[a-z0-9._-]+(@[a-zA-Z0-9.^~*x-]+)?$/i});var Gg,Xg,Ve,rn=S(()=>{Gg=n=>n!=null&&n>=0&&n<=4?n:void 0,Xg=(n,e)=>{let t={...n};for(let r of["input","output","reasoning","cacheRead"])e[r]!==void 0&&(t[r]=e[r]);return t},Ve=n=>n===void 0||n.input===void 0&&n.output===void 0?void 0:{input:n.input??0,output:n.output??0,reasoning:n.reasoning,cacheRead:n.cacheRead}});var ke,Fe,Kn=S(()=>{ke=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=`
|
|
1497
1497
|
|
|
1498
1498
|
`){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 ke(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 ke(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 To,vu=S(()=>{rn();Kn();To=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(`
|
|
1499
1499
|
`)),!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,usage:this.mapUsage(e.usage)}}parseProviderStreamChunk(e){if(this.isResponsesApiEvent(e))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 ke(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};case"response.completed":{let t=this.mapUsage(e.response?.usage);return t?{usage:t}:void 0}default:return}}mapUsage(e){if(e)return Ve({input:e.input_tokens,output:e.output_tokens,reasoning:e.output_tokens_details?.reasoning_tokens,cacheRead:e.input_tokens_details?.cached_tokens})}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(`
|
|
@@ -1502,12 +1502,12 @@ ${QA(t,u)}
|
|
|
1502
1502
|
|
|
1503
1503
|
`);return{text:t,reasoning:r||void 0,usage:Ve(this.mapUsage(e.usage))}}parseProviderStreamChunk(e){if(this.isAnthropicEvent(e))switch(e.type){case"content_block_delta":return e.delta.type==="text_delta"?{text:e.delta.text||""}:e.delta.type==="thinking_delta"?{reasoning:e.delta.thinking||""}:void 0;case"message_start":{let t=this.mapUsage(e.message?.usage);return t?{usage:t}:void 0}case"message_delta":{let t=this.mapUsage(e.usage);return t?{usage:t}:void 0}default:return}}mapUsage(e){if(typeof e!="object"||e===null)return;let t=e,r=l=>typeof l=="number"?l:void 0,s=r(t.input_tokens),i=r(t.cache_read_input_tokens),o=r(t.cache_creation_input_tokens),a=r(t.output_tokens),c=s!==void 0||i!==void 0||o!==void 0?(s??0)+(i??0)+(o??0):void 0;if(!(c===void 0&&a===void 0))return{input:c,output:a,cacheRead:i}}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 _o,xu=S(()=>{rn();Kn();_o=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,`
|
|
1504
1504
|
`),c={contents:o.map(f=>({role:f.role==="assistant"?"model":"user",parts:[{text:f.content}]}))};r?.webSearch===!0&&(c.tools=[{google_search:{}}]),i&&(c.systemInstruction={role:"system",parts:[{text:i}]});let l=r?.effort;if(l!==void 0){let f=this.geminiVersion(t),u=f!==void 0&&f>=3?{thinkingLevel:this.thinkingLevelFor(f,l)}:{thinkingBudget:this.budgetMap[l]};c.generationConfig={thinkingConfig:l===0?u:{includeThoughts:!0,...u}}}return r?.maxOutputTokens!==void 0&&(c.generationConfig={...c.generationConfig,maxOutputTokens:r.maxOutputTokens}),c}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(`
|
|
1505
|
-
`)[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,usage:this.mapUsage(e.usageMetadata)}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return;let t=this.extractParts(e),r=this.mapUsage(e.usageMetadata);return r&&(t.usage=r),t.text||t.reasoning||t.usage?t:void 0}mapUsage(e){if(!e)return;let t=e.candidatesTokenCount!==void 0||e.thoughtsTokenCount!==void 0;return Ve({input:e.promptTokenCount,output:t?(e.candidatesTokenCount??0)+(e.thoughtsTokenCount??0):void 0,reasoning:e.thoughtsTokenCount,cacheRead:e.cachedContentTokenCount})}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):void 0}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 ke(`Prompt blocked: ${t}`)}}}});var Ro,Eu=S(()=>{Oo();Ro=class extends Wn{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 s?{model:t,messages:e,stream:s,stream_options:{include_usage:!0}}:{model:t,messages:e,stream:s}}}});function sn(n){let e=
|
|
1505
|
+
`)[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,usage:this.mapUsage(e.usageMetadata)}}parseProviderStreamChunk(e){if(this.checkGeminiError(e),!this.isGeminiResponse(e))return;let t=this.extractParts(e),r=this.mapUsage(e.usageMetadata);return r&&(t.usage=r),t.text||t.reasoning||t.usage?t:void 0}mapUsage(e){if(!e)return;let t=e.candidatesTokenCount!==void 0||e.thoughtsTokenCount!==void 0;return Ve({input:e.promptTokenCount,output:t?(e.candidatesTokenCount??0)+(e.thoughtsTokenCount??0):void 0,reasoning:e.thoughtsTokenCount,cacheRead:e.cachedContentTokenCount})}geminiVersion(e){let t=e.match(/^gemini-(\d+(?:\.\d+)?)/);return t?Number(t[1]):void 0}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 ke(`Prompt blocked: ${t}`)}}}});var Ro,Eu=S(()=>{Oo();Ro=class extends Wn{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 s?{model:t,messages:e,stream:s,stream_options:{include_usage:!0}}:{model:t,messages:e,stream:s}}}});function sn(n){let e=pT.get(n);if(!e)throw new Error(`Unsupported protocol: ${n}`);return e}function hT(n,e){return n.replace(/\/+$/,"")+(e.startsWith("/")?e:`/${e}`)}async function Au(n,e){let t=sn(n.protocol),r=t.getPath(n.model,e.stream),s=hT(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 mT(n){return/prompt is too long|context[_ ](length|window)|maximum context|token count exceeds|too many tokens/i.test(n)}async function Hn(n,e){let t=sn(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||mT(s))&&(o="context_exceeded"),{code:o,message:s,retryable:i===429||i>=500}}var Qg,pT,Tu=S(()=>{vu();Su();ku();xu();Eu();Qg=new Ro,pT=new Map([["openai",new To],["openrouter",new Po],["anthropic",new Co],["gemini",new _o],["ollama",Qg],["openai-compat",Qg]])});function Zg(n){let e=n.indexOf(`\r
|
|
1506
1506
|
\r
|
|
1507
1507
|
`),t=n.indexOf(`
|
|
1508
1508
|
|
|
1509
1509
|
`);return e!==-1&&(t===-1||e<t)?{pos:e,len:4}:t!==-1?{pos:t,len:2}:{pos:-1,len:0}}function Ou(n){let t=n.split(/\r?\n/).filter(s=>s.startsWith("data:"));if(!t.length)return;let r=t.map(s=>s.replace(/^data:\s?/,"")).join(`
|
|
1510
|
-
`).trim();if(r){if(r==="[DONE]")return"done";try{return JSON.parse(r)}catch{return}}}async function*ey(n,e,t){let r=new TextDecoder,s="",i,o=e?new Promise((a,c)=>{e.aborted&&c(new Error("Aborted")),i=()=>c(new Error("Aborted")),e.addEventListener("abort",i,{once:!0})}):void 0;o?.catch(()=>{});try{for(;;){let{done:a,value:c}=o?await Promise.race([n.read(),o]):await n.read();if(a){if(s.trim()){let u=Ou(s);u!==void 0&&u!=="done"&&(yield u)}return}t?.(),s+=r.decode(c,{stream:!0});let{pos:l,len:f}=Zg(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=Ou(u);if(d==="done")return;d!==void 0&&(yield d),{pos:l,len:f}=Zg(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await n.cancel()}catch{}}}async function Pu(n,e){return(await Yn(n,e)).text}async function Yn(n,e){if(!n.body)throw new Error("Response body is missing");let t="",r;for await(let s of on(n,e))s.kind==="text"?t+=s.text:s.kind==="usage"&&(r=s.usage);return{text:t,usage:r}}async function*on(n,e){let t=e??(n.headers.get("X-Provider-Protocol")||"openai"),r=sn(t);if(!n.body)return;let s=n.body.getReader(),i;for await(let a of ey(s)){let c=r.parseStreamChunk(a);c?.reasoning&&(yield{kind:"reasoning",text:c.reasoning}),c?.text&&(yield{kind:"text",text:c.text}),c?.usage&&(i=Xg(i,c.usage))}let o=Ve(i);o&&(yield{kind:"usage",usage:o})}var ty=S(()=>{rn();Tu()});import{strToU8 as
|
|
1510
|
+
`).trim();if(r){if(r==="[DONE]")return"done";try{return JSON.parse(r)}catch{return}}}async function*ey(n,e,t){let r=new TextDecoder,s="",i,o=e?new Promise((a,c)=>{e.aborted&&c(new Error("Aborted")),i=()=>c(new Error("Aborted")),e.addEventListener("abort",i,{once:!0})}):void 0;o?.catch(()=>{});try{for(;;){let{done:a,value:c}=o?await Promise.race([n.read(),o]):await n.read();if(a){if(s.trim()){let u=Ou(s);u!==void 0&&u!=="done"&&(yield u)}return}t?.(),s+=r.decode(c,{stream:!0});let{pos:l,len:f}=Zg(s);for(;l!==-1;){let u=s.slice(0,l);s=s.slice(l+f);let d=Ou(u);if(d==="done")return;d!==void 0&&(yield d),{pos:l,len:f}=Zg(s)}}}finally{i&&e?.removeEventListener("abort",i);try{await n.cancel()}catch{}}}async function Pu(n,e){return(await Yn(n,e)).text}async function Yn(n,e){if(!n.body)throw new Error("Response body is missing");let t="",r;for await(let s of on(n,e))s.kind==="text"?t+=s.text:s.kind==="usage"&&(r=s.usage);return{text:t,usage:r}}async function*on(n,e){let t=e??(n.headers.get("X-Provider-Protocol")||"openai"),r=sn(t);if(!n.body)return;let s=n.body.getReader(),i;for await(let a of ey(s)){let c=r.parseStreamChunk(a);c?.reasoning&&(yield{kind:"reasoning",text:c.reasoning}),c?.text&&(yield{kind:"text",text:c.text}),c?.usage&&(i=Xg(i,c.usage))}let o=Ve(i);o&&(yield{kind:"usage",usage:o})}var ty=S(()=>{rn();Tu()});import{strToU8 as gT,strFromU8 as yT,deflateSync as bT,inflateSync as wT}from"fflate";function _u(n,e){let t=[];if(t.push(`You are a data processor. Follow the instructions to analyze the provided data. Output valid JSON that the code can consume.
|
|
1511
1511
|
|
|
1512
1512
|
---
|
|
1513
1513
|
Instructions:
|
|
@@ -1525,21 +1525,21 @@ ${r}
|
|
|
1525
1525
|
</data>`)}return t.push(`
|
|
1526
1526
|
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(`
|
|
1527
1527
|
|
|
1528
|
-
`)}function ys(n){try{return JSON.parse(n)}catch{return}}function ny(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
|
|
1529
|
-
`)){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 Io(n,e=process.cwd()){for(let t of oy()){let r;try{r=iy(ze.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of ay(r))if(s===n)return i}return process.env[n]}function
|
|
1530
|
-
`)}var Vn,CT,_T,RT,IT,bs,No,ws,cn=S(()=>{"use strict";Vn={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};CT="https://api.typebulb.com/api/models",_T=1440*60*1e3,RT=5e3,IT=60*1e3});function lt(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=sn(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${zn(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=Vn[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 ${cy()}.`}function Lt(n,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return Au(n,{messages:t,stream:!0,effort:Gg(e.effort),webSearch:e.webSearch,signal:e.signal})}var Lo=S(()=>{"use strict";an();an();at();cn()});import*as Gn from"fs/promises";import*as ut from"path";function Mo(n,e,t=e){let r=ut.resolve(e,n),s=ut.normalize(t),i=ut.normalize(r);if(i!==s&&!i.startsWith(s+ut.sep))throw new Error("Path traversal detected - access denied");return r}async function vs(n,e,t){return Gn.readFile(Mo(n,e,t))}async function Bo(n,e,t,r){let s=Mo(n,t,r);await Gn.mkdir(ut.dirname(s),{recursive:!0}),await Gn.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var Mu=S(()=>{"use strict"});async function fy(n){let e=lt(n.provider,n.model);if(typeof e=="string")throw new Error(e);let t=await Lt(e,n);if(!t.ok){let r=await Hn(t,e.protocol);throw new Error(r.message)}return{response:t,protocol:e.protocol}}async function MT(n){let{response:e,protocol:t}=await fy(n);return Yn(e,t)}async function*BT(n){let{response:e,protocol:t}=await fy(n);yield*on(e,t)}function py(n,e=process.cwd()){let t=Object.assign(MT,{stream:BT}),r={read:async s=>{let i=await vs(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 vs(s,n,e)),write:async(s,i)=>(await Bo(s,i,n,e),!0)};globalThis.tb=Object.freeze({log:(...s)=>{console.log(...s)},ai:t,fs:r,dir:n,models:()=>ct(),aiAccess:$o,mode:Nn.local})}var hy=S(()=>{"use strict";an();ee();Lo();cn();Mu()});import*as Ue from"fs/promises";import*as ce from"path";import{pathToFileURL as DT}from"url";async function my(n){let t=(await Ue.readdir(n)).find(r=>r.endsWith(".bulb.md"));return t?ce.join(n,t):void 0}function Mt(n,e){let t=ce.resolve(n),r=ce.join(ce.dirname(t),ce.basename(t).replace(/\.bulb\.md$/,""));return e?ce.join(r,"batches",e):r}async function Xn(n,e){let t=Mt(n,e);await Ue.mkdir(t,{recursive:!0});let r=new Date;await Ue.utimes(t,r,r).catch(()=>{})}function Qn(n){let[e,t,r,s]=n.split(ce.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=vn(e),r=Bn(t);return{bulb:r,config:gr(r.config),warnings:Sf(e),starts:t.starts}}function Bu(n){let e=ce.basename(n).replace(/\.bulb\.md$/i,"");return ce.join(ce.dirname(n),".typebulb",`${e}.server.mjs`)}async function Ss(n,e,t,r,s){let i=su(n,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await mf(o,t));let a=ce.join(ce.dirname(e),".typebulb");await Ue.mkdir(a,{recursive:!0});let c=Ao(o);c.length>0&&await Eo(c,a,r);let l=Bu(e);return await Ue.writeFile(l,o,"utf-8"),py(Mt(e,s)),await import(`${DT(l).href}?t=${Date.now()}`)}async function Du(n,e,t,r,s){let{bulb:i,config:o,starts:a}=await qe(n),c=Hi(i.data);kg(i.code,o.dependencies??{});let l=su(i.code,{jsxImportSource:o.ts?.jsxImportSource});l.error&&console.error("Compilation error:",l.error);let{importMap:f}=await bo.buildImportMap(l.code,o.dependencies??{},r?new Set([r.name]):void 0);r&&(f.imports[r.name]=r.entryUrl);let u=Yg({name:i.name,code:l.code,css:i.css,html:i.html,data:c,insight:i.insight,importMap:f,dir:Mt(n,s),watch:e,source:{file:ce.basename(n),codeLine:a.get("code.tsx")??1},compileError:l.error?String(l.error):void 0}),d;return i.server&&t&&(d=await Ss(i.server,n,r,o.dependencies,s)),{html:u,bulb:i,serverExports:d}}var Bt,Ge=S(()=>{"use strict";is();yg();xg();yu();Vg();wu();Ks();hy();Bt=(n,e)=>ce.join(Mt(n,e),"assets")});import{readdirSync as yy,readFileSync as jT,statSync as by}from"fs";import{join as Do,basename as FT}from"path";function wy(n,e,t){if(e>8)return t;let r;try{r=yy(n,{withFileTypes:!0})}catch{return t}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;wy(Do(n,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Do(n,s.name));return t}function ju(n){let e=Do(Mt(n),"batches"),t;try{t=yy(e,{withFileTypes:!0})}catch{return[]}return t.filter(r=>r.isDirectory()).map(r=>{let s=0;try{s=by(Do(e,r.name)).mtimeMs}catch{}return{name:r.name,mtime:s}}).sort((r,s)=>s.mtime-r.mtime).map(r=>r.name)}function UT(n,e){let t,r=!1;try{let s=jT(n,"utf8");t=ao(s.slice(0,1024));let i=Ie(s);r=!!i&&oo(Bn(i))}catch{}return{mtime:e,name:t??FT(n).replace(/\.bulb\.md$/,""),serverOnly:r}}function jo(n){let e=new Map,t=wy(n,0,[]).map(r=>{let s=0;try{s=by(r).mtimeMs}catch{}let i=s?gy.get(r):void 0,o=i?.mtime===s?i:UT(r,s);return s&&e.set(r,o),{path:r,...o}});return gy=e,t}var gy,vy=S(()=>{"use strict";ee();is();ru();Ge();gy=new Map});import*as xy from"net";import{mkdir as qT,readFile as JT,writeFile as Ey}from"fs/promises";import{existsSync as KT}from"fs";import{join as Ay}from"path";function Py(){return Ay(Ot(),"blocks")}function Fu(n){return Ay(Py(),`${n}.json`)}function Uo(n){return new Promise(e=>{let t=xy.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function YT(n){for(let e=n;e<65535;e++)if(await Uo(e))return e;throw new Error(`No free port found above ${n}`)}async function Uu(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 qo(n){try{let e=JSON.parse(await JT(Fu(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Jo(n,e){try{return await Ey(Fu(n),JSON.stringify(e,null,2)),!0}catch{return nt(),!1}}async function VT(n){let e=ae(n);try{await qT(Py(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Oy;o++)t.push(Ty+o*ln);let r=await Promise.all(t.map(async o=>({base:o,block:await qo(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 Ey(Fu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(c){if((await qo(o))?.cwd===e)return o;c.code!=="EEXIST"&&nt();continue}if(!KT(a.cwd))return await Jo(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Sy(o.block)-Sy(a.block))[0];if(i)return await Jo(i.base,s)?i.base:void 0}function Sy(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function zT(n,e){let t=await qo(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=ky(t),a=o.has(0)?HT:0;for(;a>Fo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Jo(n,t),a}let r=ae(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=ky(t);for(s=Fo;s<ln&&i.has(s);)s++;if(s>=ln){let o=Object.entries(t.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:Fo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Jo(n,t),s}function ky(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function GT(n,e){let t=await VT(e);return t===void 0?void 0:t+await zT(t,n)}async function un(n){let e=ae(n);for(let t=0;t<Oy;t++){let r=await qo(Ty+t*ln);if(r?.cwd===e)return s=>r.slots[ae(s)]?.usedAt??0}return()=>0}async function Ko(n){if(n.explicit!==void 0)return await Uo(n.explicit)||await Uu(n.explicit),{port:n.explicit};let e=await GT(n.target,n.cwd);if(e!==void 0){let r=e-e%ln;for(let s=0;s<4;s++){if(await Uo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=Fo;s<ln;s++){let i=r+s;if(i!==e&&await Uo(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await YT(WT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Ty,ln,Oy,WT,Fo,HT,Zn=S(()=>{"use strict";Pt();Ae();Ty=20100,ln=100,Oy=19,WT=23e3,Fo=1,HT=ln-1});function er(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 Wo=S(()=>{"use strict"});import{readFile as XT}from"fs/promises";async function qu(n){try{let e=Ie(await XT(n,"utf-8"));return e?er(Bn(e)):void 0}catch{return}}var Cy=S(()=>{"use strict";is();Wo()});function Ju(n){let e=Ie(n);if(!e)return n;let t=e.files.get("code.tsx");if(!t)return n;let r=Sg(t);if(!r.length)return n;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=r.filter(l=>!(l in o));if(!a.length)return n;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=gf(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Af(c)}var _y=S(()=>{"use strict";ee();co()});import{spawn as Ry}from"child_process";import{basename as QT}from"path";function ZT(){return process.env.TYPEBULB_EDITOR||"code"}function tO(n,e,t){return t==null?[e]:eO.test(QT(n))?["-g",`${e}:${t}`]:[`+${t}`,e]}function nO(n,e){let t=ZT();return{command:t,args:tO(t,n,e)}}function Ku(n,e){let{command:t,args:r}=nO(n,e),s=process.platform==="win32"?Ry("cmd.exe",["/d","/s","/c",t,...r],{detached:!0,stdio:"ignore",windowsHide:!0}):Ry(t,r,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var eO,Iy=S(()=>{"use strict";eO=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as rO,writeFileSync as sO,mkdirSync as iO,statSync as oO}from"fs";import{join as aO}from"path";function Wu(){return aO(Ot(),"trust.json")}function Hu(){try{let n=Wu(),e=oO(n).mtimeMs;if(ks?.mtime!==e){let t=JSON.parse(rO(n,"utf8"));ks={mtime:e,set:new Set(Array.isArray(t)?t:[])}}return ks.set}catch{return ks=void 0,new Set}}function cO(n){try{iO(Ot(),{recursive:!0}),sO(Wu(),JSON.stringify([...n])),ks=void 0}catch(e){throw new Error(`can't write ${Wu()} \u2014 trust not remembered (unwritable home; sandboxed shell?): ${e.message}`)}}function dn(n){return Hu().has(ae(n))}function tr(n,e){let t=new Set(Hu()),r=ae(n);(e?t.has(r):!t.has(r))||(e?t.add(r):t.delete(r),cO(t))}function Yu(){return[...Hu()]}var ks,xs=S(()=>{"use strict";Pt()});import{readFileSync as uB,existsSync as lO}from"fs";import*as nr from"path";import{fileURLToPath as uO}from"url";function dO(){let n=nr.dirname(uO(import.meta.url));for(;!lO(nr.join(n,"package.json"));){let e=nr.dirname(n);if(e===n)break;n=e}return n}function Es(){return nr.join(dO(),"SKILL.md")}var Vu=S(()=>{"use strict"});import*as xe from"fs/promises";import*as Pe from"path";import{createHash as fO}from"crypto";async function Gu(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 rr(n){try{return JSON.parse(n).error||n}catch{return n}}async function Qu(n,e){try{let t=await fetch(As(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}): ${rr(await t.text())}`}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}function Zu(n,e){Oe(e);let t=process.env.TYPEBULB_ORIGIN||pO;try{return Vo(n,process.cwd(),t)}catch(r){console.error(r instanceof Error?r.message:String(r)),process.exit(1)}}function Vo(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}
|
|
1528
|
+
`)}function ys(n){try{return JSON.parse(n)}catch{return}}function ny(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 ST(n){let e=ny(n,t=>t.replace(/,(\s*[}\]])/g,"$1"));return e!==n?e:void 0}function kT(n){let e=ny(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:void 0}function xT(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 ET(n){let e,t=0;for(;t<n.length;){let r=n[t];if(r==="{"||r==="["){let s=xT(n,t);if(s!==-1){let i=n.slice(t,s+1),o=ys(i);o!==void 0&&(e={parsed:o,json:i}),t=s+1;continue}}t++}return e}function Ru(n){let e=[],t=n.trim();t.startsWith("```")&&(t=t.replace(/^```(?:json)?\s*\n?/,"").replace(/\n?```\s*$/,""),e.push("markdown fences"));let r=ys(t);if(r!==void 0)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=ys(t),r!==void 0))return{parsed:r,json:t,fixesApplied:e};if(!t.startsWith("{")&&!t.startsWith("[")){let o=t.indexOf("{"),a=t.indexOf("["),c=o>=0&&a>=0?Math.min(o,a):o>=0?o:a;if(c>0&&(t=t.slice(c),e.push("preamble text"),r=ys(t),r!==void 0))return{parsed:r,json:t,fixesApplied:e}}for(let[o,a]of vT){let c=a(t);if(c!==void 0){let l=ys(c);if(l!==void 0)return{parsed:l,json:c,fixesApplied:[...e,o]}}}let i=ET(n);return i!==void 0?{...i,fixesApplied:[...e,"extracted last JSON value"]}:{parsed:void 0,json:t,fixesApplied:e}}function Iu(n){try{let e={i:n.insight,d:n.data},t=JSON.stringify(e),r=bT(gT(t),{level:9}),s=TT(r),i=`${ry}:${s}`;return i.length>AT?"":"#"+Cu+i}catch{return""}}function Nu(n){try{let e=n.startsWith("#")?n.slice(1):n;if(!e.startsWith(Cu))return;let t=e.slice(Cu.length),r=t.indexOf(":");if(r===-1||t.slice(0,r)!==ry)return;let s=OT(t.slice(r+1)),i=JSON.parse(yT(wT(s)));return!i||typeof i.i>"u"||!Array.isArray(i.d)?void 0:{insight:i.i,insightJson:JSON.stringify(i.i,null,2),data:i.d}}catch{return}}function TT(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 OT(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 vT,Cu,ry,AT,sy=S(()=>{vT=[["orphan quote",n=>{let e=n.replace(/^[ \t]*"[ \t]*\r?\n/gm,"");return e!==n?e:void 0}],["trailing }",n=>n.endsWith("}}")?n.slice(0,-1):void 0],["trailing ]",n=>n.endsWith("]]")?n.slice(0,-1):void 0],["trailing },",n=>n.endsWith("},")?n.slice(0,-1):void 0],["trailing ],",n=>n.endsWith("],")?n.slice(0,-1):void 0],["trailing commas",ST],["arithmetic constants",kT]];Cu="tb=",ry="1",AT=6e4});var an=S(()=>{rn();Kn();Tu();ty();sy();Oo();ku();xu();vu();Su();Eu()});import{readFileSync as iy,existsSync as PT}from"fs";import*as ze from"path";function oy(n){return[...n?[`.env.${n}.local`,`.env.${n}`]:[],".env.local",".env"]}function Oe(n,e=process.cwd()){let t={},r=[];for(let s of oy(n)){let i;try{i=iy(ze.resolve(e,s),"utf-8")}catch{continue}r.push(s);for(let[o,a]of ay(i))process.env[o]===void 0&&(process.env[o]=a,t[o]=s)}return{mode:n,sources:t,loaded:r}}function*ay(n){for(let e of n.split(`
|
|
1529
|
+
`)){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 Io(n,e=process.cwd()){for(let t of oy()){let r;try{r=iy(ze.resolve(e,t),"utf-8")}catch{continue}for(let[s,i]of ay(r))if(s===n)return i}return process.env[n]}function CT(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 cy(){return`.env loads from ${process.cwd()} (the directory you ran from, not the bulb's)`}function $t(n,e,t){let{sources:r,mode:s,loaded:i}=n,o=process.cwd(),a=ze.dirname(e),c=`(mode: ${s??"none"})`,l=t?CT(t):[],f=l.filter(p=>r[p]).map(p=>`${p} \u2190 ${r[p]}`);f.length?console.log(`env: ${f.join(", ")} ${c}`):i.length&&console.log(`env: loaded ${i.join(", ")} ${c}`),s&&!i.some(p=>p===`.env.${s}`||p===`.env.${s}.local`)&&console.log(`env: mode=${s} \u2014 no .env.${s} found; using .env`);let u=ze.resolve(a)!==ze.resolve(o);if(u)for(let p of[".env.local",".env"])PT(ze.join(a,p))&&console.log(`env: ${ze.join(a,p)} present but not loaded (cwd is ${o})`);let d=l.filter(p=>process.env[p]===void 0);if(d.length){let p=u?` \u2014 try running from ${a}`:"";console.log(`env: server.ts reads ${d.join(", ")} but ${d.length>1?"they are":"it's"} unset${p}`)}}var at=S(()=>{"use strict"});function zn(n){return(n.includes("://")?n:`http://${n}`).replace(/\/+$/,"")}function $u(){return ws}async function ct(){let[n,e]=await Promise.all([uy(),LT()]);return $T([...MT(e),...n],process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL)}function $T(n,e,t){return!e||!t?n:n.map(r=>r.provider===e&&r.name===t?{...r,default:!0}:r)}async function ly(){let n;try{n=await fetch(_T,{signal:AbortSignal.timeout(IT)})}catch(e){ws=`catalog fetch failed: ${e?.message??e}`;return}if(!n.ok){ws=`catalog fetch failed: HTTP ${n.status}`;return}try{return await n.json()}catch(e){ws=`catalog returned an unreadable body: ${e?.message??e}`;return}}async function LT(){if(bs&&Date.now()-bs.fetchedAt<=RT)return bs.models;let n=await ly()??await ly();return n?(bs={models:n,fetchedAt:Date.now()},ws=void 0,n):bs?.models??[]}async function uy(){if(No&&Date.now()-No.fetchedAt<=NT)return No.models;let n=zn(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 No={models:e,fetchedAt:Date.now()},e}function MT(n){let e=new Set(Object.entries(Vn).filter(([,t])=>!!process.env[t]).map(([t])=>t));return n.filter(t=>e.has(t.provider))}function Lu(){return Object.values(Vn).some(n=>!!process.env[n])}async function $o(){return Lu()||process.env.TB_AI_BASE_URL||(await uy()).length>0?"own":"none"}function dy(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(`
|
|
1530
|
+
`)}var Vn,_T,RT,IT,NT,bs,No,ws,cn=S(()=>{"use strict";Vn={anthropic:"ANTHROPIC_API_KEY",openai:"OPENAI_API_KEY",gemini:"GOOGLE_API_KEY",openrouter:"OPENROUTER_API_KEY"};_T="https://api.typebulb.com/api/models",RT=1440*60*1e3,IT=5e3,NT=60*1e3});function lt(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=sn(t)}catch{return`Unknown provider '${t}'.`}if(t==="ollama")return{apiKey:"",baseUrl:`${zn(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=Vn[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 ${cy()}.`}function Lt(n,e){let t=[...e.system?[{role:"system",content:e.system}]:[],...e.messages.map(r=>({role:r.role,content:r.content}))];return Au(n,{messages:t,stream:!0,effort:Gg(e.effort),webSearch:e.webSearch,signal:e.signal})}var Lo=S(()=>{"use strict";an();an();at();cn()});import*as Gn from"fs/promises";import*as ut from"path";function Mo(n,e,t=e){let r=ut.resolve(e,n),s=ut.normalize(t),i=ut.normalize(r);if(i!==s&&!i.startsWith(s+ut.sep))throw new Error("Path traversal detected - access denied");return r}async function vs(n,e,t){return Gn.readFile(Mo(n,e,t))}async function Bo(n,e,t,r){let s=Mo(n,t,r);await Gn.mkdir(ut.dirname(s),{recursive:!0}),await Gn.writeFile(s,typeof e=="string"?e:Buffer.from(e))}var Mu=S(()=>{"use strict"});async function fy(n){let e=lt(n.provider,n.model);if(typeof e=="string")throw new Error(e);let t=await Lt(e,n);if(!t.ok){let r=await Hn(t,e.protocol);throw new Error(r.message)}return{response:t,protocol:e.protocol}}async function BT(n){let{response:e,protocol:t}=await fy(n);return Yn(e,t)}async function*DT(n){let{response:e,protocol:t}=await fy(n);yield*on(e,t)}function py(n,e=process.cwd()){let t=Object.assign(BT,{stream:DT}),r={read:async s=>{let i=await vs(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 vs(s,n,e)),write:async(s,i)=>(await Bo(s,i,n,e),!0)};globalThis.tb=Object.freeze({log:(...s)=>{console.log(...s)},ai:t,fs:r,dir:n,models:()=>ct(),aiAccess:$o,mode:Nn.local})}var hy=S(()=>{"use strict";an();ee();Lo();cn();Mu()});import*as Ue from"fs/promises";import*as ce from"path";import{pathToFileURL as jT}from"url";async function my(n){let t=(await Ue.readdir(n)).find(r=>r.endsWith(".bulb.md"));return t?ce.join(n,t):void 0}function Mt(n,e){let t=ce.resolve(n),r=ce.join(ce.dirname(t),ce.basename(t).replace(/\.bulb\.md$/,""));return e?ce.join(r,"batches",e):r}async function Xn(n,e){let t=Mt(n,e);await Ue.mkdir(t,{recursive:!0});let r=new Date;await Ue.utimes(t,r,r).catch(()=>{})}function Qn(n){let[e,t,r,s]=n.split(ce.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=vn(e),r=Bn(t);return{bulb:r,config:gr(r.config),warnings:Sf(e),starts:t.starts}}function Bu(n){let e=ce.basename(n).replace(/\.bulb\.md$/i,"");return ce.join(ce.dirname(n),".typebulb",`${e}.server.mjs`)}async function Ss(n,e,t,r,s){let i=su(n,{serverOnly:!0});if(i.error)throw new Error(`Server compilation error: ${i.error}`);let o=i.code;t&&(o=await mf(o,t));let a=ce.join(ce.dirname(e),".typebulb");await Ue.mkdir(a,{recursive:!0});let c=Ao(o);c.length>0&&await Eo(c,a,r);let l=Bu(e);return await Ue.writeFile(l,o,"utf-8"),py(Mt(e,s)),await import(`${jT(l).href}?t=${Date.now()}`)}async function Du(n,e,t,r,s){let{bulb:i,config:o,starts:a}=await qe(n),c=Hi(i.data);kg(i.code,o.dependencies??{});let l=su(i.code,{jsxImportSource:o.ts?.jsxImportSource});l.error&&console.error("Compilation error:",l.error);let{importMap:f}=await bo.buildImportMap(l.code,o.dependencies??{},r?new Set([r.name]):void 0);r&&(f.imports[r.name]=r.entryUrl);let u=Yg({name:i.name,code:l.code,css:i.css,html:i.html,data:c,insight:i.insight,importMap:f,dir:Mt(n,s),watch:e,source:{file:ce.basename(n),codeLine:a.get("code.tsx")??1},compileError:l.error?String(l.error):void 0}),d;return i.server&&t&&(d=await Ss(i.server,n,r,o.dependencies,s)),{html:u,bulb:i,serverExports:d}}var Bt,Ge=S(()=>{"use strict";is();yg();xg();yu();Vg();wu();Ks();hy();Bt=(n,e)=>ce.join(Mt(n,e),"assets")});import{readdirSync as yy,readFileSync as FT,statSync as by}from"fs";import{join as Do,basename as UT}from"path";function wy(n,e,t){if(e>8)return t;let r;try{r=yy(n,{withFileTypes:!0})}catch{return t}for(let s of r)if(s.isDirectory()){if(s.name.startsWith(".")||s.name==="node_modules")continue;wy(Do(n,s.name),e+1,t)}else s.isFile()&&s.name.endsWith(".bulb.md")&&t.push(Do(n,s.name));return t}function ju(n){let e=Do(Mt(n),"batches"),t;try{t=yy(e,{withFileTypes:!0})}catch{return[]}return t.filter(r=>r.isDirectory()).map(r=>{let s=0;try{s=by(Do(e,r.name)).mtimeMs}catch{}return{name:r.name,mtime:s}}).sort((r,s)=>s.mtime-r.mtime).map(r=>r.name)}function qT(n,e){let t,r=!1;try{let s=FT(n,"utf8");t=ao(s.slice(0,1024));let i=Ie(s);r=!!i&&oo(Bn(i))}catch{}return{mtime:e,name:t??UT(n).replace(/\.bulb\.md$/,""),serverOnly:r}}function jo(n){let e=new Map,t=wy(n,0,[]).map(r=>{let s=0;try{s=by(r).mtimeMs}catch{}let i=s?gy.get(r):void 0,o=i?.mtime===s?i:qT(r,s);return s&&e.set(r,o),{path:r,...o}});return gy=e,t}var gy,vy=S(()=>{"use strict";ee();is();ru();Ge();gy=new Map});import*as xy from"net";import{mkdir as JT,readFile as KT,writeFile as Ey}from"fs/promises";import{existsSync as WT}from"fs";import{join as Ay}from"path";function Py(){return Ay(Ot(),"blocks")}function Fu(n){return Ay(Py(),`${n}.json`)}function Uo(n){return new Promise(e=>{let t=xy.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function VT(n){for(let e=n;e<65535;e++)if(await Uo(e))return e;throw new Error(`No free port found above ${n}`)}async function Uu(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 qo(n){try{let e=JSON.parse(await KT(Fu(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function Jo(n,e){try{return await Ey(Fu(n),JSON.stringify(e,null,2)),!0}catch{return nt(),!1}}async function zT(n){let e=ae(n);try{await JT(Py(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Oy;o++)t.push(Ty+o*ln);let r=await Promise.all(t.map(async o=>({base:o,block:await qo(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 Ey(Fu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(c){if((await qo(o))?.cwd===e)return o;c.code!=="EEXIST"&&nt();continue}if(!WT(a.cwd))return await Jo(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Sy(o.block)-Sy(a.block))[0];if(i)return await Jo(i.base,s)?i.base:void 0}function Sy(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function GT(n,e){let t=await qo(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=ky(t),a=o.has(0)?YT:0;for(;a>Fo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await Jo(n,t),a}let r=ae(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=ky(t);for(s=Fo;s<ln&&i.has(s);)s++;if(s>=ln){let o=Object.entries(t.slots).sort((a,c)=>(a[1].usedAt??0)-(c[1].usedAt??0))[0];s=o?o[1].offset:Fo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await Jo(n,t),s}function ky(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function XT(n,e){let t=await zT(e);return t===void 0?void 0:t+await GT(t,n)}async function un(n){let e=ae(n);for(let t=0;t<Oy;t++){let r=await qo(Ty+t*ln);if(r?.cwd===e)return s=>r.slots[ae(s)]?.usedAt??0}return()=>0}async function Ko(n){if(n.explicit!==void 0)return await Uo(n.explicit)||await Uu(n.explicit),{port:n.explicit};let e=await XT(n.target,n.cwd);if(e!==void 0){let r=e-e%ln;for(let s=0;s<4;s++){if(await Uo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}for(let s=Fo;s<ln;s++){let i=r+s;if(i!==e&&await Uo(i))return{port:i,note:`(slot ${e} was busy)`}}}return{port:await VT(HT),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var Ty,ln,Oy,HT,Fo,YT,Zn=S(()=>{"use strict";Pt();Ae();Ty=20100,ln=100,Oy=19,HT=23e3,Fo=1,YT=ln-1});function er(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 Wo=S(()=>{"use strict"});import{readFile as QT}from"fs/promises";async function qu(n){try{let e=Ie(await QT(n,"utf-8"));return e?er(Bn(e)):void 0}catch{return}}var Cy=S(()=>{"use strict";is();Wo()});function Ju(n){let e=Ie(n);if(!e)return n;let t=e.files.get("code.tsx");if(!t)return n;let r=Sg(t);if(!r.length)return n;let s=e.files.get("config.json"),i={};if(s)try{let l=JSON.parse(s);l&&typeof l=="object"&&(i=l)}catch{}let o=i.dependencies&&typeof i.dependencies=="object"?{...i.dependencies}:{},a=r.filter(l=>!(l in o));if(!a.length)return n;for(let l of a)o[l]="latest";i.dependencies=o;let c={name:e.frontmatter.name};for(let[l,f]of e.files){let u=gf(l);u&&(c[u]=f)}return c.config=JSON.stringify(i,null,2),Af(c)}var _y=S(()=>{"use strict";ee();co()});import{spawn as Ry}from"child_process";import{basename as ZT}from"path";function eO(){return process.env.TYPEBULB_EDITOR||"code"}function nO(n,e,t){return t==null?[e]:tO.test(ZT(n))?["-g",`${e}:${t}`]:[`+${t}`,e]}function rO(n,e){let t=eO();return{command:t,args:nO(t,n,e)}}function Ku(n,e){let{command:t,args:r}=rO(n,e),s=process.platform==="win32"?Ry("cmd.exe",["/d","/s","/c",t,...r],{detached:!0,stdio:"ignore",windowsHide:!0}):Ry(t,r,{detached:!0,stdio:"ignore"});s.on("error",i=>console.error("[typebulb] editor launch failed:",i?.message??i)),s.unref()}var tO,Iy=S(()=>{"use strict";tO=/^(code|code-insiders|codium|vscodium|cursor|windsurf)(\.cmd|\.exe)?$/i});import{readFileSync as sO,writeFileSync as iO,mkdirSync as oO,statSync as aO}from"fs";import{join as cO}from"path";function Wu(){return cO(Ot(),"trust.json")}function Hu(){try{let n=Wu(),e=aO(n).mtimeMs;if(ks?.mtime!==e){let t=JSON.parse(sO(n,"utf8"));ks={mtime:e,set:new Set(Array.isArray(t)?t:[])}}return ks.set}catch{return ks=void 0,new Set}}function lO(n){try{oO(Ot(),{recursive:!0}),iO(Wu(),JSON.stringify([...n])),ks=void 0}catch(e){throw new Error(`can't write ${Wu()} \u2014 trust not remembered (unwritable home; sandboxed shell?): ${e.message}`)}}function dn(n){return Hu().has(ae(n))}function tr(n,e){let t=new Set(Hu()),r=ae(n);(e?t.has(r):!t.has(r))||(e?t.add(r):t.delete(r),lO(t))}function Yu(){return[...Hu()]}var ks,xs=S(()=>{"use strict";Pt()});import{readFileSync as dB,existsSync as uO}from"fs";import*as nr from"path";import{fileURLToPath as dO}from"url";function fO(){let n=nr.dirname(dO(import.meta.url));for(;!uO(nr.join(n,"package.json"));){let e=nr.dirname(n);if(e===n)break;n=e}return n}function Es(){return nr.join(fO(),"SKILL.md")}var Vu=S(()=>{"use strict"});import*as xe from"fs/promises";import*as Pe from"path";import{createHash as pO}from"crypto";async function Gu(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 rr(n){try{return JSON.parse(n).error||n}catch{return n}}async function Qu(n,e){try{let t=await fetch(As(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}): ${rr(await t.text())}`}}catch(t){return{error:t instanceof Error?t.message:String(t)}}}function Zu(n,e){Oe(e);let t=process.env.TYPEBULB_ORIGIN||hO;try{return Vo(n,process.cwd(),t)}catch(r){console.error(r instanceof Error?r.message:String(r)),process.exit(1)}}function Vo(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}
|
|
1531
1531
|
Expected <origin>/u/<user>/<slug>`);let c=a[1],l=a[2].replace(/(\.bulb)?\.md$/,"");return{origin:i.origin,userSlug:c,slug:l,dest:Pe.join(e,Ho(c,l))}}let r=Pe.resolve(e,n),s=Qn(r);if(!s)throw new Error(`Not a conventional bulb path: ${n}
|
|
1532
|
-
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
|
|
1532
|
+
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 mO(n,e){let t=await Qu(n,e);if("error"in t||!t.entries.length)return{kind:"none"};let r=t.entries,s=Bt(n.dest),i=[],o=[],a=0;for(let c of r){let l=await xe.readFile(Pe.join(s,...c.path.split("/"))).catch(()=>{});l===void 0?i.push(c.path):Xu(l)===c.md5?a++:e.force?i.push(c.path):o.push(c.path)}return o.length?{kind:"conflict",paths:o}:{kind:"plan",toGet:i,unchanged:a}}async function gO(n,e,t){let r=Bt(n.dest),s=[],i=0;return await Gu(e.toGet,4,async o=>{try{let a=await fetch(`${As(n)}/${Yo(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 c=Pe.join(r,...o.split("/"));await xe.mkdir(Pe.dirname(c),{recursive:!0}),await xe.writeFile(c,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 zo(n,e={}){let t=await fetch(zu(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??void 0};let s=await t.text(),i;try{i=await xe.readFile(n.dest,"utf-8")}catch{}let o=i!==void 0&&yO(i,s);if(i!==void 0&&!o&&!e.force){let{mtime:l}=await xe.stat(n.dest);return{kind:"conflict",dest:n.dest,localMtime:l,remoteLastModified:t.headers.get("last-modified")??void 0}}let a=await mO(n,e);if(a.kind==="conflict")return{kind:"asset-conflict",dest:n.dest,paths:a.paths};if(!o){await xe.mkdir(Pe.dirname(n.dest),{recursive:!0}),await xe.writeFile(n.dest,s);let l=new Date(t.headers.get("last-modified")??"");isNaN(l.getTime())||await xe.utimes(n.dest,new Date,l)}let c=a.kind==="plan"?await gO(n,a,e):void 0;return o?{kind:"up-to-date",dest:n.dest,assets:c}:{kind:"written",dest:n.dest,created:i===void 0,assets:c}}function yO(n,e){let t=i=>i.replace(/\r\n/g,`
|
|
1533
1533
|
`),r=Ie(t(n)),s=Ie(t(e));return!r||!s?t(n)===t(e):r.frontmatter.name===s.frontmatter.name&&Re.every(i=>(r.files.get(ue[i].path)||"")===(s.files.get(ue[i].path)||""))}async function $y(n,e){n||(console.error("Usage: typebulb pull <bulb url | typebulbs/u/<user>/<slug>.bulb.md>"),process.exit(1));let t=Zu(n,e.mode),r=`${t.origin}/u/${t.userSlug}/${t.slug}`,s;try{s=await zo(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=Pe.relative(process.cwd(),t.dest)||t.dest;switch(s.kind){case"written":console.log(`pulled ${r} \u2192 ${i}${s.created?"":" (overwritten)"}`),Ny(s.assets);return;case"up-to-date":console.log(`up to date: ${i}`),Ny(s.assets);return;case"conflict":console.error(`Refusing to overwrite ${i} \u2014 it differs from ${r}
|
|
1534
1534
|
local file modified ${s.localMtime.toISOString()}
|
|
1535
1535
|
remote last saved ${s.remoteLastModified??"unknown"}
|
|
1536
1536
|
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:
|
|
1537
1537
|
`+s.paths.map(o=>` assets/${o}`).join(`
|
|
1538
1538
|
`)+`
|
|
1539
|
-
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 Ny(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
|
|
1539
|
+
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 Ny(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 hO,Ho,zu,Yo,As,Xu,Go=S(()=>{"use strict";at();ee();Ge();hO="https://typebulb.com",Ho=(n,e)=>Pe.join("typebulbs","u",n,`${e}.bulb.md`),zu=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}.md`,Yo=n=>n.split("/").map(encodeURIComponent).join("/"),As=n=>`${n.origin}/u/${encodeURIComponent(n.userSlug)}/${encodeURIComponent(n.slug)}/assets`;Xu=n=>pO("md5").update(n).digest("hex")});import*as Xe from"fs/promises";import*as Ts from"path";async function Ly(n,e=""){let t=await Xe.readdir(n,{withFileTypes:!0}).catch(()=>[]),r=[];for(let s of t)s.isDirectory()?r.push(...await Ly(Ts.join(n,s.name),`${e}${s.name}/`)):s.isFile()&&r.push(e+s.name);return r}async function bO(n,e){let t=e.timeoutMs??3e4,r=As(n),s={Authorization:`Bearer ${e.token}`},i=Bt(n.dest);if(!await Xe.stat(i).then(y=>y.isDirectory()).catch(()=>!1))return{kind:"skipped"};let o=await Ly(i),a=await Qu(n,{token:e.token,timeoutMs:t});if("error"in a)return{kind:"sync-error",message:a.error};let c=a.entries;if(!o.length&&!c.length)return{kind:"skipped"};let l=new Map(c.map(y=>[y.path,y.md5])),f=new Set(o),u=c.map(y=>y.path).filter(y=>!f.has(y)),d=0,p=0;try{await Gu(o,4,async y=>{let h=await Xe.readFile(Ts.join(i,...y.split("/")));if(l.get(y)===Xu(h)){p++;return}let g=await fetch(`${r}/${Yo(y)}`,{method:"PUT",body:new Uint8Array(h),headers:s,signal:AbortSignal.timeout(t)});if(!g.ok)throw new Error(`upload of '${y}' refused (${g.status}): ${rr(await g.text())}`);d++})}catch(y){return{kind:"sync-error",message:y instanceof Error?y.message:String(y)}}return{kind:"synced",uploaded:d,unchanged:p,toDelete:u,base:Vs(n.userSlug,n.slug)}}async function wO(n,e,t){let r=t.timeoutMs??3e4,s=As(n),i=[];for(let o of e)try{let a=await fetch(`${s}/${Yo(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}): ${rr(await a.text())}`};i.push(o)}catch(a){return{deleted:i,error:a instanceof Error?a.message:String(a)}}return{deleted:i}}async function Xo(n,e){let t=await Xe.readFile(n.dest,"utf-8"),{mtime:r}=await Xe.stat(n.dest),s=await bO(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(zu(n),{method:"PUT",body:t,headers:o,signal:e.timeoutMs?AbortSignal.timeout(e.timeoutMs):void 0}),c=await a.text();if(a.status===409)return{kind:"conflict",message:rr(c),assets:i};if(!a.ok)return{kind:"http-error",status:a.status,message:rr(c),assets:i};let l=JSON.parse(c);if(await Xe.utimes(n.dest,new Date,new Date(l.updatedAt)),i&&s.kind==="synced"&&s.toDelete.length){let f=await wO(n,s.toDelete,{token:e.token,timeoutMs:e.timeoutMs});i.deleted=f.deleted,f.error&&(i.pruneError=f.error)}return{kind:"pushed",created:l.created,serverStripped:l.serverStripped,updatedAt:l.updatedAt,assets:i}}async function My(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=Zu(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=Ts.relative(process.cwd(),t.dest)||t.dest,o;try{o=await Xo(t,{token:r,force:e.force})}catch(a){let c=a instanceof Error?a.message:String(a);console.error(a?.code==="ENOENT"?`File not found: ${i}`:`Could not push to ${t.origin}: ${c}`),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}
|
|
1540
1540
|
push refused: the bulb text was not pushed.`),process.exitCode=1;return;case"pushed":{console.log(`pushed ${i} \u2192 ${s}/full`),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}
|
|
1541
1541
|
pull to see the remote: typebulb pull ${i}
|
|
1542
|
-
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 ed=S(()=>{"use strict";ee();Go();Ge()});var sr=S(()=>{"use strict";Ae();vy();Zn();Cy();ru();_y();Iy();xs();cn();cn();Lo();Vu();Ae();Go();ed();at()});import{existsSync as
|
|
1542
|
+
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 ed=S(()=>{"use strict";ee();Go();Ge()});var sr=S(()=>{"use strict";Ae();vy();Zn();Cy();ru();_y();Iy();xs();cn();cn();Lo();Vu();Ae();Go();ed();at()});import{existsSync as vO,mkdirSync as SO,readFileSync as kO,rmSync as xO,writeFileSync as EO}from"fs";import{homedir as AO}from"os";import*as ir from"path";function CO(){return PO.replace('"__TB_SKILL_PATH__"',JSON.stringify(Es())).replace('"__TB_BIN_PATH__"',JSON.stringify(ss()))}function By(){try{if(!vO(td()))return}catch{return}try{let n=TO(),e=CO(),t;try{t=kO(n,"utf8")}catch{}t!==e&&(SO(ir.dirname(n),{recursive:!0}),EO(n,e))}catch{}for(let n of OO())try{xO(n,{force:!0})}catch{}}var td,TO,OO,PO,Dy=S(()=>{"use strict";sr();td=()=>ir.join(AO(),".pi","agent"),TO=()=>ir.join(td(),"extensions","typebulb.ts"),OO=()=>["typebulb-wait.ts","matchu-patchu.ts"].map(n=>ir.join(td(),"extensions",n)),PO=String.raw`// Generated by typebulb — do not edit; overwritten on each run.
|
|
1543
1543
|
import { spawn } from "node:child_process";
|
|
1544
1544
|
import { existsSync } from "node:fs";
|
|
1545
1545
|
|
|
@@ -1807,23 +1807,23 @@ export default function (pi) {
|
|
|
1807
1807
|
try { pi.on("session_shutdown", () => { stopping = true; if (watcher) { try { watcher.kill(); } catch (e) {} watcher = null; } for (const c of pending) { try { c.kill(); } catch (e) {} } pending.clear(); }); } catch (e) {}
|
|
1808
1808
|
} catch (e) { logErr("load", e && e.message); }
|
|
1809
1809
|
}
|
|
1810
|
-
`});function Y(n){return n?.message??String(n)}var z,Dt=S(()=>{"use strict";z=process.cwd()});import{spawn as jy}from"child_process";import{StringDecoder as
|
|
1811
|
-
`))>=0;){let o=r.slice(0,i);r=r.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var
|
|
1810
|
+
`});function Y(n){return n?.message??String(n)}var z,Dt=S(()=>{"use strict";z=process.cwd()});import{spawn as jy}from"child_process";import{StringDecoder as _O}from"string_decoder";function MO(n,e){let t=new _O("utf8"),r="";n.on("data",s=>{r+=typeof s=="string"?s:t.write(s);let i;for(;(i=r.indexOf(`
|
|
1811
|
+
`))>=0;){let o=r.slice(0,i);r=r.slice(i+1),o.endsWith("\r")&&(o=o.slice(0,-1)),o&&e(o)}})}var RO,Fy,Uy,nd,qy,IO,NO,$O,Jy,LO,Qo,Zo,Ky,Wy=S(()=>{"use strict";Dt();RO=3e4,Fy=18e4,Uy="starting pi\u2026",nd=5e3,qy=2e3,IO=2e3,NO=12e4,$O=8e3,Jy=15e3,LO=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"]),Qo=new Set;process.on("exit",()=>{for(let n of Qo)try{n.kill()}catch{}});Zo=class{#e;#s=!1;#t=0;#r=!1;#T=0;#a=!1;#m=null;#c=[];#g=null;#n=null;#i=null;#d=new Map;#o=[];#y=null;#S=null;#b=null;#f;#p;#w="";#_=1;#l=new Map;#k;#v;constructor(e,t,r=(s,i)=>jy(s,{cwd:i,shell:!0,stdio:["pipe","pipe","pipe"],env:{...process.env,TYPEBULB_MIRROR:"1"}})){if(this.#k=new Promise(o=>{this.#v=o}),t?.includes('"')){this.#p="session path contains a quote \u2014 cannot drive it",this.#v();return}let s=t?`pi --mode rpc --session "${t}"`:"pi --mode rpc",i;try{i=r(s,e)}catch(o){this.#p=`could not start pi: ${Y(o)}`,this.#v();return}this.#e=i,this.#f=t,this.#r=!0,this.#T=Date.now()+Fy,this.#n={text:Uy,kind:"info"},Qo.add(i),i.stdout&&MO(i.stdout,o=>this.#I(o)),i.stderr&&i.stderr.on("data",o=>{this.#w=(this.#w+o.toString()).slice(-IO)}),i.on("error",o=>this.#P(`could not start pi: ${o.message}`)),i.on("exit",o=>{this.#e===i&&this.#P(o?`pi exited (code ${o})${this.#w.trim()?`: ${this.#w.trim()}`:""}`:"pi exited"),Qo.delete(i),this.#v()}),this.#u({type:"get_state"}).then(o=>{let a=o.data?.sessionFile;typeof a=="string"&&a&&(this.#f=a);let c=o.data?.model;c&&typeof c.id=="string"&&c.id&&(this.#b=c.id)}).catch(()=>{}).finally(()=>this.#R())}#R(){this.#r&&(this.#r=!1,this.#n?.text===Uy&&(this.#n=null),this.#i&&(this.#i.until=Date.now()+Jy),!this.#s&&Date.now()<this.#t&&(this.#t=Date.now()+nd),this.#A())}get streaming(){return this.#s||Date.now()<this.#t}get draft(){return this.#m}get echo(){return this.#g}get queue(){return this.#y}get stats(){return this.#S}get model(){return this.#b}get sessionFile(){return this.#f}get error(){return this.#p}get status(){if(this.#n)return this.#n;if(this.#i){if(Date.now()<this.#i.until)return{text:this.#i.text,kind:this.#i.kind};this.#i=null}return this.#d.size?{text:[...this.#d.values()].join(" \xB7 "),kind:"info"}:null}get dialog(){let e=Date.now();for(;this.#o.length;){let t=this.#o[0];if(e<t.until)return t.req;this.#o.shift(),t.ownTimeout||this.#x({type:"extension_ui_response",id:t.req.id,cancelled:!0})}return null}notice(e,t){this.#h(e,t)}respondUi(e,t){let r=this.#o.findIndex(o=>o.req.id===e);if(r<0)return{ok:!1,error:"dialog expired or already answered"};let[s]=this.#o.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.#x(i),{ok:!0}}async rpc(e){if(!LO.has(e.type))return{ok:!1,error:`command not allowed: ${e.type}`};try{let t=await this.#u(e);if(t.success&&e.type==="set_model"){let r=t.data?.id;typeof r=="string"&&r&&(this.#b=r)}if(t.success&&(e.type==="fork"||e.type==="clone")){try{let s=(await this.#u({type:"get_state"})).data?.sessionFile;typeof s=="string"&&s&&(this.#f=s)}catch{}return{ok:!0,data:{...t.data??{},sessionFile:this.#f}}}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=e.trimStart().startsWith("/"),i=r?s?{type:"prompt",message:e,streamingBehavior:t?.followUp?"followUp":"steer"}:{type:t?.followUp?"follow_up":"steer",message:e}:{type:"prompt",message:e},o=c=>{r||(this.#t=c,s||(this.#g=e))};if(this.#r)return this.#u(i).catch(()=>{}),o(this.#T+nd),{ok:!0};let a;try{a=await this.#u(i)}catch(c){return{ok:!1,error:Y(c)}}return a.success&&o(Date.now()+nd),a.success?{ok:!0}:{ok:!1,error:a.error??"pi rejected the message"}}async stop(){if(this.#e){if(this.#r){this.#x({type:"abort"}),this.#t=0;return}try{await this.#u({type:"abort"})}catch{}}}clearCompletedDraft(){this.#a||(this.#m=null)}clearEcho(){this.#g=null}async dispose(){let e=this.#e;if(e){if(this.#e=void 0,this.#r=!1,this.#s){try{e.stdin?.write(JSON.stringify({type:"abort"})+`
|
|
1812
1812
|
`)}catch{}await Promise.race([this.#k,Ky(qy)])}try{e.stdin?.end()}catch{}if(await Promise.race([this.#k,Ky(qy)]),e.exitCode===null&&!e.killed)if(process.platform==="win32"&&e.pid)try{jy("taskkill",["/pid",String(e.pid),"/T","/F"],{stdio:"ignore"})}catch{}else try{e.kill("SIGKILL")}catch{}Qo.delete(e),this.#o=[],this.#C("pi was shut down")}}#x(e){try{this.#e?.stdin?.write(JSON.stringify(e)+`
|
|
1813
1813
|
`)}catch{}}#O(){let e=this.#c[this.#c.length-1];this.#m={text:this.#c.filter(t=>t?.kind==="text").map(t=>t.text).join(""),thinking:this.#c.filter(t=>t?.kind==="thinking").map(t=>t.text).join(`
|
|
1814
|
-
`),tool:e?.kind==="tool"?e.name:void 0}}#E(e){let t=Array.isArray(e?.content)?e.content:[];this.#c=t.map(r=>({kind:r.type==="thinking"?"thinking":r.type==="toolCall"?"tool":"text",text:(r.type==="thinking"?r.thinking:r.text)??"",name:r.name})),this.#O()}#h(e,t){let r=e.length>200?e.slice(0,200)+"\u2026":e;r&&(this.#i={text:r,kind:t,until:Date.now()+(t==="info"
|
|
1815
|
-
`)}catch(c){clearTimeout(a),this.#l.delete(s),o(new Error(Y(c)))}})}#I(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let r=t,s=r.id?this.#l.get(r.id):void 0;s&&(this.#l.delete(r.id),clearTimeout(s.timer),s.resolve(r));return}case"agent_start":this.#s=!0,this.#t=0;return;case"agent_end":this.#s=!1,this.#t=0,this.#a=!1,this.#n=null,this.#y=null,this.#A();return;case"message_start":{let r=t.message;if(r?.role!=="assistant")return;this.#a=!0,this.#E(r);return}case"message_update":{if(!this.#a)return;if(t.message){this.#E(t.message);return}let r=t.assistantMessageEvent;if(!r||typeof r.contentIndex!="number")return;let s=r.type.startsWith("thinking")?"thinking":r.type.startsWith("toolcall")?"tool":"text",i=this.#c[r.contentIndex]??={kind:s,text:""};i.kind=s,typeof r.delta=="string"&&s!=="tool"&&(i.text+=r.delta),typeof r.content=="string"&&(i.text=r.content),r.toolCall?.name&&(i.name=r.toolCall.name),this.#O();return}case"message_end":if(!this.#a)return;t.message&&this.#E(t.message),this.#a=!1;return;case"auto_retry_start":this.#n={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#n=null,t.success===!1&&this.#h(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#n={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#n=null;let r=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#h(`compaction failed: ${t.errorMessage}`,"error"):r?.tokensBefore&&this.#h(`compacted: ~${Math.round(r.tokensBefore/1e3)}k \u2192 ~${Math.round((r.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#A();return}case"queue_update":{let r=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#y=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.#o.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??
|
|
1816
|
-
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function
|
|
1817
|
-
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;r.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:r,usage:u,model:s.model,cost:l?.cost?.total}}return{events:r}}chainWorking(e){let t;for(let a of e)Zy(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=
|
|
1814
|
+
`),tool:e?.kind==="tool"?e.name:void 0}}#E(e){let t=Array.isArray(e?.content)?e.content:[];this.#c=t.map(r=>({kind:r.type==="thinking"?"thinking":r.type==="toolCall"?"tool":"text",text:(r.type==="thinking"?r.thinking:r.text)??"",name:r.name})),this.#O()}#h(e,t){let r=e.length>200?e.slice(0,200)+"\u2026":e;r&&(this.#i={text:r,kind:t,until:Date.now()+(t==="info"?$O:Jy)})}#A(){this.#u({type:"get_session_stats"}).then(e=>{if(!e.success||!e.data)return;let t=e.data;this.#S={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(()=>{})}#u(e){let t=this.#e;if(!t?.stdin?.writable)return Promise.reject(new Error(this.#p??"pi is not running"));let r=this.#r?Fy:RO,s=`tb-${this.#_++}`;return new Promise((i,o)=>{let a=setTimeout(()=>{this.#l.delete(s),o(new Error(`pi did not respond (${Math.round(r/1e3)}s)`))},r);a.unref?.(),this.#l.set(s,{resolve:i,timer:a});try{t.stdin.write(JSON.stringify({id:s,...e})+`
|
|
1815
|
+
`)}catch(c){clearTimeout(a),this.#l.delete(s),o(new Error(Y(c)))}})}#I(e){let t;try{t=JSON.parse(e)}catch{return}switch(t.type){case"response":{let r=t,s=r.id?this.#l.get(r.id):void 0;s&&(this.#l.delete(r.id),clearTimeout(s.timer),s.resolve(r));return}case"agent_start":this.#s=!0,this.#t=0;return;case"agent_end":this.#s=!1,this.#t=0,this.#a=!1,this.#n=null,this.#y=null,this.#A();return;case"message_start":{let r=t.message;if(r?.role!=="assistant")return;this.#a=!0,this.#E(r);return}case"message_update":{if(!this.#a)return;if(t.message){this.#E(t.message);return}let r=t.assistantMessageEvent;if(!r||typeof r.contentIndex!="number")return;let s=r.type.startsWith("thinking")?"thinking":r.type.startsWith("toolcall")?"tool":"text",i=this.#c[r.contentIndex]??={kind:s,text:""};i.kind=s,typeof r.delta=="string"&&s!=="tool"&&(i.text+=r.delta),typeof r.content=="string"&&(i.text=r.content),r.toolCall?.name&&(i.name=r.toolCall.name),this.#O();return}case"message_end":if(!this.#a)return;t.message&&this.#E(t.message),this.#a=!1;return;case"auto_retry_start":this.#n={text:`retrying after a transient error (attempt ${Number(t.attempt)||1}/${Number(t.maxAttempts)||"?"})\u2026`,kind:"warning"};return;case"auto_retry_end":this.#n=null,t.success===!1&&this.#h(`retries exhausted: ${String(t.finalError??"unknown error")}`,"error");return;case"compaction_start":this.#n={text:"compacting context\u2026",kind:"info"};return;case"compaction_end":{this.#n=null;let r=t.result;typeof t.errorMessage=="string"&&t.errorMessage?this.#h(`compaction failed: ${t.errorMessage}`,"error"):r?.tokensBefore&&this.#h(`compacted: ~${Math.round(r.tokensBefore/1e3)}k \u2192 ~${Math.round((r.estimatedTokensAfter??0)/1e3)}k tokens`,"info"),this.#A();return}case"queue_update":{let r=Array.isArray(t.steering)?t.steering.map(String):[],s=Array.isArray(t.followUp)?t.followUp.map(String):[];this.#y=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.#o.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??NO),ownTimeout:s!==void 0})}else if(r==="notify"){let s=t.notifyType==="warning"?"warning":t.notifyType==="error"?"error":"info";this.#h(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.#d.set(s,t.statusText):this.#d.delete(s)}return}default:return}}#P(e){this.#p=e,this.#r=!1,this.#s=!1,this.#t=0,this.#a=!1,this.#m=null,this.#c=[],this.#g=null,this.#n=null,this.#i=null,this.#d.clear(),this.#o=[],this.#y=null,this.#S=null,this.#b=null,this.#e=void 0,this.#C(e)}#C(e){for(let[,t]of this.#l)clearTimeout(t.timer),t.resolve({type:"response",success:!1,error:e});this.#l.clear()}},Ky=n=>new Promise(e=>{setTimeout(e,n).unref?.()})});import{existsSync as Hy,readFileSync as BO,realpathSync as DO}from"fs";import{join as fn,dirname as Gy,resolve as jO}from"path";import{homedir as Yy}from"os";function UO(n,e){let t=fn(n,".pi");if(FO.some(s=>Hy(fn(t,s))))return!0;let r=fn(e,".agents","skills");for(let s=n;;){let i=fn(s,".agents","skills");if(i!==r&&Hy(i))return!0;let o=Gy(s);if(o===s)return!1;s=o}}function qO(n,e){for(let t=e;;){if(n[t]===!0||n[t]===!1)return!0;let r=Gy(t);if(r===t)return!1;t=r}}function Xy(n,e){try{let t=e?.agentDir??fn(Yy(),".pi","agent"),r=Vy(e?.home??process.env.HOME??Yy()),s=Vy(jO(n));if(!UO(s,r))return null;let i=zy(fn(t,"settings.json")).defaultProjectTrust;return i==="always"||i==="never"||qO(zy(fn(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 FO,Vy,zy,Qy=S(()=>{"use strict";FO=["settings.json","extensions","skills","prompts","themes","SYSTEM.md","APPEND_SYSTEM.md"],Vy=n=>{try{return DO(n)}catch{return n}},zy=n=>{try{return JSON.parse(BO(n,"utf8"))}catch{return{}}}});import{statSync as JO,openSync as KO,readSync as WO,closeSync as HO,existsSync as eb}from"fs";import{join as ea}from"path";import{homedir as rd}from"os";import{execFile as YO}from"child_process";async function zO(n){let e=ea(rd(),".pi","agent","bin",process.platform==="win32"?"fd.exe":"fd");for(let t of["fd","fdfind",...eb(e)?[e]:[]]){let r=await new Promise(s=>{YO(t,["--base-directory",n,"--type","f","--follow","--hidden","--exclude",".git"],{maxBuffer:67108864},(i,o)=>s(i?null:o))});if(r!==null)return r.split(`
|
|
1816
|
+
`).filter(Boolean).map(s=>s.replace(/\\/g,"/"))}return null}function GO(n){return`--${n.replace(/^[/\\]/,"").replace(/[/\\:]/g,"-")}--`}function Zy(n){return n.type==="message"?XO(n.message?.role):n.type==="custom_message"?n.display!==!1:!1}var VO,XO,or,sd=S(()=>{"use strict";Xr();Fl();Xi();Dy();Wy();Qy();VO=ea(rd(),".pi","agent","sessions");XO=n=>n==="user"||n==="assistant"||n==="toolResult"||n==="bashExecution";or=class extends At{displayName="Pi Mirror";detectsSelf(){return process.env.PI_CODING_AGENT==="true"}detectsInstalled(){return eb(ea(rd(),".pi","agent"))}ensureHarnessSupport(){By()}createDriver(e,t){let r=new Zo(e,t),s=Xy(e);return s&&r.notice(s,"warning"),r}walkFiles(e){return zO(e)}sessionsDir(e){return ea(VO,GO(e))}listSessionFiles(e){return Gi(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 Zy(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:Le(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(d=>d.type==="text").map(d=>d.text??"").join(""),a=i.filter(d=>d.type==="thinking").map(d=>d.thinking??"").join(`
|
|
1817
|
+
`),c=i.filter(d=>d.type==="toolCall").map(d=>({id:d.id??"",name:d.name??"",input:d.arguments??{}}));if(o||a||c.length){let d=Date.parse(e.timestamp??""),p=!isNaN(d)&&d>=t;r.push({type:"assistant",text:o,thinking:a,tools:c,live:p})}let l=s.usage,f=l?(l.input??0)+(l.output??0)+(l.cacheRead??0)+(l.cacheWrite??0):0,u=l&&f>0&&s.stopReason!=="aborted"&&s.stopReason!=="error"?{in:l.input??0,out:l.output??0,cached:l.cacheRead??0,cacheCreate:l.cacheWrite??0}:void 0;return{events:r,usage:u,model:s.model,cost:l?.cost?.total}}return{events:r}}chainWorking(e){let t;for(let a of e)Zy(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=KO(e,"r")}catch{return""}try{let s=65536;try{s=JO(e).size}catch{}let i=(u,d)=>{let p=Buffer.alloc(d),y=WO(t,p,0,d,u);return p.subarray(0,y).toString("utf8")},o=i(0,Math.min(65536,s)),a=s>65536?i(s-65536,65536):"",c=u=>{let d="";for(let p of u.split(`
|
|
1818
1818
|
`))if(p.includes('"session_info"'))try{let y=JSON.parse(p);y?.type==="session_info"&&typeof y.name=="string"&&y.name&&(d=y.name)}catch{}return d},l="";for(let u of o.split(`
|
|
1819
|
-
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{
|
|
1820
|
-
`):""}}});var ta,tb=S(()=>{"use strict";ta=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as
|
|
1819
|
+
`))if(!(l||!u.includes('"type"')))try{let d=JSON.parse(u);d?.type==="message"&&d.message?.role==="user"&&(l=this.contentText(d.message.content).replace(/\s+/g," ").trim())}catch{}let f=c(a)||c(o)||l;return f?f.slice(0,200):""}finally{HO(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"?ve(e):Array.isArray(e)?e.map(t=>typeof t?.text=="string"?ve(t.text):t?.type==="image"&&t.data?zi(t.data,t.mimeType):"").filter(Boolean).join(`
|
|
1820
|
+
`):""}}});var ta,tb=S(()=>{"use strict";ta=class{#e=new Map;accept(e,t){return this.#e.get(e)===t?!1:(this.#e.set(e,t),!0)}}});import{execFile as QO}from"child_process";import{promisify as ZO}from"util";import{readFile as eP}from"fs/promises";import{resolve as nb,sep as tP}from"path";async function Je(n,e){let{stdout:t}=await nP("git",n,{cwd:e,maxBuffer:67108864});return t}async function pn(){if(na)return na;try{na=(await Je(["rev-parse","--show-toplevel"],z)).trim()}catch{}return na}function rP(n,e){let t=e===" "?n:e;return t==="?"?"U":t}async function od(){let n=await pn();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:rP(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 c=/^(\d+|-)\t(\d+|-)\t(.*)$/.exec(o[a]);if(!c)continue;let l=c[3]||o[a+=2];l&&i.set(l,{add:+c[1]||0,del:+c[2]||0,binary:c[1]==="-"})}for(let a of t){let c=i.get(a.path);c&&(c.binary?a.binary=!0:(a.add=c.add,a.del=c.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 ad(n){let e=await pn();if(!e)return{ok:!1,error:"not a git repository"};try{if((await Je(["status","--porcelain","-z","--",n],e)).startsWith("??")){let s=nb(e,n);if(!s.startsWith(nb(e)+tP))return{ok:!1,error:"outside repository"};let i=await eP(s);return i.includes(0)?id("Binary file (not shown)",!1):id(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 id(r,!1)}catch(t){return{ok:!1,error:Y(t)}}}var nP,rb,na,id,Os=S(()=>{"use strict";Dt();nP=ZO(QO),rb=2e6;id=(n,e)=>({ok:!0,text:n.slice(0,rb),untracked:e,truncated:n.length>rb})});function ra(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 cd=S(()=>{"use strict"});function sb(){return sP.map(([n,e])=>lt(n,e)).filter(n=>typeof n!="string")}function ib(){return sb().length>0}async function sa(n,e,t=0){let r=AbortSignal.timeout(e);for(let s of sb()){try{let i=await Lt(s,{messages:[{role:"user",content:n}],effort:t,webSearch:!1,signal:r});if(i.ok){let o=(await Pu(i,s.protocol)).trim();if(o)return o}}catch{}if(r.aborted)return}}var sP,ld=S(()=>{"use strict";an();sr();sP=[["openrouter","openai/gpt-5.6-luna"],["openai","gpt-5.6-luna"]]});var ia,oa,ob=S(()=>{"use strict";ia=".typebulb/paste",oa={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 iP,mkdirSync as oP,writeFileSync as aP,readFileSync as cP}from"fs";import{join as aa}from"path";function ab(){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 dP(n){return n.trim().toLowerCase().replace(/\.[a-z0-9]{1,4}$/,"").replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)}async function fP(n){let e=await sa(`Reply with ONLY a short kebab-case filename (2-5 words, lowercase, no extension) describing this text:
|
|
1821
1821
|
|
|
1822
|
-
${n.slice(0,
|
|
1823
|
-
`+
|
|
1822
|
+
${n.slice(0,uP)}`,lP);return e&&dP(e)||void 0}async function cb(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=aa(n,ia);try{oP(t,{recursive:!0})}catch(a){return{ok:!1,error:Y(a)}}let r,s,i;if(e.kind==="image"){if(r=`img-${ab()}`,s=Object.keys(oa).find(a=>oa[a]===e.mime)??"png",i=Buffer.from(e.data,"base64"),!i.length)return{ok:!1,error:"empty image data"}}else r=await fP(e.data)??`paste-${ab()}`,s="md",i=e.data;let o=`${r}.${s}`;for(let a=2;iP(aa(t,o));a++)o=`${r}-${a}.${s}`;try{aP(aa(t,o),i)}catch(a){return{ok:!1,error:Y(a)}}return{ok:!0,path:`${ia}/${o}`}}function lb(n,e){if(!/^[\w-]+(\.[\w-]+)*$/.test(e))return{ok:!1,error:"bad name"};let t=e.slice(e.lastIndexOf(".")+1).toLowerCase(),r=oa[t];if(!r)return{ok:!1,error:"not an image"};try{return{ok:!0,mime:r,base64:cP(aa(n,ia,e)).toString("base64")}}catch{return{ok:!1,error:"not found"}}}var lP,uP,ub=S(()=>{"use strict";ld();Dt();ob();lP=4e3,uP=4e3});async function pb(n,e=""){let t=n.trim();if(!t)return{ok:!1,error:"nothing to summarize"};if(!ib())return{ok:!1,error:"Summary needs OPENROUTER_API_KEY or OPENAI_API_KEY in this project\u2019s .env.",setup:!0};let r=e.trim()?fb+`CONTEXT \u2014 the user message this reply answers. It is context only: never summarize it, and never report it as the reply's content.
|
|
1823
|
+
`+hP(e.trim())+`
|
|
1824
1824
|
|
|
1825
1825
|
REPLY TO SUMMARIZE:
|
|
1826
|
-
`+t.slice(0,db):fb+t.slice(0,db),s=await sa(r,
|
|
1826
|
+
`+t.slice(0,db):fb+t.slice(0,db),s=await sa(r,pP,1);return s?{ok:!0,text:s}:{ok:!1,error:"the model call failed or timed out"}}var pP,db,fb,hP,hb=S(()=>{"use strict";ld();pP=2e4,db=24e3,fb=`Summarize this assistant reply for someone who wants its substance without the prose.
|
|
1827
1827
|
|
|
1828
1828
|
- Markdown. Start with the direct answer, recommendation, result, or status. If it is qualified, put the qualification in that same opening sentence; do not make the reader infer it from later bullets.
|
|
1829
1829
|
- Preserve material limits and conditions that change the answer: exceptions, tradeoffs, prerequisites, uncertainty, incomplete validation, and clauses such as but, only when, unless, or if. Cut only filler hedges (for example, "I think" or "arguably") that change nothing.
|
|
@@ -1838,23 +1838,23 @@ Reply with the summary alone.
|
|
|
1838
1838
|
|
|
1839
1839
|
---
|
|
1840
1840
|
|
|
1841
|
-
`,
|
|
1841
|
+
`,hP=(n,e=4e3)=>{if(n.length<=e)return n;let t=Math.floor(e/2)-20;return n.slice(0,t)+`
|
|
1842
1842
|
|
|
1843
1843
|
[snipped for brevity]
|
|
1844
1844
|
|
|
1845
|
-
`+n.slice(n.length-t)}});function
|
|
1846
|
-
`))>=0;){let H=m.partial.slice(0,$);if(m.partial=m.partial.slice($+1),!H.trim())continue;let we=n.parseEntry(H);if(!we)continue;let le=n.idOf(we);le&&(m.entries.set(le,we),!n.isSidechain(we)&&n.isLeafType(we)&&(T=le))}if(!T)return;let F=[],B=m.entries.get(T),V=!1;for(;B;){if(F.push(B),n.idOf(B)===m.chainLastId){V=!0;break}let H=n.parentOf(B);B=H?m.entries.get(H):void 0}if(V)for(let H=F.length-2;H>=0;H--)hr(F[H]);else{m.chainLastId!==void 0&&(m.buffer.push({type:"cleared"}),m.buffer.push({type:"session",sessionId:m.sessionId}),m.latest={in:0,out:0,cached:0,cacheCreate:0});let H=new Set(F.map(le=>n.idOf(le))),we=Z(m.entries);for(let le=F.length-1;le>=0;le--)hr(F[le]),J(n.idOf(F[le]),we,H)}m.chainLastId=T}function Z(m){let k=new Map;for(let b of m.values()){let T=n.parentOf(b);if(!T)continue;let $=k.get(T);$?$.push(b):k.set(T,[b])}return k}function J(m,k,b){if(!m)return;let T=k.get(m);if(!T)return;let $=T.filter(H=>!n.isSidechain(H));if($.length<2)return;let F=$.filter(H=>!b.has(n.idOf(H)));if(!F.length)return;let B=[],V=0;for(let H of F){let we=G(H,k);B.push(...we.events),V+=we.count}V>0&&e.buffer.push({type:"fork",atId:m,count:V,events:B})}function G(m,k){let b=[],T=[m];for(;T.length;){let B=T.pop();if(n.isSidechain(B))continue;b.push(B);let V=k.get(n.idOf(B)??"");if(V)for(let H of V)T.push(H)}b.sort((B,V)=>(Date.parse(n.timestampOf(B)??"")||0)-(Date.parse(n.timestampOf(V)??"")||0));let $=[];for(let B of b)n.isRecoveryNoise(B)||$.push(...n.apply(B,e.sessionStartMs).events);return{count:$.reduce((B,V)=>B+(V.type==="user"||V.type==="assistant"?1:0),0),events:$}}function hr(m){try{let{events:k,usage:b,model:T,cost:$}=n.apply(m,e.sessionStartMs);for(let F of k)e.buffer.push(F);k.some(F=>F.type==="assistant")&&i()?.d.clearCompletedDraft(),k.some(F=>F.type==="user")&&i()?.d.clearEcho(),T&&(e.latestModel=T),b&&(e.latest=b),(b||$)&&e.buffer.push({type:"usage",...e.latest,cost:$})}catch(k){console.error("[mirror] skipped malformed entry:",Y(k))}}async function Kt(){return{cwd:e.cwd,pid:process.pid,composer:!!n.createDriver,elsewhere:await w()}}async function w(){if(n.listSessionFiles(e.cwd).length)return;let m=await pn();if(!m)return;let k=vb(m).toLowerCase();for(let b=vb(e.cwd);b.toLowerCase()!==k;){let T=
|
|
1847
|
-
`).filter(Boolean):await n.walkFiles?.(e.cwd)??[];return(await Promise.all(k.map(async T=>{try{return{f:T,m:(await
|
|
1848
|
-
`)){if(!F.trim())continue;let B=n.parseEntry(F);if(!B)continue;let V=n.searchText(B);V&&T.push({text:V,lower:V.toLowerCase()})}return rf.set(m,{mtime:k,turns:T}),T}async function wv(m){let k=m.toLowerCase(),b=[];for(let{sessionId:T,file:$,mtime:F}of n.listSessionFiles(e.cwd).sort((B,V)=>V.mtime-B.mtime)){let{hitCount:B,snippet:V}=ra(bv($,F),k);if(B&&(b.push({sessionId:T,mtime:F,preview:n.readPreview($),hitCount:B,snippet:V}),b.length>=
|
|
1849
|
-
`)){if(!B.trim())continue;let V=n.parseEntry(B);if(V)for(let H of n.apply(V,e.sessionStartMs).events)H.type==="assistant"&&H.text.trim()&&($=H.text.trim())}let F=$.length>sf?$.slice(0,sf).trimEnd()+"\u2026":$;return of.set(m,{mtime:k,text:F}),F}async function Sv(m){let k=n.listSessionFiles(e.cwd).find(b=>b.sessionId===m);return{text:k?vv(k.file,k.mtime):""}}async function kv(m){let k=e,b=n.listSessionFiles(k.cwd).find(T=>T.sessionId===m);if(!b){let T=c().find($=>$.sessionId===m)?.rec;return T?((r!==T||k.sessionId!==T.id)&&(r=T,M(void 0,T.id),k.everAttached=!0,f()),{ok:!0}):{ok:!1,error:"session not found"}}return b.file===k.file?{ok:!0}:(A(b),u(),f(),{ok:!0})}return g(e.cwd),x(e.cwd),P(),{info:Kt,poll:X,logInlineStatus:R,listSessions:yv,searchSessions:wv,sessionPeek:Sv,attach:kv,composerSend:ne,composerStop:Ke,composerNew:ht,composerFiles:Ba,composerUiRespond:re,composerRpc:Ze,composerPaste:hv,composerPasteRead:mv,summarizeTurn:gv,shutdownComposer:Da}}var
|
|
1850
|
-
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=ra(i,e);o&&t.push({path:r.path,hitCount:o,snippet:a})}return t}async function Sd(n,e,t){let r=z;e!=null&&tr(n,e);let s=await io(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 kd(n){return{cap:await qu(n)}}async function xd(n,e){return tr(n,e),{ok:!0}}async function Ed(n,e){return Ye(n,e)}async function Ad(){return Ps&&Date.now()-Ps.fetchedAt
|
|
1851
|
-
${n}`;return jt?.key===e&&Date.now()-jt.fetchedAt<=
|
|
1845
|
+
`+n.slice(n.length-t)}});function mP(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 mb,gb=S(()=>{"use strict";mb=(n,e)=>mP(n,{key:e,desc:!0})});import{existsSync as yb,openSync as gP,readSync as yP,closeSync as bP,statSync as ar,readdirSync as bb,watchFile as wP,unwatchFile as wb,mkdirSync as vP,writeFileSync as SP,readFileSync as ca,unlinkSync as kP,rmSync as xP}from"fs";import{stat as EP}from"fs/promises";import{dirname as AP,join as hn,resolve as vb}from"path";function CP(n){if(!Number.isInteger(n))return!0;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function cr(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 m of t)if(m.file===e.file)return m;return}return r}function o(m){let k={d:n.createDriver(e.cwd,m),file:m,id:`new:${++s}`,startedAt:Date.now()};return t.add(k),e.file||(r=k),k}function a(){let m=[...t].filter(b=>b.file);if(!m.length)return[];let k=new Map(n.listSessionFiles(e.cwd).map(b=>[b.file,b.sessionId]));return m.map(b=>{let T=k.get(b.file);return{rec:b,sessionId:T??b.id,pending:T===void 0}})}let c=()=>a().filter(m=>m.pending&&m.rec.prompt!==void 0);async function l(m){t.delete(m),r===m&&(r=void 0);try{await m.d.dispose()}catch(k){console.error("[composer] dispose:",Y(k))}}function f(){let m=i(),k=new Set(c().map(b=>b.rec));for(let b of[...t])b!==m&&(k.has(b)||b.d.streaming||b.d.queue||b.d.error||l(b))}function u(){for(let m of t)m.d.sessionFile&&m.file!==m.d.sessionFile&&(m.file=m.d.sessionFile);if(r&&!e.file&&r.file){let m=n.listSessionFiles(e.cwd).find(k=>k.file===r.file);m&&A(m)}r&&!e.file&&r.prompt!==void 0&&e.sessionId!==r.id&&(M(void 0,r.id),e.everAttached=!0)}let d=m=>hn(m,OP),p=(m,k)=>hn(d(m),`${k}.lock`);function y(m,k){try{let b=p(m,k);if(Date.now()-ar(b).mtimeMs>=Sb)return!1;try{let T=parseInt(ca(b,"utf8").trim(),10);if(T===process.pid||!CP(T))return!1}catch{}return!0}catch{return!1}}function h(m,k){if(k)try{vP(d(m),{recursive:!0}),SP(p(m,k),String(process.pid))}catch(b){console.error("[lock] claim failed:",Y(b))}}function g(m){try{xP(hn(m,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function x(m){let k=d(m);if(!yb(k))return;let b;try{b=bb(k)}catch{return}let T=Date.now();for(let $ of b){if(!$.endsWith(".lock"))continue;let F=hn(k,$);try{let B=ar(F);T-B.mtimeMs>PP&&kP(F)}catch{}}}function v(m){try{return ar(m),!1}catch(k){return k.code==="ENOENT"}}function P(){let m=e;if(m.file&&!v(m.file)){h(m.cwd,m.sessionId);return}let k=_(m);k&&A(k)}function _(m){if(!m.everAttached)return C(m.cwd)??I(m.cwd,()=>!0)}function C(m){let k=d(m);if(!yb(k))return;let b;try{b=bb(k)}catch{return}let T;for(let F of b)if(F.endsWith(".lock"))try{let B=ar(hn(k,F));if(Date.now()-B.mtimeMs>=Sb||parseInt(ca(hn(k,F),"utf8").trim(),10)!==process.pid)continue;(!T||B.mtimeMs>T.mtime)&&(T={sessionId:F.slice(0,-5),mtime:B.mtimeMs})}catch{}if(!T)return;let $=n.listSessionFiles(m).find(F=>F.sessionId===T.sessionId);if(!(!$||v($.file)))return $}function I(m,k){return n.listSessionFiles(m).sort((b,T)=>T.mtime-b.mtime).find(b=>!y(m,b.sessionId)&&k(b))}function M(m,k){let b=e;if(b.file)try{wb(b.file)}catch{}b.file=m,b.sessionId=k,b.partial="",b.offset=0,b.latest={in:0,out:0,cached:0,cacheCreate:0},b.latestModel=null,b.entries=new Map,b.chainLastId=void 0,b.buffer.push({type:"cleared"}),b.buffer.push({type:"session",sessionId:k})}function A(m){let k=e;r=void 0,M(m.file,m.sessionId),k.everAttached=!0,h(k.cwd,m.sessionId),U();try{wb(m.file)}catch{}wP(m.file,{interval:200},()=>U())}function j(){M(void 0,"")}function U(){let m=e;if(!m.file)return;let k;try{k=ar(m.file).size}catch{return}if(k<=m.offset)return;let b;try{b=gP(m.file,"r")}catch{return}try{let H=k-m.offset,we=Buffer.alloc(H),le=0;for(;le<H;){let af=yP(b,we,le,H-le,m.offset+le);if(!af)break;le+=af}m.offset+=le,m.partial+=we.subarray(0,le).toString("utf8")}finally{bP(b)}let T,$;for(;($=m.partial.indexOf(`
|
|
1846
|
+
`))>=0;){let H=m.partial.slice(0,$);if(m.partial=m.partial.slice($+1),!H.trim())continue;let we=n.parseEntry(H);if(!we)continue;let le=n.idOf(we);le&&(m.entries.set(le,we),!n.isSidechain(we)&&n.isLeafType(we)&&(T=le))}if(!T)return;let F=[],B=m.entries.get(T),V=!1;for(;B;){if(F.push(B),n.idOf(B)===m.chainLastId){V=!0;break}let H=n.parentOf(B);B=H?m.entries.get(H):void 0}if(V)for(let H=F.length-2;H>=0;H--)hr(F[H]);else{m.chainLastId!==void 0&&(m.buffer.push({type:"cleared"}),m.buffer.push({type:"session",sessionId:m.sessionId}),m.latest={in:0,out:0,cached:0,cacheCreate:0});let H=new Set(F.map(le=>n.idOf(le))),we=Z(m.entries);for(let le=F.length-1;le>=0;le--)hr(F[le]),J(n.idOf(F[le]),we,H)}m.chainLastId=T}function Z(m){let k=new Map;for(let b of m.values()){let T=n.parentOf(b);if(!T)continue;let $=k.get(T);$?$.push(b):k.set(T,[b])}return k}function J(m,k,b){if(!m)return;let T=k.get(m);if(!T)return;let $=T.filter(H=>!n.isSidechain(H));if($.length<2)return;let F=$.filter(H=>!b.has(n.idOf(H)));if(!F.length)return;let B=[],V=0;for(let H of F){let we=G(H,k);B.push(...we.events),V+=we.count}V>0&&e.buffer.push({type:"fork",atId:m,count:V,events:B})}function G(m,k){let b=[],T=[m];for(;T.length;){let B=T.pop();if(n.isSidechain(B))continue;b.push(B);let V=k.get(n.idOf(B)??"");if(V)for(let H of V)T.push(H)}b.sort((B,V)=>(Date.parse(n.timestampOf(B)??"")||0)-(Date.parse(n.timestampOf(V)??"")||0));let $=[];for(let B of b)n.isRecoveryNoise(B)||$.push(...n.apply(B,e.sessionStartMs).events);return{count:$.reduce((B,V)=>B+(V.type==="user"||V.type==="assistant"?1:0),0),events:$}}function hr(m){try{let{events:k,usage:b,model:T,cost:$}=n.apply(m,e.sessionStartMs);for(let F of k)e.buffer.push(F);k.some(F=>F.type==="assistant")&&i()?.d.clearCompletedDraft(),k.some(F=>F.type==="user")&&i()?.d.clearEcho(),T&&(e.latestModel=T),b&&(e.latest=b),(b||$)&&e.buffer.push({type:"usage",...e.latest,cost:$})}catch(k){console.error("[mirror] skipped malformed entry:",Y(k))}}async function Kt(){return{cwd:e.cwd,pid:process.pid,composer:!!n.createDriver,elsewhere:await w()}}async function w(){if(n.listSessionFiles(e.cwd).length)return;let m=await pn();if(!m)return;let k=vb(m).toLowerCase();for(let b=vb(e.cwd);b.toLowerCase()!==k;){let T=AP(b);if(T===b)return;b=T;let $=n.listSessionFiles(b).length;if($)return{dir:b,count:$}}}w().then(m=>{m&&console.log(`No sessions for ${e.cwd} \u2014 ${m.count} exist for ${m.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let E=new ta;async function R(m,k){E.accept(m,k)&&console.log(k)}function L(){let m=n.sessionAlive(e.sessionId,e.cwd);if(m!==void 0)return m;if(!e.file)return!1;try{return Date.now()-ar(e.file).mtimeMs<1e4}catch{return!1}}function N(){return n.chainWorking([...e.entries.values()])&&L()}function K(){!n.createDriver||i()||e.latestModel||N()||o(e.file)}async function X(m){let k=e;P(),u(),K(),f();let b=i();for(let B of t)B!==b&&B.d.dialog;let T=a().filter(B=>B.rec.d.streaming).map(B=>B.sessionId),$=N(),F=n.createDriver?{streaming:!!b?.d.streaming,foreign:!b&&$,draft:b?.d.draft??null,echo:b?.d.echo??null,status:b?.d.status??null,dialog:b?.d.dialog??null,queue:b?.d.queue??null,stats:b?.d.stats??null,model:b?.d.model??null,error:b?.d.error}:void 0;return{events:k.buffer.slice(m),cursor:k.buffer.length,working:!!b?.d.streaming||$,latestModel:k.latestModel,composer:F,busy:T}}async function fe(){P(),u();let m=i();if(m?.d.error&&!m.d.streaming&&(await l(m),m=void 0),!m){if(N())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};m=o(e.file)}let k=m;return{ok:!0,d:k.d,markSent:b=>{k.prompt===void 0&&(k.prompt=b)}}}async function ne(m,k){if(!n.createDriver)return{ok:!1,error:"not supported"};let b=String(m??"").trim();if(!b)return{ok:!1,error:"empty message"};let T=await fe();if(!T.ok)return T;let $=await T.d.send(b,k);return $.ok&&T.markSent(b),$}async function re(m,k){let b=i();return b?b.d.respondUi(String(m??""),k??{}):{ok:!1,error:"no dialog pending"}}async function Ze(m,k){if(!n.createDriver)return{ok:!1,error:"not supported"};if(!m||typeof m.type!="string")return{ok:!1,error:"bad command"};if(k?.spawn){let T=await fe();return T.ok?T.d.rpc(m):T}let b=i();return!b||b.d.error?{ok:!1,error:"not running"}:b.d.rpc(m)}async function Ke(){let m=i();if(m)try{await m.d.stop()}catch(k){console.error("[composer] stop:",Y(k))}return{ok:!0}}async function ht(){return n.createDriver?(u(),!e.file&&r&&r.prompt===void 0&&!r.d.streaming&&!r.d.error?{ok:!0}:(r?.d.error&&await l(r),r=void 0,j(),o(void 0),f(),{ok:!0})):{ok:!1,error:"not supported"}}async function Ba(){if(!n.createDriver)return[];let m=await Je(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),k=m!==null?m.split(`
|
|
1847
|
+
`).filter(Boolean):await n.walkFiles?.(e.cwd)??[];return(await Promise.all(k.map(async T=>{try{return{f:T,m:(await EP(hn(e.cwd,T))).mtimeMs}}catch{return{f:T,m:0}}}))).sort((T,$)=>$.m-T.m).map(T=>T.f)}function Da(){for(let m of[...t])l(m)}async function hv(m){return n.createDriver?cb(e.cwd,m):{ok:!1,error:"not supported"}}async function mv(m){return lb(e.cwd,String(m??""))}async function gv(m,k){return pb(String(m??""),String(k??""))}async function yv(){let m=n.listSessionFiles(e.cwd).map(({sessionId:b,file:T,mtime:$})=>({sessionId:b,mtime:$,preview:n.readPreview(T)})),k=c().map(b=>({sessionId:b.sessionId,mtime:b.rec.startedAt,preview:b.rec.prompt??"",pending:!0}));return mb([...m,...k],b=>b.mtime)}let rf=new Map;function bv(m,k){let b=rf.get(m);if(b&&b.mtime===k)return b.turns;let T=[],$="";try{$=ca(m,"utf8")}catch{return[]}for(let F of $.split(`
|
|
1848
|
+
`)){if(!F.trim())continue;let B=n.parseEntry(F);if(!B)continue;let V=n.searchText(B);V&&T.push({text:V,lower:V.toLowerCase()})}return rf.set(m,{mtime:k,turns:T}),T}async function wv(m){let k=m.toLowerCase(),b=[];for(let{sessionId:T,file:$,mtime:F}of n.listSessionFiles(e.cwd).sort((B,V)=>V.mtime-B.mtime)){let{hitCount:B,snippet:V}=ra(bv($,F),k);if(B&&(b.push({sessionId:T,mtime:F,preview:n.readPreview($),hitCount:B,snippet:V}),b.length>=_P))break}return b}let sf=800,of=new Map;function vv(m,k){let b=of.get(m);if(b&&b.mtime===k)return b.text;let T="";try{T=ca(m,"utf8")}catch{return""}let $="";for(let B of T.split(`
|
|
1849
|
+
`)){if(!B.trim())continue;let V=n.parseEntry(B);if(V)for(let H of n.apply(V,e.sessionStartMs).events)H.type==="assistant"&&H.text.trim()&&($=H.text.trim())}let F=$.length>sf?$.slice(0,sf).trimEnd()+"\u2026":$;return of.set(m,{mtime:k,text:F}),F}async function Sv(m){let k=n.listSessionFiles(e.cwd).find(b=>b.sessionId===m);return{text:k?vv(k.file,k.mtime):""}}async function kv(m){let k=e,b=n.listSessionFiles(k.cwd).find(T=>T.sessionId===m);if(!b){let T=c().find($=>$.sessionId===m)?.rec;return T?((r!==T||k.sessionId!==T.id)&&(r=T,M(void 0,T.id),k.everAttached=!0,f()),{ok:!0}):{ok:!1,error:"session not found"}}return b.file===k.file?{ok:!0}:(A(b),u(),f(),{ok:!0})}return g(e.cwd),x(e.cwd),P(),{info:Kt,poll:X,logInlineStatus:R,listSessions:yv,searchSessions:wv,sessionPeek:Sv,attach:kv,composerSend:ne,composerStop:Ke,composerNew:ht,composerFiles:Ba,composerUiRespond:re,composerRpc:Ze,composerPaste:hv,composerPasteRead:mv,summarizeTurn:gv,shutdownComposer:Da}}var TP,OP,Sb,PP,_P,la=S(()=>{"use strict";Dt();tb();Os();cd();ub();hb();gb();TP=".typebulb",OP=`${TP}/locks`,Sb=5e3,PP=6e4;_P=50});import{existsSync as pd,mkdirSync as RP,readFileSync as kb,writeFileSync as IP}from"fs";import{join as mn,isAbsolute as NP}from"path";async function md(n,e){let t=NP(n)?n:mn(z,n);return pd(t)?(Ku(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function gd(n){let e=z,t=Ju(n),r=mn(e,"typebulbs");RP(r,{recursive:!0});let s=nu(t),i=`${s}.bulb.md`;for(let l=2;pd(mn(r,i))&&kb(mn(r,i),"utf8")!==t;l++)i=`${s}-${l}.bulb.md`;let o=mn(r,i);pd(o)||IP(o,t);let a=mn("typebulbs",i),c=await io(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:c.pid,url:c.url}}async function yd(){return Q(z)}async function bd(n){return await Xt(n),{ok:!0}}async function wd(){let n=await un(z);return jo(z).filter(e=>!e.serverOnly).map(e=>({...e,trusted:dn(e.path),batches:ju(e.path),lastRunAt:n(e.path)}))}async function vd(n){let e=n.toLowerCase(),t=[];for(let r of jo(z).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=kb(r.path,"utf8")}catch{continue}let i=[];for(let c of s.split(`
|
|
1850
|
+
`)){let l=c.replace(/\s+/g," ").trim();l&&i.push({text:l,lower:l.toLowerCase()})}let{hitCount:o,snippet:a}=ra(i,e);o&&t.push({path:r.path,hitCount:o,snippet:a})}return t}async function Sd(n,e,t){let r=z;e!=null&&tr(n,e);let s=await io(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 kd(n){return{cap:await qu(n)}}async function xd(n,e){return tr(n,e),{ok:!0}}async function Ed(n,e){return Ye(n,e)}async function Ad(){return Ps&&Date.now()-Ps.fetchedAt<=LP?Ps.samples:(ud??=MP().finally(()=>{ud=null}),ud)}async function MP(){try{let n=await fetch(`${$P}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Eb)});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:Va(i.config)}));return Ps={samples:s,fetchedAt:Date.now()},s}catch{return Ps?.samples??[]}}async function Td(n){return hd.test(n)?Tb(xb,"samples",n,!0):{ok:!1,error:"bad slug"}}async function Pd(){let n=Od();if(!n)return{bulbs:[]};let e=`${ua()}
|
|
1851
|
+
${n}`;return jt?.key===e&&Date.now()-jt.fetchedAt<=BP?{user:jt.user,bulbs:jt.bulbs}:(dd??=DP(e,n).finally(()=>{dd=null}),dd)}async function fd(n,e,t){let r=await fetch(`${n}${e}`,{headers:t,signal:AbortSignal.timeout(Eb)});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 DP(n,e){let t={Authorization:`Bearer ${e}`};try{let r=ua(),s;try{s=await fd(r,"/api/me",t)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await fd(r,"/api/me",t)}let o=(await fd(r,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:Va(a.config)}));return jt={key:n,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return jt?.key===n?{user:jt.user,bulbs:jt.bulbs}:{bulbs:[]}}}async function Cd(n,e,t=!1){return!hd.test(e)||!hd.test(n)?{ok:!1,error:"bad slug"}:Tb(ua(),n,e,t)}async function Tb(n,e,t,r){let s=Ho(e,t);try{let i=await zo({origin:n,userSlug:e,slug:t,dest:mn(z,s)},{force:r,token:Od(),timeoutMs:Ab});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 _d(n,e=!1){let t=Od();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=Vo(n,z,ua()),s=await Xo(r,{token:t,force:e,timeoutMs:Ab});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 $P,xb,LP,Eb,Ab,Ps,ud,hd,BP,jt,dd,ua,Od,da=S(()=>{"use strict";sr();Dt();cd();ee();$P="https://api.typebulb.com",xb="https://typebulb.com",LP=3600*1e3,Eb=5e3,Ab=15e3,Ps=null,ud=null;hd=/^[a-z0-9][a-z0-9-]*$/,BP=300*1e3,jt=null,dd=null,ua=()=>Io("TYPEBULB_ORIGIN",z)||xb,Od=()=>Io("TYPEBULB_TOKEN",z)});import{readFileSync as Nd,writeFileSync as Pb,mkdirSync as jP,appendFileSync as Cb,rmSync as Ob}from"fs";import{join as ha,dirname as FP}from"path";import{createServer as UP}from"http";function Ft(n){try{return JSON.parse(Nd(n,"utf8"))}catch{return null}}function pa(n,e){jP(FP(n),{recursive:!0}),Pb(n,JSON.stringify(e,null,2)+`
|
|
1852
1852
|
`)}function Rb(n,e,t){let r=ha(n,".gitignore"),s="";try{s=Nd(r,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(c=>c.trim())),o=e.filter(c=>!i.has(c));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
1853
1853
|
`)?`
|
|
1854
1854
|
`:"";try{Cb(r,a+t+`
|
|
1855
1855
|
`+o.join(`
|
|
1856
1856
|
`)+`
|
|
1857
|
-
`)}catch(c){console.error("[switcher] .gitignore update failed",Y(c))}}function
|
|
1857
|
+
`)}catch(c){console.error("[switcher] .gitignore update failed",Y(c))}}function HP(n){let e=i=>{let o=i.exec(n);return o?Number(o[1]):0},t=e(/"cache_read_input_tokens":\s*(\d+)/),r=e(/"cache_creation_input_tokens":\s*(\d+)/),s=e(/"input_tokens":\s*(\d+)/);t>0||r>0?Rs="live":s>WP&&(Rs="uncached")}function Nb(n,e){let t={"content-type":"application/json",authorization:`Bearer ${e}`,"anthropic-version":n.headers["anthropic-version"]||"2023-06-01"},r=n.headers["anthropic-beta"];return typeof r=="string"&&(t["anthropic-beta"]=r),t}function YP(n){if(Array.isArray(n?.messages))for(let e of n.messages){if(!Array.isArray(e?.content))continue;let t=e.content.filter(r=>r?.type!=="thinking"&&r?.type!=="redacted_thinking");t.length&&t.length!==e.content.length&&(e.content=t)}}function $b(n){let e;try{e=JSON.parse(n)}catch{return n}_s=typeof e?.model=="string"?e.model:null,Qe&&(e.model=Qe),yn&&(e.provider=Ib(yn));let t=/haiku/i.test(_s||"");return Is!=null&&!t&&(e.reasoning={effort:Rd[Is]}),delete e.thinking,e.output_config&&delete e.output_config.effort,YP(e),JSON.stringify(e)}function VP(){let n="",e=0,t=new Map,r=new Set(["thinking","redacted_thinking"]),s=i=>{let o=/^data: (.*)$/m.exec(i);if(!o)return i;let a;try{a=JSON.parse(o[1])}catch{return i}switch(a.type){case"message_start":return t.clear(),e=0,i;case"content_block_start":{if(r.has(a.content_block?.type))return t.set(a.index,null),null;let c=e++;return t.set(a.index,c),a.index=c,`event: ${a.type}
|
|
1858
1858
|
data: ${JSON.stringify(a)}
|
|
1859
1859
|
|
|
1860
1860
|
`}case"content_block_delta":case"content_block_stop":{let c=t.get(a.index);return c==null?null:(a.index=c,`event: ${a.type}
|
|
@@ -1862,11 +1862,11 @@ data: ${JSON.stringify(a)}
|
|
|
1862
1862
|
|
|
1863
1863
|
`)}default:return i}};return i=>{n+=i;let o="",a;for(;(a=n.indexOf(`
|
|
1864
1864
|
|
|
1865
|
-
`))!==-1;){let c=n.slice(0,a);if(n=n.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function
|
|
1865
|
+
`))!==-1;){let c=n.slice(0,a);if(n=n.slice(a+2),!c.trim())continue;let l=s(c);l!==null&&(o+=l)}return o}}function zP(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 Cs(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 GP(n,e,t){if(!Qe){Cs(e,400,"invalid_request_error",KP);return}let r=process.env.OPENROUTER_API_KEY;if(!r){Cs(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($d,{method:"POST",headers:Nb(n,r),body:$b(t),signal:s.signal})}catch(u){Cs(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"),c=i.body.getReader(),l=new TextDecoder,f=a?VP():null;try{for(;;){let{done:u,value:d}=await c.read();if(u)break;if(d)if(f){let p=l.decode(d,{stream:!0});HP(p);let y=f(p);y&&e.write(y)}else e.write(Buffer.from(d))}}catch{}finally{e.writableEnded||e.end()}}async function XP(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(!Qe||!r)return s();try{let i=await fetch(`${$d}/count_tokens`,{method:"POST",headers:Nb(n,r),body:$b(t)});if(!i.ok)return s();let o=await i.text();e.writeHead(200,{"content-type":"application/json"}),e.end(o)}catch{s()}}function QP(n,e){let t=n.url||"/";if(n.method==="HEAD"){e.writeHead(200),e.end();return}if(n.method!=="POST"){Cs(e,404,"not_found_error",t);return}zP(n).then(r=>{if(t.includes("count_tokens"))return XP(n,e,r);if(t.includes("/v1/messages"))return GP(n,e,r);Cs(e,404,"not_found_error",t)})}function ZP(){return lr&&gn?Promise.resolve(gn):new Promise((n,e)=>{let t=UP(QP);t.on("error",e),t.listen(0,"127.0.0.1",()=>{lr=t,gn=t.address().port,console.log(`[switcher] wire proxy listening on ${fa(gn)}`),n(gn)})})}function eC(){try{lr?.close()}catch{}lr=null,gn=null}function tC(n,e){let t=ma(n),r=Ft(t),s=r||{};if((!s.env||typeof s.env!="object")&&(s.env={}),s.env.ANTHROPIC_BASE_URL===fa(e)&&s.env.ANTHROPIC_AUTH_TOKEN)return;let i=ga(n);if(!Ft(i)){let a={};for(let c of _b)a[c]=c in s.env?s.env[c]:null;pa(i,{managedBy:"agent-switcher",fileExisted:r!==null,snapshot:a,active:null})}s.env.ANTHROPIC_BASE_URL=fa(e),s.env.ANTHROPIC_AUTH_TOKEN=JP,pa(t,s),Rb(n,[".claude/settings.local.json",".claude/.cc-switcher.json"],"# agent switcher (local Claude Code model override)")}function nC(n,e,t){let r=ga(n),s=Ft(r)||{managedBy:"agent-switcher",fileExisted:!1,snapshot:{}};s.active={model:e,provider:t},pa(r,s)}function Lb(n){let e=ma(n),t=ga(n),r=Ft(t),s=Ft(e);if(s?.env){let i=r?.snapshot||{};for(let o of _b){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{Ob(e,{force:!0})}catch{}else pa(e,s)}try{Ob(t,{force:!0})}catch{}}async function rC(){let n=!!process.env.OPENROUTER_API_KEY,e=[];try{e=(await ct()).filter(r=>r.provider==="openrouter"&&!Ld(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:$u()??void 0;return{hasKey:n,models:e,error:t}}async function sC(){if(lr&&Qe)return{active:!0,managed:!0,model:Qe,port:gn,provider:yn,routedModel:_s,caching:Rs,reasoning:Is,externalBaseUrl:null};let n=Ft(ma(z))?.env||{};return{active:!1,managed:!1,model:null,port:null,provider:null,routedModel:null,caching:"unknown",reasoning:Is,externalBaseUrl:n.ANTHROPIC_BASE_URL||null}}async function Mb(n,e){let t=await ZP();return Qe=n,yn=e,tC(z,t),t}async function iC({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(Ld(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 Mb(n,Md[n]??null),_s=null,Rs="unknown",nC(z,n,yn)}catch(e){return{ok:!1,error:`failed to start the wire proxy: ${Y(e)}`}}return{ok:!0}}async function oC({level:n}){return n!=null&&(!Number.isInteger(n)||n<0||n>=Rd.length)?{ok:!1,error:`reasoning level must be 0\u2013${Rd.length-1} or null`}:(Is=n,{ok:!0,level:n})}async function aC(){return Lb(z),Qe=null,yn=null,_s=null,Rs="unknown",{ok:!0}}async function cC({key:n}){let e=(n||"").trim();if(!e)return{ok:!1,error:"empty key"};let t=z,r=ha(t,".env"),s="";try{s=Nd(r,"utf8")}catch{}try{if(/^\s*OPENROUTER_API_KEY\s*=/m.test(s))Pb(r,s.replace(/^\s*OPENROUTER_API_KEY\s*=.*$/m,`OPENROUTER_API_KEY=${e}`));else{let i=s&&!s.endsWith(`
|
|
1866
1866
|
`)?`
|
|
1867
1867
|
`:"";Cb(r,i+`OPENROUTER_API_KEY=${e}
|
|
1868
|
-
`)}}catch(i){return{ok:!1,error:Y(i)}}return process.env.OPENROUTER_API_KEY=e,Rb(t,[".env"],"# secrets"),{ok:!0}}function
|
|
1869
|
-
`)}catch(o){return{ok:!1,error:`could not write ${n}: ${Y(o)}`}}return{ok:!0,count:e.length}}var
|
|
1868
|
+
`)}}catch(i){return{ok:!1,error:Y(i)}}return process.env.OPENROUTER_API_KEY=e,Rb(t,[".env"],"# secrets"),{ok:!0}}function lC(){if(!(!lr&&!Qe)){try{Lb(z)}catch{}eC()}}function uC(n,e){return Bb.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 dC(n){if(Bb.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 fC(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=Id(e?.cache_read_input_tokens)||Id(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 pC({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(Ld(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 c=new AbortController,l=setTimeout(()=>c.abort(),2e4);try{let f=JSON.stringify(a?{...i,provider:Ib(a)}:i),u=await fetch($d,{method:"POST",signal:c.signal,headers:s,body:f}),d=await u.json().catch(()=>({}));return{r:u,j:d}}finally{clearTimeout(l)}};try{let{r:a,j:c}=await o();if(!a.ok){let x=c?.error?.message||c?.message||JSON.stringify(c).slice(0,300);return{ok:!0,callable:!1,status:a.status,ms:Date.now()-t,error:uC(a.status,x),restriction:dC(x)}}let l=typeof c?.provider=="string"?c.provider:void 0,f=c?.content?.find?.(x=>x.type==="text")?.text??c?.content?.[0]?.text??"ok",u=Id(c?.usage?.cache_creation_input_tokens),{r:d,j:p}=await o(l),{works:y,read:h,note:g}=fC(d.ok,p?.usage,l);return y===!0&&l&&(Md[n]=l,Qe===n&&(yn=l)),{ok:!0,callable:!0,status:a.status,ms:Date.now()-t,provider:l,sample:String(f).trim().slice(0,60),cache:{works:y,created:u,read:h,note:g}}}catch(a){let c=Y(a);return{ok:!0,callable:!1,ms:Date.now()-t,error:/abort/i.test(c)?"timed out (20s)":c}}}var qP,$d,JP,KP,_b,WP,Rd,ma,ga,fa,Ld,lr,gn,Qe,yn,_s,Rs,Is,Md,Id,Ib,Bb,Db=S(()=>{"use strict";sr();Dt();qP="https://openrouter.ai/api",$d=`${qP}/v1/messages`,JP="typebulb-proxy-managed",KP="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.",_b=["ANTHROPIC_BASE_URL","ANTHROPIC_AUTH_TOKEN"],WP=5e3,Rd=["low","medium","high"],ma=n=>ha(n,".claude","settings.local.json"),ga=n=>ha(n,".claude",".cc-switcher.json"),fa=n=>`http://127.0.0.1:${n}`;Ld=n=>/^anthropic\//i.test(n)||/claude/i.test(n),lr=null,gn=null,Qe=null,yn=null,_s=null,Rs="unknown",Is=1,Md={},Id=n=>typeof n=="number"?n:0,Ib=n=>({order:[n],allow_fallbacks:!1});Bb=/data policy|no endpoints|no allowed providers|privacy|requires.*(training|logging|data)/i;(async function(){try{let e=Ft(ga(z)),t=e?.active?.model;if(!t)return;let s=(Ft(ma(z))?.env||{}).ANTHROPIC_BASE_URL||"";if(!/127\.0\.0\.1|localhost/.test(s))return;let i=await Mb(t,e.active.provider??Md[t]??null);console.log(`[switcher] re-adopted override after restart: ${t} via ${fa(i)}`)}catch(e){console.error("[switcher] boot reconcile failed",Y(e))}})()});var Fb={};Fa(Fb,{attach:()=>SC,blockToMarkdown:()=>Qi,breakout:()=>gd,capText:()=>ve,cleanUserText:()=>Tt,clearSwitchModel:()=>aC,composerPasteRead:()=>kC,displayName:()=>hC,downloadSample:()=>Td,firstLineDigest:()=>Le,git:()=>Je,gitChangedFiles:()=>od,gitDiff:()=>ad,info:()=>mC,isHiddenTurn:()=>Qr,launchBulb:()=>Sd,listBreakouts:()=>yd,listBulbFiles:()=>wd,listMyBulbs:()=>Pd,listSamples:()=>Ad,listSessions:()=>bC,listSwitchModels:()=>rC,logInlineStatus:()=>yC,openFile:()=>md,poll:()=>gC,predictTrustOf:()=>kd,probeModel:()=>pC,pullRemoteBulb:()=>Cd,pushLocalBulb:()=>_d,readBulbLog:()=>Ed,repoRoot:()=>pn,saveOpenRouterKey:()=>cC,searchBulbs:()=>vd,searchSessions:()=>wC,sessionPeek:()=>vC,setBulbTrust:()=>xd,setReasoning:()=>oC,setSwitchModel:()=>iC,shutdownSwitcher:()=>lC,stopBreakout:()=>bd,summarizeTurn:()=>xC,switchState:()=>sC,toolResultDigest:()=>Kl});var jb,hC,mC,gC,yC,bC,wC,vC,SC,kC,xC,Ub=S(()=>{"use strict";la();Zi();da();Os();Db();Zi();Xr();jb=new $n,hC=jb.displayName,{info:mC,poll:gC,logInlineStatus:yC,listSessions:bC,searchSessions:wC,sessionPeek:vC,attach:SC,composerPasteRead:kC,summarizeTurn:xC}=cr(jb)});var Jb={};Fa(Jb,{attach:()=>RC,breakout:()=>gd,composerPasteRead:()=>IC,displayName:()=>EC,downloadSample:()=>Td,git:()=>Je,gitChangedFiles:()=>od,gitDiff:()=>ad,info:()=>AC,launchBulb:()=>Sd,listBreakouts:()=>yd,listBulbFiles:()=>wd,listMyBulbs:()=>Pd,listSamples:()=>Ad,listSessions:()=>PC,logInlineStatus:()=>OC,openFile:()=>md,poll:()=>TC,predictTrustOf:()=>kd,pullRemoteBulb:()=>Cd,pushLocalBulb:()=>_d,readBulbLog:()=>Ed,repoRoot:()=>pn,searchBulbs:()=>vd,searchSessions:()=>CC,sessionPeek:()=>_C,setBulbTrust:()=>xd,stopBreakout:()=>bd,summarizeTurn:()=>NC});var qb,EC,AC,TC,OC,PC,CC,_C,RC,IC,NC,Kb=S(()=>{"use strict";la();Hl();da();Os();qb=new Ln,EC=qb.displayName,{info:AC,poll:TC,logInlineStatus:OC,listSessions:PC,searchSessions:CC,sessionPeek:_C,attach:RC,composerPasteRead:IC,summarizeTurn:NC}=cr(qb)});import{readFileSync as $C,writeFileSync as LC,mkdirSync as MC}from"fs";import{homedir as BC}from"os";import*as ya from"path";async function Yb(){try{let n=await fetch(new URL("/api/tags",Hb()).toString(),{signal:AbortSignal.timeout(DC)});return n.ok?((await n.json()).models??[]).map(t=>t.name).filter(t=>!!t):[]}catch{return[]}}function Vb(n){let e;try{e=$C(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&&!Bd(r)}}}catch{}return{json:void 0,unreadable:!0}}function Bd(n){let e=n?.providers;return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function jC(n){let e=Bd(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 zb(){let{json:n,unreadable:e}=Vb(Wb());return e?{installed:[],configured:null}:{installed:await Yb(),configured:jC(n)}}async function Gb(){let n=await Yb();return n.length?FC(Wb(),n,Hb()):{ok:!1,error:"Ollama is not running (or has no models installed)"}}function FC(n,e,t){let{json:r,unreadable:s}=Vb(n);if(s)return{ok:!1,error:`could not parse ${n} \u2014 edit the ollama provider there yourself`};let i={...r??{},providers:{...Bd(r)??{},ollama:{baseUrl:`${t}/v1`,api:"openai-completions",apiKey:"ollama",models:e.map(o=>({id:o}))}}};try{MC(ya.dirname(n),{recursive:!0}),LC(n,JSON.stringify(i,null,2)+`
|
|
1869
|
+
`)}catch(o){return{ok:!1,error:`could not write ${n}: ${Y(o)}`}}return{ok:!0,count:e.length}}var DC,Wb,Hb,Xb=S(()=>{"use strict";Dt();sr();DC=1500,Wb=()=>ya.join(BC(),".pi","agent","models.json"),Hb=()=>zn(process.env.OLLAMA_HOST??"http://localhost:11434")});var Zb={};Fa(Zb,{attach:()=>VC,breakout:()=>gd,composerFiles:()=>QC,composerNew:()=>XC,composerPaste:()=>t_,composerPasteRead:()=>n_,composerRpc:()=>e_,composerSend:()=>zC,composerStop:()=>GC,composerUiRespond:()=>ZC,displayName:()=>UC,downloadSample:()=>Td,git:()=>Je,gitChangedFiles:()=>od,gitDiff:()=>ad,info:()=>qC,launchBulb:()=>Sd,listBreakouts:()=>yd,listBulbFiles:()=>wd,listMyBulbs:()=>Pd,listSamples:()=>Ad,listSessions:()=>WC,logInlineStatus:()=>KC,ollamaOffer:()=>zb,ollamaSync:()=>Gb,openFile:()=>md,poll:()=>JC,predictTrustOf:()=>kd,pullRemoteBulb:()=>Cd,pushLocalBulb:()=>_d,readBulbLog:()=>Ed,repoRoot:()=>pn,searchBulbs:()=>vd,searchSessions:()=>HC,sessionPeek:()=>YC,setBulbTrust:()=>xd,shutdownComposer:()=>s_,stopBreakout:()=>bd,summarizeTurn:()=>r_});var Qb,UC,qC,JC,KC,WC,HC,YC,VC,zC,GC,XC,QC,ZC,e_,t_,n_,r_,s_,ew=S(()=>{"use strict";la();sd();da();Os();Xb();Qb=new or,UC=Qb.displayName,{info:qC,poll:JC,logInlineStatus:KC,listSessions:WC,searchSessions:HC,sessionPeek:YC,attach:VC,composerSend:zC,composerStop:GC,composerNew:XC,composerFiles:QC,composerUiRespond:ZC,composerRpc:e_,composerPaste:t_,composerPasteRead:n_,summarizeTurn:r_,shutdownComposer:s_}=cr(Qb)});import*as pv from"fs/promises";import*as pt from"path";Ks();ee();function jl(n){if(!Re.includes(n))throw new Error(`Unknown block kind '${n}' (one of: ${Re.join(", ")})`);return n}function Hm(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=jl(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}Zi();Hl();sd();var ba={claude:{adapter:()=>new $n,server:()=>Promise.resolve().then(()=>(Ub(),Fb))},codex:{adapter:()=>new Ln,server:()=>Promise.resolve().then(()=>(Kb(),Jb))},pi:{adapter:()=>new or,server:()=>Promise.resolve().then(()=>(ew(),Zb))}};function tw(n){return n in ba}function ur(){return Object.keys(ba)}function nw(){return Object.fromEntries(Object.entries(ba).map(([n,e])=>[n,e.adapter]))}function rw(n){return ba[n].server()}var Ns=nw();function sw(){for(let n of Object.values(Ns))try{n().ensureHarnessSupport()}catch{}}function bn(){for(let n of Object.keys(Ns))try{if(Ns[n]().detectsSelf())return n}catch{}}function iw(n){let e=ur(),t=new Map(e.filter(i=>Ns[i]).map(i=>[i,Ns[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 jd=5e3;function Dd(n){try{return n()}catch(e){console.error(e instanceof Error?e.message:String(e)),process.exit(1)}}function ow(n){let t={subcommand:"run",file:"",watch:!0,open:process.env.TERM_PROGRAM==="vscode"||bn()!==void 0?"link":"window",server:!1,trust:!1,noTrust:!1,force:!1,follow:!1,clear:!1,help:!1,version:!1,callArgs:[],hasArgsFlag:!1},r=["call","check","predict","logs","wait","stop","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="window";else if(a==="--no-open")t.open="none";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 c=n[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --mode (e.g. --mode staging)"),process.exit(1)),t.mode=c}else if(a==="--batch"){let c=n[++o];(!c||c.startsWith("-"))&&(console.error("Missing value for --batch (a batch name, e.g. --batch pilot)"),process.exit(1));let l=c.replace(/[\\/]+$/,"");(!l||/[\\/]/.test(l)||l==="."||l==="..")&&(console.error(`Invalid --batch value: ${c} (a single folder name \u2014 no path separators or dot segments)`),process.exit(1)),t.batch=l}else if(a==="--follow"||a==="-f")t.follow=!0;else if(a==="--clear")t.clear=!0;else if(a==="--run"){let c=n[++o];if(c==="latest")t.run="latest";else{let l=parseInt(c,10);(isNaN(l)||l<1)&&(console.error(`Invalid --run value: ${c} (a run number, or 'latest')`),process.exit(1)),t.run=l}}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 c=n[++o];c===void 0&&(console.error("Missing value for --match (a literal substring new log lines must contain)"),process.exit(1)),t.match=c}else if(a==="--timeout"){let c=parseInt(n[++o],10);(isNaN(c)||c<=0)&&(console.error(`Invalid --timeout value: ${n[o]} (seconds)`),process.exit(1)),t.timeoutSec=c}else if(a==="--wait"||a.startsWith("--wait="))if(a.startsWith("--wait=")){let c=parseInt(a.slice(7),10);(isNaN(c)||c<=0)&&(console.error(`Invalid --wait value: ${a.slice(7)} (milliseconds)`),process.exit(1)),t.sendWaitMs=c}else t.sendWaitMs=jd;else if(a==="--lines"||a==="-n"){let c=parseInt(n[++o],10);(isNaN(c)||c<0)&&(console.error(`Invalid --lines value: ${n[o]}`),process.exit(1)),t.lines=c}else if(a==="--port"||a==="-p"){let c=n[++o],l=parseInt(c,10);isNaN(l)&&(console.error(`Invalid port: ${c}`),process.exit(1)),t.port=l}else if(a==="--replace"||a.startsWith("--replace=")){let c=a.startsWith("--replace=")?a.slice(10):n[++o]??"",l=Dd(()=>pf(c));t.local&&(console.error(`--replace can only be used once (got '${t.local.name}' and '${l.name}')`),process.exit(1)),t.local=l}else if(a==="--args"||a.startsWith("--args=")){t.hasArgsFlag=!0;let c=a.startsWith("--args=")?a.slice(7):n[++o];c===void 0&&(console.error("Missing value for --args (a JSON array, or - to read it from stdin)"),process.exit(1)),t.argsJson=c}else if(!a.startsWith("-")||a==="-"&&t.subcommand==="send")["call","send","get","put","slug"].includes(t.subcommand)?i.push(a):t.file=a;else{let c=t.subcommand==="call"?" (for a negative or dash-leading argument, use --args '<json-array>')":"";console.error(`Unknown option: ${a}${c}`),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=Dd(()=>jl(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=Dd(()=>Hm(i.slice(1)))),t}function aw(){console.log(`
|
|
1870
1870
|
typebulb - Local bulb runner for Typebulb
|
|
1871
1871
|
|
|
1872
1872
|
Usage:
|
|
@@ -2043,7 +2043,7 @@ Examples:
|
|
|
2043
2043
|
typebulb my-editor.bulb.md
|
|
2044
2044
|
typebulb --no-watch --port 8080 my-editor.bulb.md
|
|
2045
2045
|
typebulb .
|
|
2046
|
-
`)}Ge();is();Ks();xs();Ge();import*as _e from"path";import{spawn as
|
|
2046
|
+
`)}Ge();is();Ks();xs();Ge();import*as _e from"path";import{spawn as R_,execSync as I_}from"child_process";import{createRequire as N_}from"module";import{existsSync as $_}from"fs";import*as me from"fs/promises";import*as pe from"path";var Fd=[{name:"es5"},{name:"es2015.core"},{name:"es2015.collection"},{name:"es2015.promise"},{name:"es2015.iterable"},{name:"es2015.symbol"},{name:"es2015.symbol.wellknown"},{name:"es2015.generator"},{name:"es2015.proxy"},{name:"es2015.reflect"},{name:"es2016.array.include"},{name:"es2016.intl"},{name:"es2017.object"},{name:"es2017.string"},{name:"es2017.sharedmemory"},{name:"es2017.typedarrays"},{name:"es2017.date"},{name:"es2017.intl"},{name:"es2018.asynciterable"},{name:"es2018.asyncgenerator"},{name:"es2018.promise"},{name:"es2018.regexp"},{name:"es2018.intl"},{name:"es2019.array"},{name:"es2019.object"},{name:"es2019.string"},{name:"es2019.symbol"},{name:"es2019.intl"},{name:"es2020.bigint"},{name:"es2020.promise"},{name:"es2020.string"},{name:"es2020.sharedmemory"},{name:"es2020.date"},{name:"es2020.number"},{name:"es2020.symbol.wellknown"},{name:"es2020.intl"},{name:"es2021.promise"},{name:"es2021.string"},{name:"es2021.weakref"},{name:"es2021.intl"},{name:"es2022.array"},{name:"es2022.object"},{name:"es2022.error"},{name:"es2022.string"},{name:"es2022.regexp"},{name:"es2022.intl"},{name:"es2023.array"},{name:"es2023.collection"},{name:"es2023.intl",since:"5.5"},{name:"es2024.arraybuffer",since:"5.5"},{name:"es2024.collection",since:"5.5"},{name:"es2024.object",since:"5.5"},{name:"es2024.promise",since:"5.5"},{name:"es2024.regexp",since:"5.5"},{name:"es2024.sharedmemory",since:"5.5"},{name:"es2024.string",since:"5.5"},{name:"esnext.array",since:"5.5"},{name:"esnext.collection"},{name:"esnext.decorators"},{name:"esnext.disposable"},{name:"esnext.error",since:"5.5"},{name:"esnext.float16",since:"5.5"},{name:"esnext.iterator",since:"5.5"},{name:"esnext.object"},{name:"esnext.promise"},{name:"esnext.sharedmemory",since:"5.5"},{name:"esnext.intl"}],Ud=[{name:"dom"},{name:"dom.iterable"},{name:"dom.asynciterable"}];function qd(n,e){if(!e)return n.filter(s=>!s.since);let t={"5.0":0,"5.5":1},r=t[e];return n.filter(s=>!s.since||t[s.since]<=r)}ee();var i_=`
|
|
2047
2047
|
/**
|
|
2048
2048
|
* Get raw data chunk from the Data tab.
|
|
2049
2049
|
* @param index - Chunk index (0-based). Separate chunks with 2 blank lines.
|
|
@@ -2054,7 +2054,7 @@ Examples:
|
|
|
2054
2054
|
* @param index - Chunk index (0-based)
|
|
2055
2055
|
* @throws If chunk is not valid JSON/JSON-ish
|
|
2056
2056
|
*/
|
|
2057
|
-
json<T = unknown>(index: number): T;`,
|
|
2057
|
+
json<T = unknown>(index: number): T;`,o_=`
|
|
2058
2058
|
/**
|
|
2059
2059
|
* Get the insight data produced by the inference layer.
|
|
2060
2060
|
*
|
|
@@ -2147,7 +2147,7 @@ type AiAccess = "own" | "courtesy" | "none";
|
|
|
2147
2147
|
* \`tb.mode\` or the length of \`tb.models()\` \u2014 which hosts offer a courtesy
|
|
2148
2148
|
* model is the host's business and changes without your bulb changing.
|
|
2149
2149
|
*/
|
|
2150
|
-
aiAccess(): Promise<AiAccess>;`,
|
|
2150
|
+
aiAccess(): Promise<AiAccess>;`,a_="\n /**\n * The bulb's theme override (`<html data-theme>`).\n *\n * - Get: the current override \u2014 `'dark'` | `'light'`, or `undefined` when\n * following the OS preference.\n * - Set `'dark'`/`'light'` to force and persist it (per-bulb); set\n * `undefined` to clear the override and follow the OS again.\n *\n * Drives `<html data-theme>`, so render off `html[data-theme=\"\u2026\"]` selectors\n * (or observe the attribute) rather than reading `tb.theme`.\n */\n theme: 'light' | 'dark' | undefined;",pw=`
|
|
2151
2151
|
/**
|
|
2152
2152
|
* The mode this bulb is running in.
|
|
2153
2153
|
*
|
|
@@ -2174,7 +2174,7 @@ type AiAccess = "own" | "courtesy" | "none";
|
|
|
2174
2174
|
readBytes(path: string): Promise<Uint8Array>;
|
|
2175
2175
|
/** Write text or raw bytes to a file. Creates parent directories if needed. */
|
|
2176
2176
|
write(path: string, content: string | Uint8Array): Promise<boolean>;
|
|
2177
|
-
};`,mw="\n /**\n * The bulb's folder \u2014 absolute path to `<bulb-dir>/<filename-stem>/`\n * (or its `batches/<name>/` folder when the run is scoped with `--batch`).\n *\n * For interop only (handing a path to `server.ts` or a spawned tool):\n * `tb.fs` already resolves relative paths against it, so bulb code writing\n * its own files never needs it. CLI only \u2014 throws in ide/published/inline mode.\n */\n readonly dir: string;",
|
|
2177
|
+
};`,mw="\n /**\n * The bulb's folder \u2014 absolute path to `<bulb-dir>/<filename-stem>/`\n * (or its `batches/<name>/` folder when the run is scoped with `--batch`).\n *\n * For interop only (handing a path to `server.ts` or a spawned tool):\n * `tb.fs` already resolves relative paths against it, so bulb code writing\n * its own files never needs it. CLI only \u2014 throws in ide/published/inline mode.\n */\n readonly dir: string;",c_=`
|
|
2178
2178
|
/**
|
|
2179
2179
|
* Async value inspector for tensor-like objects.
|
|
2180
2180
|
*
|
|
@@ -2225,14 +2225,14 @@ type AiAccess = "own" | "courtesy" | "none";
|
|
|
2225
2225
|
*
|
|
2226
2226
|
* @returns The full canonical URL
|
|
2227
2227
|
*/
|
|
2228
|
-
url(): Promise<string>;`,
|
|
2228
|
+
url(): Promise<string>;`,l_="\n /**\n * Subscribe to a value pushed from the terminal via `typebulb send <file> [message]`.\n *\n * The dual of `tb.log` (data out): a value sent *in* from the CLI, no `--trust` required.\n * Use it to start expensive work on demand instead of on load \u2014 e.g. `tb.onMessage(() => start())`\n * \u2014 so hot reloads don't re-trigger it while you edit, and an agent kicks off one run when ready.\n *\n * The message is the JSON-parsed value of what `send` was given (or the raw string if it isn't\n * JSON; `undefined` for a bare `typebulb send <file>`). A non-`undefined` return value (awaited)\n * becomes the reply `send --wait` prints on stdout \u2014 JSON-serializable, at most one handler\n * replying \u2014 the structured read-back for self-tests. Returns an unsubscribe function. Inert in\n * an inline bulb (no sender) \u2014 the handler is registered but never fires.\n *\n * @param handler - Called with each pushed message; may return a JSON-serializable reply.\n * @returns An unsubscribe function.\n */\n onMessage(handler: (message: any) => unknown): () => void;",u_="\n /**\n * Print to the CLI's stdout \u2014 the bulb's log channel, read back with `typebulb logs <file>`.\n *\n * Ungated: needs no `server.ts` block and no `--trust`, so a Restricted client-only bulb can\n * instrument itself. Args cross to the CLI as JSON; where no CLI serves the page (web, inline,\n * or a transport failure) it falls back to the browser console. Works in `server.ts` too (same\n * as `console.log` there).\n */\n log(...args: any[]): void;",d_="\n /**\n * Server-side function proxy.\n *\n * In the CLI, calls exported functions from the `**server.ts**` section.\n *\n * A normal export is awaited for its result (`await tb.server.fn()`). An `async function*`\n * export streams: `for await (const chunk of tb.server.gen())`. The call object supports both;\n * break the `for await` to cancel and tear down the server generator.\n */\n server: Record<string, (...args: any[]) => Promise<any> & AsyncIterable<any>>;",Jd=`${lw}${uw}
|
|
2229
2229
|
/**
|
|
2230
2230
|
* Typebulb utilities namespace.
|
|
2231
2231
|
* Type \`tb.\` to discover available helpers.
|
|
2232
2232
|
*/
|
|
2233
|
-
declare const tb: {${
|
|
2233
|
+
declare const tb: {${i_}${c_}${o_}${u_}${d_}${l_}${dw}${hw}${mw}${fw}${a_}${pw}
|
|
2234
2234
|
};
|
|
2235
|
-
`,
|
|
2235
|
+
`,f_=`
|
|
2236
2236
|
/**
|
|
2237
2237
|
* Print to the CLI's stdout \u2014 the same channel as \`console.log\` here (the server's console IS
|
|
2238
2238
|
* the bulb's log). One log verb across blocks: page-side \`tb.log\` reaches this same stdout.
|
|
@@ -2242,27 +2242,27 @@ declare const tb: {${s_}${a_}${i_}${l_}${u_}${c_}${dw}${hw}${mw}${fw}${o_}${pw}
|
|
|
2242
2242
|
* Typebulb utilities namespace (server-side).
|
|
2243
2243
|
* Type \`tb.\` to discover available helpers.
|
|
2244
2244
|
*/
|
|
2245
|
-
declare const tb: {${
|
|
2245
|
+
declare const tb: {${f_}${dw}${hw}${mw}${fw}${pw}
|
|
2246
2246
|
};
|
|
2247
|
-
`;st();import
|
|
2247
|
+
`;st();import g_ from"p-limit";st();import{resolve as yw}from"resolve.exports";var dt={maxRelativeTypeRefs:500,maxBareDeps:8,maxBareDepth:3,prefetchConcurrency:4,negativeTtlMs:1e4},$s=["index.d.ts","index.d.mts"],Wd=/\.d\.(ts|mts|cts)$/i;function wa(n){return/\.d\.(ts|mts|cts)(?:[?#].*)?$/i.test(n)||/[?&]dts(?:[&#]|$)/i.test(n)}function gw(n){return[`${n}.d.ts`,`${n}.d.mts`]}function Ut(n){if(!n||n==="./"||n==="/")return[...$s];let e=n.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),t=gw(e),r=e.endsWith("/")?e:`${e}/`;return t.push(...gw(`${r}index`)),t}async function dr(n,{retries:e=2,timeoutMs:t=15e3,init:r}={}){for(let s=0;s<=e;s++){let i=new AbortController,o=setTimeout(()=>i.abort(),t);try{let a=await fetch(n,{...r,signal:i.signal});if(p_(a.status)&&s<e)continue;return a}catch{if(s<e)continue;return}finally{clearTimeout(o)}}}function p_(n){return n===408||n===429||n>=500&&n<600}var va=class{constructor(e,t){this.fetchDts=e,this.cdnClient=t}async tryUrls(e){for(let t of e){let r=await this.fetchDts(t);if(r&&(this.looksLikeDts(r.dts)||wa(r.url)))return r}}looksLikeDts(e){return/^\s*export\s*\{\s*\}\s*;?\s*$/m.test(e)?!0:/declare\s+(module|namespace|class|interface|function|const|var|let)/.test(e)||/interface\s+\w+/.test(e)||/type\s+\w+\s*=/.test(e)}async loadPackageAtVersionedRoot(e,t){let r=this.cdnClient.packageJson(new D({name:e,version:t})),s=await dr(r);if(!s?.ok)return;let i;try{i=await s.json()}catch{return}if(i)return{pkg:i,baseDir:this.cdnClient.baseDir(new D({name:e,version:t??i.version})),version:t}}extractPathFromResult(e){if(typeof e=="string")return e;if(Array.isArray(e))return e.find(t=>typeof t=="string")}async tryUntilSuccess(e,t){for(let r of e){let s=await t(r);if(s)return s}}async resolveFromSelected(e,t,r){if(e.kind==="types"){let o=en(e.path);if(!o||o==="/"||o===".")return this.tryUntilSuccess([...$s],t);if(!Wd.test(o)){let a=await this.tryUntilSuccess(Ut(o),t);if(a)return a}return t(o)}let s=Ut(e.path),i=r?.subpath?[...s,...$s]:[...$s,...s];return this.tryUntilSuccess(i,t)}toResolutionResult(e){return{kind:Wd.test(e)?"types":"probe",path:e}}resolveExportsPath(e,t){let r=t||".",s=e;try{let i=this.extractPathFromResult(yw(s,r,{conditions:["types"]}));if(i)return i}catch{}try{return this.extractPathFromResult(yw(s,r,{browser:!0,conditions:["import","default","module","browser","node"]}))}catch{return}}async resolve(e){try{let t=D.parse(e),{pkg:r,baseDir:s}=await this.loadPackageAtVersionedRoot(t.name,t.version)||{};if(!r||!s)return;let i={name:t.name,version:t.version},o=new D(i).format(),a=new D({...i,subpath:t.subpath}).format(),c=u=>this.fetchCandidateFrom(s,t.name,u);if(t.subpath){let u=au(t.subpath),d=this.resolveExportsPath(r,u);if(d){let y=await this.resolveFromSelected(this.toResolutionResult(d),c,{subpath:!0});if(y)return{...y,resolvedPkg:a}}let p=await this.tryUntilSuccess(Ut(u),c);if(p)return{...p,resolvedPkg:a}}let l=r.types??r.typings;if(l){let u=await this.resolveFromSelected({kind:"types",path:l},c);if(u)return{...u,resolvedPkg:o}}let f=this.resolveExportsPath(r,".");if(f){let u=await this.resolveFromSelected(this.toResolutionResult(f),c);if(u)return{...u,resolvedPkg:o}}return}catch{return}}async fetchCandidateFrom(e,t,r){let s=en(r),i=new URL(s,e).toString(),o=await this.tryUrls([i]);return o?{dts:o.dts,url:o.url,resolvedPkg:t}:void 0}};st();import{gunzipSync as h_}from"fflate";var Sa=class{async fetchAndExtract(e,t){let r=this.getTarballUrl(e,t),s=await dr(r,{timeoutMs:3e4});if(!s?.ok)return new Map;let i=new Uint8Array(await s.arrayBuffer());return this.extractDtsFiles(i)}getTarballUrl(e,t){return`https://registry.npmjs.org/${e.replace("/","%2F")}/-/${e.split("/").pop()}-${t}.tgz`}normalizeTarPath(e){let t=e.replace(/^package\//,""),r=t.indexOf("/");return r>0?t.substring(r+1):t}extractDtsFiles(e){let t=new Map;try{let r=h_(e),s=new TextDecoder("utf-8"),i=0;for(;i<r.length-512;){let o=r.slice(i,i+512);if(o[0]===0)break;let a=o.slice(0,100),c=a.indexOf(0),l=s.decode(a.slice(0,c>0?c:100)).trim(),f=o.slice(124,136),u=s.decode(f).trim().replace(/\0/g,""),d=parseInt(u,8)||0,p=String.fromCharCode(o[156]);if(i+=512,(p==="0"||p==="\0")&&(l.endsWith(".d.ts")||l.endsWith(".d.mts"))){let y=r.slice(i,i+d);t.set(this.normalizeTarPath(l),s.decode(y))}i+=Math.ceil(d/512)*512}}catch{}return t}};var ka=class{constructor(e,t,r=new Sa){this.cdnClient=e,this.cache=t,this.tarballFetcher=r}typesNameCandidates(e){let t=e.startsWith("@")?e.slice(1).replace("/","__"):e;return t.includes(".")?[t,t.split(".").join("-"),t.split(".").join("")]:[t]}selectTypesVersion(e,t,r){try{if(r){let i=tn.majorOf(r),o=e.filter(a=>tn.majorOf(a)===i);if(o.length)return o.sort((a,c)=>tn.cmp(c,a))[0]}let s=t?.latest;return s&&e.includes(s)?s:e[0]}catch{return e[0]}}subpathCandidates(e){let t=e.replace(/\.(mjs|cjs|js|mts|cts|ts)$/i,""),r=Ut(e);return t!==e&&r.push(`${e}.d.ts`,`${e}/index.d.ts`),r}async fetchFromVersionedRoot(e,t){let r=new D(e),s=r.version;if(!s)return;let i;try{i=await this.tarballFetcher.fetchAndExtract(r.name,s)}catch{return}if(!i||i.size===0)return;for(let[a,c]of i.entries()){let l=this.cdnClient.file(e,a);try{await this.cache.setCachedFile(l,c)}catch{}}let o=t.subpath?this.subpathCandidates(t.subpath):["index.d.ts"];for(let a of o){let c=i.get(a);if(c)return{dts:c,url:this.cdnClient.file(e,a),resolvedPkg:t.subpath?new D(t).format():t.name}}}async resolve(e){let t=D.parse(e);if(t.name)for(let r of this.typesNameCandidates(t.name)){let s=`@types/${r}`,i;try{i=await this.cdnClient.fetchVersionsIndex(s)}catch{continue}if(!i?.versions?.length)continue;let o=this.selectTypesVersion(i.versions,i.distTags,t.version),a=await this.fetchFromVersionedRoot(`${s}@${o}`,t);if(a)return a}}};var xa=class{collectRelativeTypeRefs(e){return this.collectRefs(e).filter(t=>t.startsWith("./")||t.startsWith("../"))}collectBareModuleRefs(e){return this.collectRefs(e).filter(t=>this.isBare(t))}collectRefs(e){let t=e.split(`
|
|
2248
2248
|
`).filter(s=>{let i=s.trimStart();return!(i.startsWith("*")||i.startsWith("//")||i.startsWith("/*"))}).join(`
|
|
2249
|
-
`),r=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))r.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))r.add(s[1]);return Array.from(r)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};st();var bw="file:///node_modules",Ea=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${bw}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let r=en(t);return`${bw}/${this.epochDir()}/${e}/${r}`}};import{LRUCache as
|
|
2250
|
-
`);await this.prefetchBareDeps(y,l,d,p,s);let h=c.format(),g=e===h?[e]:[e,h],x=g.some(v=>this.ambientlyDeclares(i,v));return x?this.markFileAmbient(d,f):p.push(...g.map(v=>({module:v,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};yu();st();Un();gs();mu();Fn();import*as fr from"path";var
|
|
2251
|
-
`,"utf8"),await me.writeFile(pe.join(e,"code.tsx"),n.code,"utf8"),await me.writeFile(pe.join(e,"tb.d.ts"),Jd,"utf8"),{dir:e}}var Yd={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function
|
|
2252
|
-
`,"utf8"),{dir:e}}function
|
|
2253
|
-
`))console.log(`${e} ${r}`);return n.length>0}function
|
|
2249
|
+
`),r=new Set;for(let s of t.matchAll(/(import|export)\s+[^'"\n]*from\s*['"]([^'"\n]+)['"]/g))r.add(s[2]);for(let s of t.matchAll(/export\s*\*\s*from\s*['"]([^'"\n]+)['"]/g))r.add(s[1]);return Array.from(r)}isBare(e){return!(e.startsWith("./")||e.startsWith("../")||e.startsWith("file:")||e.startsWith("http://")||e.startsWith("https://"))}};st();var bw="file:///node_modules",Ea=class{constructor(){this.epoch=0}bumpEpoch(){this.epoch+=1}epochDir(){return`__tsepoch_${this.epoch}`}pathForMain(e){return`${bw}/${this.epochDir()}/${e}/index.d.ts`}pathFor(e,t){let r=en(t);return`${bw}/${this.epochDir()}/${e}/${r}`}};import{LRUCache as m_}from"lru-cache";function ww(n){let e=new m_({ttl:dt.negativeTtlMs,max:500}),t=new Map;return async function(s){try{if(await n.isNegative(s)||e.has(s))return;let i=await n.getCachedFile(s);if(i)return{dts:i,url:s};let o=t.get(s);if(o)return o;let a=(async()=>{let c=await dr(s,{init:{cache:"no-store"}});if(!c?.ok){c?.status===404&&(e.set(s,!0),await n.recordNegative(s));return}let l=await c.text(),f=c.url||s;return await n.clearNegative(s),await n.setCachedFile(f,l),{dts:l,url:f}})();return t.set(s,a),await a.finally(()=>t.delete(s))}catch{return}}}var Ls=class{constructor(e){this.inFlight=new Map,this.scanner=new xa,this.cache=e.cache,this.cdnClient=e.cdnClient,this.versionResolver=e.versionResolver,this.packageService=e.packageService,this.fetchDts=ww(e.cache),this.typescriptProvider=new va(this.fetchDts,e.cdnClient),this.definitelyTypedProvider=new ka(e.cdnClient,e.cache),this.virtualFs=new Ea}withInFlight(e,t){let r=this.inFlight.get(e);if(r)return r;let s=t().finally(()=>this.inFlight.delete(e));return this.inFlight.set(e,s),s}invalidate(){this.virtualFs.bumpEpoch(),this.inFlight.clear()}pushFileIfNew(e,t,r){e.some(s=>s.path===t)||e.push({path:t,content:r})}createStubDef(e){let t=this.virtualFs.pathForMain(e);return{pkg:e,mainPath:t,files:[{path:t,content:"export const _shim: any; export default _shim;"}],shims:[{module:e,path:t}]}}async fetchViaProviders(e){for(let t of[this.typescriptProvider,this.definitelyTypedProvider])try{let r=await t.resolve(e);if(r?.dts)return r}catch{}}async fetchRootDts(e,t){let{effectivePackage:r,root:s,pinned:i}=await this.versionResolver.effectivePackage(e,t),o=await this.cache.getCachedDts(r);if(o?.content){let c=o.url??this.cdnClient.file(i?`${s}@${i}`:s,"index.d.ts");return{dts:o.content,url:c,resolvedPkg:r}}let a;try{a=await this.fetchViaProviders(r)}catch{return}if(!(!a?.dts||!a.url)&&new D(r).subpath===new D(a.resolvedPkg||r).subpath){try{await this.cache.setCachedDts(r,a.dts,a.url)}catch{}return a}}extractPackageRootUrl(e){let t=e.pathname.match(/^(.+@[^/]+\/)/);return t?new URL(t[1],e.origin):new URL("./",e)}toVirtualPath(e,t,r){let s=t.pathname.startsWith(e.pathname)?t.pathname.slice(e.pathname.length):`__deps__/${encodeURIComponent(t.toString()).replace(/%/g,"_")}.d.ts`;return this.virtualFs.pathFor(r,s)}computeEntryPath(e,t){if(!e)return{mainPath:this.virtualFs.pathForMain(t),packageRootUrl:void 0};let r=new URL(e),s=this.extractPackageRootUrl(r);return{mainPath:this.toVirtualPath(s,r,t),packageRootUrl:s}}async expandRelativeRefs(e,t,r,s,i=new Set,o){if(!i.has(t)&&(i.add(t),!(i.size>dt.maxRelativeTypeRefs)))try{let a=new URL(t),c=new URL("./",a);o??(o=this.extractPackageRootUrl(a));let l=this.scanner.collectRelativeTypeRefs(e).slice(0,dt.maxRelativeTypeRefs);for(let f of l)await this.tryRelativeRef(f,c,o,r,s,i)}catch{}}async tryRelativeRef(e,t,r,s,i,o){try{let a=new URL(e,t),c=a.pathname+a.search,l=wa(c)?[c]:Ut(c);for(let f of l){let d=new URL(f,a).toString();if(o.has(d))return;let p=await this.fetchDts(d);if(p?.dts){let y=this.toVirtualPath(r,new URL(p.url),s);this.pushFileIfNew(i,y,p.dts),await this.expandRelativeRefs(p.dts,p.url,s,i,o,r);return}}}catch{}}isDifferentPackage(e,t){return e===t?!1:new D(e).name!==new D(t).name}ambientlyDeclares(e,t){if(/^(?:import|export)\b/m.test(e))return!1;for(let r of e.matchAll(/declare\s+module\s+['"]([^'"]+)['"]/g)){let s=r[1];if(s===t||s.endsWith("/*")&&t.startsWith(s.slice(0,-1)))return!0}return!1}markFileAmbient(e,t){let r=e.find(s=>s.path===t);r&&(r.ambient=!0)}async prefetchBareDeps(e,t,r,s,i){try{let o=this.scanner.collectBareModuleRefs(e).slice(0,dt.maxBareDeps).filter(l=>this.isDifferentPackage(l,t));if(!o.length)return;let a=new Set([t]),c=g_(dt.prefetchConcurrency);await Promise.all(o.map(l=>c(()=>this.prefetchBareDepsRecursive(l,r,s,dt.maxBareDepth,a,i).catch(()=>{}))))}catch{}}async prefetchBareDepsRecursive(e,t,r,s,i,o){if(s<=0||i.has(e))return;i.add(e);let a=await this.fetchRootDts(e,o);if(!a?.dts)return;let c=a.resolvedPkg||e,l=this.virtualFs.pathForMain(c);this.pushFileIfNew(t,l,a.dts),this.ambientlyDeclares(a.dts,e)?this.markFileAmbient(t,l):r.push({module:e,path:l}),a.url&&await this.expandRelativeRefs(a.dts,a.url,c,t);let f=this.scanner.collectBareModuleRefs(a.dts).slice(0,dt.maxBareDeps).filter(u=>!i.has(u));for(let u of f)await this.prefetchBareDepsRecursive(u,t,r,s-1,i,o)}async resolve(e,t,r){let s=await this.packageService.extractImports(e),i=r?[...s,...r]:s;return(await Promise.all(i.map(a=>this.resolveOne(a,t)))).filter(a=>!!a)}async resolveOne(e,t){let{effectivePackage:r}=await this.versionResolver.effectivePackage(e,t);return this.withInFlight(r,async()=>{let s=new D(e),i=await this.fetchRootDts(e,t)??(s.subpath?await this.fetchRootDts(s.name,t):void 0);return i?this.buildDefFromContent(e,i,i.resolvedPkg||e,t):this.createStubDef(e)})}async buildDefFromContent(e,t,r,s){let{dts:i,url:o,resolvedPkg:a}=t,c=new D(a||r),l=c.version?`${c.name}@${c.version}`:c.name,{mainPath:f,packageRootUrl:u}=this.computeEntryPath(o,l),d=[{path:f,content:i}],p=[];o&&await this.expandRelativeRefs(i,o,l,d,void 0,u);let y=d.map(v=>v.content).join(`
|
|
2250
|
+
`);await this.prefetchBareDeps(y,l,d,p,s);let h=c.format(),g=e===h?[e]:[e,h],x=g.some(v=>this.ambientlyDeclares(i,v));return x?this.markFileAmbient(d,f):p.push(...g.map(v=>({module:v,path:f}))),{pkg:e,mainPath:f,files:d,shims:p,ambient:x}}};yu();st();Un();gs();mu();Fn();import*as fr from"path";var y_=fr.join(ho,"pkg"),b_=fr.join(ho,"files"),w_=fr.join(ho,"negative.json"),Ta=class{pkgMem=new Map;fileMem=new Map;negativeCache=new nn(new qn(w_));async getCachedDts(e){if(this.pkgMem.has(e))return this.pkgMem.get(e);await te();let t=await it(vw(e));return this.pkgMem.set(e,t),t}async setCachedDts(e,t,r){let s={content:t,url:r};this.pkgMem.set(e,s),await Aa(async()=>{await te(),await Te(vw(e),JSON.stringify(s))})}async getCachedFile(e){if(this.fileMem.has(e))return this.fileMem.get(e);await te();let t=await po(Sw(e));return this.fileMem.set(e,t),t}async setCachedFile(e,t){this.fileMem.set(e,t),await Aa(async()=>{await te(),await Te(Sw(e),t)})}isNegative(e){return this.negativeCache.isNegative(e)}async recordNegative(e){await Aa(async()=>{await te(),await this.negativeCache.recordNegative(e)})}clearNegative(e){return Aa(()=>this.negativeCache.clearNegative(e))}};async function Aa(n){try{await n()}catch{}}function vw(n){return fr.join(y_,De(n)+".json")}function Sw(n){return fr.join(b_,De(n)+".txt")}Un();var Hd;function v_(){return Hd||(Hd=new Ls({cache:new Ta,cdnClient:qg,packageService:bo,versionResolver:Ug})),Hd}var kw="file:///node_modules/";async function xw(n){let e=mo(n.emitKey,"typecheck");await te(),await me.rm(e,{recursive:!0,force:!0}),await me.mkdir(e,{recursive:!0});let t=E_(n.jsxImportSource,n.dependencies),r=await v_().resolve(n.code,n.dependencies,t),s=n.local?.name,i=s?r.filter(f=>f.pkg!==s):r,o=new Set;for(let f of i)for(let u of f.files){let d=Oa(u.path);if(!d||o.has(d))continue;o.add(d);let p=pe.join(e,"node_modules",d);await me.mkdir(pe.dirname(p),{recursive:!0}),await me.writeFile(p,u.content,"utf8")}let a={};for(let f of i)for(let u of f.shims){let d=Oa(u.path);d&&(a[u.module]=[`./node_modules/${d}`])}for(let f of i){if(f.ambient)continue;let u=Oa(f.mainPath);u&&(a[f.pkg]=[`./node_modules/${u}`])}let c=new Set;for(let f of i)for(let u of f.files){if(!u.ambient)continue;let d=Oa(u.path);d&&c.add(`node_modules/${d}`)}if(n.local){delete a[n.local.name];let f=await A_(n.local,e);f?a[n.local.name]=[`./node_modules/${n.local.name}/${f}`]:console.warn(` local: '${n.local.name}' ships no type defs; check cannot type against it.`)}let l=S_(n.jsxImportSource,a,[...c]);return await me.writeFile(pe.join(e,"tsconfig.json"),JSON.stringify(l,null,2)+`
|
|
2251
|
+
`,"utf8"),await me.writeFile(pe.join(e,"code.tsx"),n.code,"utf8"),await me.writeFile(pe.join(e,"tb.d.ts"),Jd,"utf8"),{dir:e}}var Yd={target:"es2023",module:"esnext",moduleResolution:"bundler",strict:!0,noEmit:!0,skipLibCheck:!0,esModuleInterop:!0,allowSyntheticDefaultImports:!0,forceConsistentCasingInFileNames:!0};function S_(n,e,t=[]){return{compilerOptions:{...Yd,lib:k_([...Fd,...Ud]),jsx:"react-jsx",jsxImportSource:n??"react",paths:e},include:["code.tsx","tb.d.ts",...t]}}function k_(n){return qd(n).map(e=>x_(e.name))}function x_(n){return n.split(".").map(e=>/^es\d+$/i.test(e)?e.toUpperCase():e==="dom"?"DOM":e==="esnext"?"ESNext":e.charAt(0).toUpperCase()+e.slice(1)).join(".")}function E_(n,e){let t=n??("react"in e?"react":void 0);return t?[`${t}/jsx-runtime`,`${t}/jsx-dev-runtime`]:[]}function Oa(n){if(!n.startsWith(kw))return;let e=n.slice(kw.length),t=e.indexOf("/");if(!(t<0))return e.slice(t+1)}async function A_(n,e){if(!n.typesAbs)return;let t=pe.dirname(n.typesAbs),r=pe.join(e,"node_modules",n.name);for(let s of await T_(t)){let i=pe.join(r,pe.relative(t,s));await me.mkdir(pe.dirname(i),{recursive:!0}),await me.copyFile(s,i)}return pe.basename(n.typesAbs)}async function T_(n){let e=[];async function t(r){let s=await me.readdir(r,{withFileTypes:!0});for(let i of s){let o=pe.join(r,i.name);i.isDirectory()?await t(o):/\.d\.ts(\.map)?$/.test(i.name)&&e.push(o)}}return await t(n),e}import*as Ce from"fs/promises";import*as ft from"path";import{existsSync as O_}from"fs";Un();wu();var P_="^22";async function Ew(n){let e=mo(n.emitKey,"typecheck-server");await te(),await Ce.rm(e,{recursive:!0,force:!0}),await Ce.mkdir(e,{recursive:!0});let t=ft.join(n.bulbDir,".typebulb"),r=Ao(n.server).filter(o=>o!==n.local?.name);await Eo([`@types/node@${P_}`,...r],t,n.dependencies,{ignoreScripts:!0});let s=ft.join(t,"node_modules"),i=ft.join(e,"node_modules");return await __(s,i),await Ce.writeFile(ft.join(e,"server.ts"),n.server,"utf8"),await Ce.writeFile(ft.join(e,"tb.d.ts"),Kd,"utf8"),await Ce.writeFile(ft.join(e,"tsconfig.json"),JSON.stringify(C_(n.local),null,2)+`
|
|
2252
|
+
`,"utf8"),{dir:e}}function C_(n){let e={...Yd,lib:["ES2023"],types:["node"]};if(n?.typesAbs){let t=i=>i.replace(/\\/g,"/"),r=t(ft.dirname(n.typesAbs)),s=t(n.typesAbs).replace(/\.d\.ts$/,"");e.paths={[n.name]:[s],[`${n.name}/*`]:[`${r}/*`]}}return{compilerOptions:e,include:["server.ts","tb.d.ts"]}}async function __(n,e){if(!O_(n)){await Ce.mkdir(e,{recursive:!0});return}await Ce.rm(e,{recursive:!0,force:!0});let t=process.platform==="win32"?"junction":"dir";await Ce.symlink(n,e,t)}co();ee();async function Tw(n,e){let{bulb:t,config:r,warnings:s,starts:i}=await qe(n),o=_e.basename(n),a=h=>i.get(h)??1;!t.code&&!t.server&&(console.error("Bulb has neither **code.tsx** nor **server.ts**; nothing to check."),process.exit(1));let c=!1,l=!1;for(let h of s)console.log(`structure ${h}`);s.length&&(c=!0);let f=Qn(_e.resolve(n)),u=f?In(t.name):"";f&&u&&u!==f.slug&&(console.log(`naming filename '${f.slug}.bulb.md' doesn't match the title '${t.name}' \u2014 its slug derives to '${u}'. Rename the file to '${u}.bulb.md', or change name: to suit the filename.`),l=!0),t.code&&(c=Aw(os(t.code,{target:"client",dependencies:r.dependencies??{},lineOffset:a("code.tsx")}),"client")||c),t.server&&(c=Aw(os(t.server,{target:"server",lineOffset:a("server.ts")}),"server")||c);let d=D_([process.cwd(),_e.dirname(n)]);if(!d){let h=_e.relative(process.cwd(),n)||n;console.error("check: TypeScript not found \u2014 install it once, then re-run:"),console.error(" npm i -g typescript"),console.error(` typebulb check ${h}`),process.exit(2)}let p=[];if(t.code){let{dir:h}=await xw({code:t.code,dependencies:r.dependencies??{},jsxImportSource:r.ts?.jsxImportSource,emitKey:n,local:e});p.push({role:"client",dir:h})}if(t.server){let{dir:h}=await Ew({server:t.server,bulbDir:_e.dirname(n),emitKey:n,local:e?{name:e.name,typesAbs:e.typesAbs}:void 0,dependencies:r.dependencies});p.push({role:"server",dir:h})}for(let{role:h,dir:g}of p){let{stdout:x,exitCode:v}=await M_(d,g);for(let P of x.split(/\r?\n/))P.trim()&&console.log(`${h} ${L_(P,o,a)}`);v!==0&&(c=!0)}c&&process.exit(1);let y=[t.code&&"code.tsx",t.server&&"server.ts"].filter(Boolean).join(", ");console.error(l?`\u2713 type-checks (${y}) \u2014 see the naming warning above`:`\u2713 no issues (${y})`)}function Aw(n,e){for(let t of n)for(let r of t.message.split(`
|
|
2253
|
+
`))console.log(`${e} ${r}`);return n.length>0}function L_(n,e,t){return n.replace(/\b(code\.tsx|server\.ts)\((\d+),(\d+)\)/g,(r,s,i,o)=>`${e}(${Number(i)+t(s)-1},${o})`)}function M_(n,e){return new Promise(t=>{let r=R_(process.execPath,[n,"--noEmit"],{cwd:e}),s="";r.stdout?.on("data",i=>{s+=i.toString()}),r.stderr?.on("data",i=>{s+=i.toString()}),r.on("close",i=>t({stdout:s,exitCode:i??1}))})}var B_=N_(import.meta.url);function D_(n){let e=r=>{try{let s=B_.resolve("typescript/package.json",{paths:r}),i=_e.join(_e.dirname(s),"lib","tsc.js");return $_(i)?i:void 0}catch{return}},t=e(n);if(t)return t;try{let r=I_("npm root -g",{encoding:"utf8"}).trim();return e([r])}catch{return}}Ge();Wo();xs();async function Ow(n,e){let{bulb:t}=await qe(n),r=er(t);if(dn(n)){console.log("remembered-trusted \u2014 runs with filesystem / AI / server.ts automatically (`typebulb untrust` to revoke)."),r&&console.log(` (it uses ${r})`);return}r?(console.log(`This bulb appears to use ${r}; it runs Restricted unless you grant trust:`),console.log(` ${e}`)):console.log("No privileged capability detected \u2014 runs Restricted by default. (A clean scan is a hint, not a guarantee.)")}xs();import*as Ms from"path";async function Pw(n,e){if(!n){e||(console.error("Usage: typebulb untrust <file.bulb.md>"),process.exit(1));let r=Yu();if(!r.length){console.log("No bulbs are remembered as trusted.");return}console.log("Trusted bulbs (run with fs/AI/server.ts without --trust):");for(let s of r)console.log(` ${s}`);return}let t=Ms.resolve(n);t.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1));try{tr(t,e)}catch(r){console.error(r.message),process.exit(1)}console.log(e?`Trusted ${Ms.basename(t)} \u2014 runs with fs / AI / server.ts (no --trust needed).`:`Untrusted ${Ms.basename(t)} \u2014 runs Restricted.`),console.log(` ${t}`)}Ae();import*as Rw from"readline";Vu();function Vd(n){let e=t=>r=>n?`\x1B[${t}m${r}\x1B[0m`:r;return{lit:e("38;5;70"),litLink:e("4;38;5;70"),brand:e("38;5;135")}}var j_=5e3,Pa=()=>Math.round(performance.now()),Cw=n=>n>=1e3?`${(n/1e3).toFixed(1)}s`:`${n}ms`;async function Iw(n){let e=iw(process.cwd()),t=Pa();if("ambiguous"in e){let r=await F_(n,e.ambiguous);return r?_w(n,r,{boot:t,from:Pa()}):U_(n,e.ambiguous)}return _w(n,e.name,{boot:t,from:Pa()})}async function _w(n,e,t){let r,s;try{r=await gg(e)}catch(p){s=p instanceof Error?p.message:String(p)}let i=Pa()-t.from,{lit:o,litLink:a,brand:c}=Vd(process.stdout.isTTY===!0),l=[" Read the authoring skill before writing a bulb:",` \u2022 ${o(Es())}`],f=r?[` Agent mirror (${e}) is live\u{1F4A1}`,` ${o("\u25CF")} ${a(r.url)}`," Inline bulbs render live here."," Agents:",` Reusable app/tool \u2192 write a ${o(".bulb.md")}`," Show something inline \u2192 emit an inline bulb"," emit it with no .bulb.md draft first",...e==="codex"?[" verify it this turn \u2014 foreground-wait, bounded:",` \u2022 ${o('typebulb wait agent --match "[inline <name>" --timeout 120')}`," raise the shell tool's timeout_ms to 130000"," (its 10s default kills even a clean ok)"]:[e==="pi"?" arm a wait for its render verdict \u2014 run it plainly:":" background a wait for its render verdict:",` \u2022 ${o('typebulb wait agent --match "[inline <name>"')}`],...l," End this reply with the mirror link above"," \u2022 easy to miss the link mid-message"]:[` The mirror did not start (${s})`,` \u25CF Start it manually: ${o(`npx typebulb agent:${e}`)}`," Agents:",...l],u=t.boot+i>j_?[` slow launch: boot ${Cw(t.boot)} \xB7 mirror ${Cw(i)}`]:[],d=[` ${c(`typebulb v${n}`)}`,...u,...f,""];process.stdout.write(d.join(`
|
|
2254
2254
|
`)+`
|
|
2255
|
-
`)}async function
|
|
2255
|
+
`)}async function F_(n,e){if(!process.stdin.isTTY||!process.stdout.isTTY)return;let{lit:t,brand:r}=Vd(!0),s=[` ${r(`typebulb v${n}`)}`," More than one agent harness is available here.",...e.map((o,a)=>` ${t(String(a+1))}) ${o}`),""];process.stdout.write(s.join(`
|
|
2256
2256
|
`)+`
|
|
2257
|
-
`);let i=Rw.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function
|
|
2257
|
+
`);let i=Rw.createInterface({input:process.stdin,output:process.stdout});try{let o=(await new Promise(c=>i.question(" Open which? [1]: ",c))).trim();if(o==="")return e[0];let a=Number(o);return Number.isInteger(a)&&a>=1&&a<=e.length?e[a-1]:e.find(c=>c===o.toLowerCase())}finally{i.close()}}function U_(n,e){let{lit:t,brand:r}=Vd(process.stdout.isTTY===!0),s=[` ${r(`typebulb v${n}`)}`," More than one agent harness is available here."," Open the mirror for the one you want:",...e.map(i=>` \u2022 ${t(`npx typebulb agent:${i}`)}`),""];process.stdout.write(s.join(`
|
|
2258
2258
|
`)+`
|
|
2259
|
-
`)}at();cn();async function Nw(n){Oe(n);let e=await ct();if(e.length>0){console.log(dy(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Lu()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,r]of Object.entries(Vn))console.log(` ${r.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}ee();function $w(n){n?.trim()||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1));let e=In(n);e||(console.error(`'${n}' has no slug \u2014 a bulb name needs at least one letter or digit.`),process.exit(1)),console.log(e)}Pt();import*as Mw from"path";import{valid as Lw,lt as
|
|
2260
|
-
`+e)}function Gd(n,e,t,r,s){let i=
|
|
2259
|
+
`)}at();cn();async function Nw(n){Oe(n);let e=await ct();if(e.length>0){console.log(dy(e,process.env.TB_AI_PROVIDER,process.env.TB_AI_MODEL));return}if(!Lu()){console.log("No AI provider keys found in this directory's .env, and no local Ollama server detected."),console.log("Set one of these to use a cloud model with tb.ai:");for(let[t,r]of Object.entries(Vn))console.log(` ${r.padEnd(20)} (${t})`);console.log("\u2026or start Ollama (http://localhost:11434, or set OLLAMA_HOST) for local models. Then re-run `typebulb models`.");return}console.log("Couldn't fetch the model catalog (offline?). tb.ai still works with any valid provider/model id for your keys.")}ee();function $w(n){n?.trim()||(console.error("Usage: typebulb slug <bulb name>"),process.exit(1));let e=In(n);e||(console.error(`'${n}' has no slug \u2014 a bulb name needs at least one letter or digit.`),process.exit(1)),console.log(e)}Pt();import*as Mw from"path";import{valid as Lw,lt as q_}from"semver";Ae();to();function J_(n,e,t,r){if(/^\d+$/.test(e))return n.find(i=>i.pid===parseInt(e,10));let s=e==="agent"?n.filter(i=>i.agent!=null):n.filter(i=>i.agent===e);if(s.length){if(!t)return s[0];let i=s.filter(o=>rs(o,t));return r&&i.find(o=>o.agent===r)||i[0]}return n.find(i=>ae(i.file)===ae(e))}var Bs=n=>n.agent??Mw.basename(n.file);function K_(n){return n===Be?"":n?(Lw(n)&&Lw(Be)?q_(n,Be):!0)?` STALE runtime v${n} (this CLI is v${Be} \u2014 relaunch to update)`:` runtime v${n} (newer than this CLI's v${Be})`:" STALE runtime (predates the version stamp \u2014 relaunch to update)"}function Bw(n,e){for(let t of n)e(` ${t.url} pid ${t.pid} ${t.trust?"trusted":"restricted"}${t.batch?` --batch ${t.batch}`:""}${K_(t.version)} ${t.file}`)}function zd(n,e){if(!n.length){console.log("No running bulb servers.");return}console.log("Running bulb servers:"),Bw(n,t=>console.log(t)),console.log(`
|
|
2260
|
+
`+e)}function Gd(n,e,t,r,s){let i=J_(n,e,r,s);if(i)return i;console.error(`No running server for '${e}'.`),n.length?(console.error(`Running servers (try \`typebulb ${t} <file|pid>\`):`),Bw(n,o=>console.error(o))):console.error("No bulb servers are running."),process.exit(1)}async function Dw(n,e){if(!n){e.clear&&(console.error("Specify which server to clear: typebulb logs --clear <file|pid>"),process.exit(1)),zd(await Q(process.cwd()),"Run `typebulb logs <file|pid>` to print one server's console.");return}let t=Gd(await Q(),n,"logs",process.cwd(),bn());if(e.clear){lg(t.pid),console.log(`Cleared log for ${Bs(t)} (pid ${t.pid}).`);return}let r=Ye(t.pid),s=r.text;if(e.run!==void 0?(s=ug(s,e.run),s||console.error(e.run==="latest"?"No output in the latest run yet (the server has logged nothing since its last reload).":`No output for run ${e.run} (it hasn't started, or was trimmed from the log).`)):!s&&!e.follow&&console.error("Log is empty \u2014 this server has logged nothing yet."),e.lines&&e.lines>0){let i=s.split(`
|
|
2261
2261
|
`);i.length&&i[i.length-1]===""&&i.pop(),s=i.slice(-e.lines).join(`
|
|
2262
2262
|
`)}if(process.stdout.write(s),s&&!s.endsWith(`
|
|
2263
2263
|
`)&&process.stdout.write(`
|
|
2264
|
-
`),e.follow&&e.run===void 0){let i=r.offset,o=setInterval(()=>{let c=Ye(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var
|
|
2265
|
-
`);g=P.pop()??"";for(let _ of P)_.trim()&&(e.match&&!_.includes(e.match)||(console.log(_),!i&&(h??=Date.now()+p,r&&(_.includes("] compile error")||_.includes("] runtime error"))&&(h=Math.min(h,Date.now()+y)))))}if(h&&Date.now()>=h)break;if(!o&&!h&&Date.now()>=d){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${Bs(t)} within ${a}s`),x=2;break}if(!Zl(t.pid)){h||(console.error(`server ${Bs(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await
|
|
2264
|
+
`),e.follow&&e.run===void 0){let i=r.offset,o=setInterval(()=>{let c=Ye(t.pid,i);i=c.offset,c.text&&process.stdout.write(c.text)},500),a=()=>{clearInterval(o),process.exit(0)};process.on("SIGINT",a),process.on("SIGTERM",a),await new Promise(()=>{})}}var W_=n=>new Promise(e=>setTimeout(e,n));async function jw(n,e){if(!n){zd(await Q(process.cwd()),"Run `typebulb wait <file|pid>` to block until one logs a new line.");return}let t=Gd(await Q(),n,"wait",process.cwd(),bn()),r=t.agent!=null,s=process.env.TYPEBULB_WAIT_SHIM==="1",i=process.env.TYPEBULB_WAIT_FOLLOW==="1",o=s||i,a=e.timeoutSec??1800,c=e.match??"",l=Ye(t.pid).offset,f=i?void 0:Xl(t.pid,c)??(c?Xl(t.pid):void 0),u=i?l:f!==void 0&&f<=l?f:c?0:l,d=Date.now()+a*1e3,p=r?1e4:1e3,y=2e3,h,g="",x=0;for(;;){let v=Ye(t.pid,u);if(u=v.offset,v.text){g+=v.text;let P=g.split(`
|
|
2265
|
+
`);g=P.pop()??"";for(let _ of P)_.trim()&&(e.match&&!_.includes(e.match)||(console.log(_),!i&&(h??=Date.now()+p,r&&(_.includes("] compile error")||_.includes("] runtime error"))&&(h=Math.min(h,Date.now()+y)))))}if(h&&Date.now()>=h)break;if(!o&&!h&&Date.now()>=d){console.error(`timeout: no ${e.match?`line matching '${e.match}'`:"new output"} from ${Bs(t)} within ${a}s`),x=2;break}if(!Zl(t.pid)){h||(console.error(`server ${Bs(t)} (pid ${t.pid}) exited while waiting`),process.exit(3));break}await W_(400)}i||ro(t.pid,u,c),process.exit(x)}async function Fw(n){if(!n){zd(await Q(process.cwd()),"Run `typebulb stop <file|pid>` to stop one.");return}let e=Gd(await Q(),n,"stop",process.cwd(),bn());await Xt(e.pid),console.log(`Stopped ${Bs(e)} (pid ${e.pid}, ${e.url}).`)}async function Uw(n){let e=process.cwd(),t=n==="agent"?bn():void 0,r=n==="global"?await Q():n==="bulbs"?await Q(e):(await Q()).filter(i=>rs(i,e)&&(!t||i.agent===t)),s=n==="global"?"server":n==="agent"?"mirror":"bulb";if(!r.length){console.log(n==="global"?"No running bulb servers.":`No running ${s}s for this project.`);return}await Promise.all(r.map(i=>Xt(i.pid))),console.log(`Stopped ${r.length} ${s}${r.length===1?"":"s"}:`);for(let i of r)console.log(` ${i.url} pid ${i.pid} ${Bs(i)}`)}Ae();Pt();Zn();import*as $a from"path";import*as Vw from"http";import{mkdir as uR,writeFile as dR}from"fs/promises";an();ee();import{Hono as X_}from"hono";import{serve as Q_}from"@hono/node-server";import{streamSSE as Z_}from"hono/streaming";import*as ef from"fs/promises";import eR from"open";Un();gs();Fn();import*as Xd from"fs/promises";import*as Ds from"path";var Ca=class{async get(e){let t=De(e),r=Ds.join(ms,t+".bin"),s=Ds.join(ms,t+".json");try{let[i,o]=await Promise.all([Xd.readFile(r),Xd.readFile(s,"utf8")]),a=JSON.parse(o);return{body:i,contentType:a.contentType,cacheControl:a.cacheControl}}catch{return}}async set(e,t){await te();let r=De(e),s=Ds.join(ms,r+".bin"),i=Ds.join(ms,r+".json"),o={url:e,contentType:t.contentType,cacheControl:t.cacheControl};await Promise.all([Te(s,t.body),Te(i,JSON.stringify(o))])}};var qw=`
|
|
2266
2266
|
const CSS = '\\n' +
|
|
2267
2267
|
/* The agent mirror's token set, verbatim (agents/core/client/styles.css) \u2014 one system across CLI
|
|
2268
2268
|
chrome: app chrome sits on --panel, content wells paint --veil, grays ride one neutral tint.
|
|
@@ -2583,23 +2583,23 @@ export function runInference(ctx) {
|
|
|
2583
2583
|
showConfirm();
|
|
2584
2584
|
document.body.appendChild(host);
|
|
2585
2585
|
}
|
|
2586
|
-
`;Jn();Ae();cn();Lo();an();import{stream as
|
|
2587
|
-
${d}`:"";return w.text(`Forbidden: this capability requires --trust.${N}`,403)}await E()},C=async(w,E)=>{let R=w.req.header("sec-fetch-site");if(R){if(R!=="same-origin")return w.text(`Forbidden: ${R} request`,403)}else{let L=w.req.header("origin");if(L&&!
|
|
2588
|
-
`+ne.slice(-4e3)),new ke("LLM output is not valid JSON","parse_error",!0);re.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",re.fixesApplied.join(", "));let Ze={insight:re.parsed,insightJson:re.json,data:N};yield{kind:"complete",...Ze,fixesApplied:re.fixesApplied,hash:Iu(Ze)}})();return _a(w,fe)}catch(E){return w.json(js(E),500)}});let Z=async w=>{let{hash:E}=await w.req.json().catch(()=>({}));return typeof E=="string"?Nu(E):void 0};v.post("/__infer-save",async w=>{try{if(!l)return w.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let E=await Z(w);return E?(await l(E.data,E.insightJson),w.json({ok:!0})):w.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(E){return w.json(js(E),500)}}),v.get("/__infer-info",w=>{let E=c?.(),R=gr(E?.config??"").inference,L=Hi(E?.data??""),N=lt();return typeof N=="string"?w.json({error:N,inference:R,data:L}):w.json({provider:N.protocol,model:N.model,inference:R,data:L})}),v.use("/__infer-decode",C),v.post("/__infer-decode",async w=>w.json(await Z(w)??{error:"invalid fragment"})),v.get("/__infer-ui.js",w=>w.body(qw,200,{"Content-Type":"text/javascript; charset=utf-8"})),v.get("/__models",async w=>{try{let E=await ct();return w.json(E)}catch{return w.json([],200)}}),v.get("/__ai-access",async w=>{try{return w.json(await $o())}catch{return w.json("none",200)}}),h&&v.get("/__source/*",async w=>{let E=await ef.readFile(h,"utf-8").catch(()=>{});return E===void 0?w.text("Not Found",404):new Response(E,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let J=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],G=new Ca;v.get("/proxy/*",async w=>{let E=new URL(w.req.url),L=(E.pathname+E.search).slice(7),N=L.lastIndexOf("https://");return N===-1?w.text("Invalid proxy URL",400):hr(w,L.slice(N))}),f&&Kw(v,`/local/${f.name}/`,f.serveDir),p&&Kw(v,p.mount,p.dir),y&&v.get("/assets/*",async w=>{let{pathname:E}=new URL(w.req.url),R=E.slice(8),L;try{L=decodeURIComponent(R)}catch{return w.text("Not Found",404)}let N=Rf(L);if(N)return w.text(`${N} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{for(let X of y.dirs){let fe=await Yw(L,X,{"Cache-Control":"no-cache"});if(fe)return fe}}catch{return w.text("Not Found",404)}let K=y.remoteBase;return K?w.redirect(K+R,302):w.text("Not Found",404)});async function hr(w,E){let R;try{R=new URL(E)}catch{return w.text("Invalid URL",400)}if(R.protocol!=="https:")return w.text("HTTPS only",400);if(!J.includes(R.hostname))return w.text("Host not allowed",403);let L=await G.get(E);if(L)return new Response(L.body,{status:200,headers:Zd(L.contentType,L.cacheControl)});try{let N=await fetch(E,{headers:{Accept:w.req.header("Accept")||"*/*"},redirect:"follow"});if(!N.ok)return w.text(`Upstream ${N.status}`,N.status);let K=N.headers.get("Content-Type")||void 0,X=N.headers.get("Cache-Control")||void 0;if(N.body){let[fe,ne]=N.body.tee();return(async()=>{try{let re=await new Response(ne).arrayBuffer();await G.set(E,{body:Buffer.from(re),contentType:K,cacheControl:X})}catch{}})(),new Response(fe,{status:N.status,headers:Zd(K,X)})}return new Response(null,{status:N.status,headers:Zd(K,X)})}catch(N){return w.text(`Proxy fetch failed: ${N instanceof Error?N.message:N}`,502)}}(i||o)&&(v.get("/__reload",w=>
|
|
2589
|
-
`).trimEnd()}function
|
|
2586
|
+
`;Jn();Ae();cn();Lo();an();import{stream as H_}from"hono/streaming";var Y_="X-TB-Stream";function js(n){return n instanceof ke?{message:n.message,code:n.code,retryable:n.retryable}:{message:n instanceof Error?n.message:"Unknown error",code:"unknown",retryable:!1}}function _a(n,e){return n.header("Content-Type","application/x-ndjson; charset=utf-8"),n.header("Cache-Control","no-cache"),n.header(Y_,"1"),H_(n,async t=>{let r=e[Symbol.asyncIterator]();t.onAbort(()=>{r.return?.()});try{for(;;){let{done:s,value:i}=await r.next();if(s)break;await t.writeln(JSON.stringify({type:"chunk",value:i}))}}catch(s){await t.writeln(JSON.stringify({type:"error",error:js(s)}))}finally{try{await r.return?.()}catch{}}})}var Ra={log:(...n)=>console.log(...n)};function Ia(n,e){let t=n?.[e]??(Object.hasOwn(Ra,e)?Ra[e]:void 0);return typeof t=="function"?t:void 0}function Na(n){return n.constructor?.name==="AsyncGeneratorFunction"}Mu();var V_=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,z_=/[?&]target=/,G_=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function Jw(n,e=""){return V_.test(n)?!0:G_.test(n)&&z_.test(e)}var tR="127.0.0.1",nR=new Set(["localhost","127.0.0.1","::1"]),rR=0;function sR(n){if(n)try{return new URL(n.includes("://")?n:`http://${n}`).hostname}catch{return}}function Ww(n){let e=sR(n);return!!e&&nR.has(e)}function iR(n){try{let e=new URL(n);return(e.protocol==="http:"||e.protocol==="https:")&&Ww(e.host)}catch{return!1}}function oR(n){return!!n&&/\bCode\/\d/.test(n)&&/\bElectron\//.test(n)}function aR(n,e){if(!e)return!1;try{return new URL(n).host===e}catch{return!1}}function Qd(n){return n instanceof Error?n.message:"Unknown error"}var cR=3e3,tf=1e4,lR=2e3;async function Hw(n){let{getHtml:e,basePath:t,fsBase:r,port:s,reloadEmitter:i,messageEmitter:o,getServerExports:a,getBulbBlocks:c,saveInferenceResult:l,localOverride:f,trusted:u=!1,trustHint:d,staticAssets:p,bulbAssets:y,sourceFile:h}=n,g=`${process.pid}-${++rR}-${Date.now()}`,x=r??t,v=new X_;v.use("*",async(w,E)=>{if(!Ww(w.req.header("host")))return w.text("Forbidden: untrusted Host",403);await E()}),v.use("*",async(w,E)=>{await E(),w.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),w.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let P=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],_=async(w,E)=>{if(!u){let R=new URL(w.req.url).pathname,L=P.find(([K])=>K.endsWith("/*")?R.startsWith(K.slice(0,-2)):R===K)?.[1]??"server-side code (server.ts)";fg(process.pid,L);let N=d?`
|
|
2587
|
+
${d}`:"";return w.text(`Forbidden: this capability requires --trust.${N}`,403)}await E()},C=async(w,E)=>{let R=w.req.header("sec-fetch-site");if(R){if(R!=="same-origin")return w.text(`Forbidden: ${R} request`,403)}else{let L=w.req.header("origin");if(L&&!aR(L,w.req.header("host")))return w.text("Forbidden: cross-origin request",403)}await E()};for(let[w]of P)v.use(w,_),v.use(w,C);v.use("/__log",C),v.post("/__log",async w=>{try{let{args:E}=await w.req.json();console.log(...E||[])}catch{}return w.json({ok:!0})});let I=0,M=new Set,A=Date.now(),j={at:0,opened:!1},U=async w=>{if(M.size>0)return{how:"attached"};let E=Date.now(),R=Math.max(w.fresh?0:A,I);if(E-R<cR)return{how:"pending"};if(j.opened&&E-j.at<tf)return{how:"pending"};if(!j.opened&&E-j.at<lR)return{how:"none"};j={at:E,opened:!0};let L=`http://localhost:${s}`,N=await hg(L,t);return N?.where==="editor"?{how:"editor",via:N.via}:w.external==="force"||w.external==="follow"&&N?.where==="external"?(await eR(L),{how:"external"}):(j.opened=!1,{how:"none"})};if(o){let w=0,E=new Map;v.use("/__send",C),v.post("/__send",async R=>{let L="";try{L=await R.req.text()}catch{}let N=Number(R.req.query("reply"))||0,K=o.listenerCount("message"),X=K===0&&I?Date.now()-I:void 0,fe=K===0&&R.req.query("open")!==void 0?await U({external:"follow",fresh:!1}):void 0,ne={clients:K,droppedMsAgo:X,...fe?{opening:fe.how,via:fe.how==="editor"?fe.via:void 0}:{}};if(R.req.query("solo")!==void 0&&K!==1)return R.json({...ne,refused:K>1});if(K===0)return R.json(ne);if(N<=0)return o.emit("message",{payload:L}),R.json(ne);let re=++w,Ze=await new Promise(Ke=>{let ht={expected:K,received:0,results:[],errors:[],finish:Da=>{clearTimeout(Ba),E.delete(re),Ke({results:ht.results,errors:ht.errors,timedOut:Da})}},Ba=setTimeout(()=>ht.finish(!0),N);E.set(re,ht),o.emit("message",{id:re,payload:L})});return R.json({clients:K,...Ze})}),v.use("/__send-reply",C),v.post("/__send-reply",async R=>{try{let{id:L,results:N,errors:K}=await R.req.json(),X=E.get(L);X&&(X.results.push(...N??[]),X.errors.push(...K??[]),++X.received>=X.expected&&X.finish(!1))}catch{}return R.json({ok:!0})})}v.get("/",w=>w.html(e())),v.post("/__fs/read",async w=>{try{let{path:E}=await w.req.json(),R=await vs(E,x,t);return new Response(new Uint8Array(R),{headers:{"Content-Type":"application/octet-stream"}})}catch(E){let R=Qd(E);return w.json({error:R},400)}}),v.post("/__fs/write",async w=>{try{let E=w.req.query("path");return E?(await Bo(E,new Uint8Array(await w.req.arrayBuffer()),x,t),w.json({success:!0})):w.json({error:"Missing path"},400)}catch(E){let R=Qd(E);return w.json({error:R},400)}}),v.post("/__api/:name",async w=>{try{let E=w.req.param("name"),R=Ia(a?.(),E);if(!R)return w.json({error:`API function '${E}' not found`},404);let{args:L}=await w.req.json();if(Na(R))return _a(w,R(...L||[]));let N=await R(...L||[]);return w.json({result:N})}catch(E){let R=Qd(E);return w.json({error:R},500)}}),v.post("/__ai",async w=>{try{let{messages:E,system:R,effort:L,provider:N,model:K,webSearch:X,stream:fe}=await w.req.json();if(!E||!Array.isArray(E)||E.length===0)return w.json({message:"messages array is required",code:"unknown",retryable:!1},400);let ne=lt(N,K);if(typeof ne=="string")return w.json({message:ne,code:"unknown",retryable:!1},400);let re=await Lt(ne,{messages:E,system:R,effort:L,webSearch:X,signal:w.req.raw.signal});if(!re.ok){let ht=await Hn(re,ne.protocol);return w.json(ht,re.status)}if(fe)return _a(w,on(re,ne.protocol));let{text:Ze,usage:Ke}=await Yn(re,ne.protocol);return Ze||console.warn("[tb.ai] Empty response from provider"),w.json({text:Ze,usage:Ke})}catch(E){return w.json(js(E),500)}}),v.post("/__infer",async w=>{try{let{data:E}=await w.req.json().catch(()=>({})),R=c?.();if(!R?.infer.trim())return w.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let L=lt();if(typeof L=="string")return w.json({message:L,code:"unknown",retryable:!1},400);let N=Array.isArray(E)?E.map(String):[],K=_u(R,N),X=await Lt(L,{messages:[{role:"user",content:K}],signal:w.req.raw.signal});if(!X.ok){let ne=await Hn(X,L.protocol);return w.json(ne,X.status)}let fe=(async function*(){let ne="";for await(let Ke of on(X,L.protocol))Ke.kind!=="text"||!Ke.text||(ne+=Ke.text,yield{kind:"delta",text:Ke.text});let re=Ru(ne);if(re.parsed===void 0)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
2588
|
+
`+ne.slice(-4e3)),new ke("LLM output is not valid JSON","parse_error",!0);re.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",re.fixesApplied.join(", "));let Ze={insight:re.parsed,insightJson:re.json,data:N};yield{kind:"complete",...Ze,fixesApplied:re.fixesApplied,hash:Iu(Ze)}})();return _a(w,fe)}catch(E){return w.json(js(E),500)}});let Z=async w=>{let{hash:E}=await w.req.json().catch(()=>({}));return typeof E=="string"?Nu(E):void 0};v.post("/__infer-save",async w=>{try{if(!l)return w.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let E=await Z(w);return E?(await l(E.data,E.insightJson),w.json({ok:!0})):w.json({message:"No decodable #tb= fragment to save.",code:"unknown",retryable:!1},400)}catch(E){return w.json(js(E),500)}}),v.get("/__infer-info",w=>{let E=c?.(),R=gr(E?.config??"").inference,L=Hi(E?.data??""),N=lt();return typeof N=="string"?w.json({error:N,inference:R,data:L}):w.json({provider:N.protocol,model:N.model,inference:R,data:L})}),v.use("/__infer-decode",C),v.post("/__infer-decode",async w=>w.json(await Z(w)??{error:"invalid fragment"})),v.get("/__infer-ui.js",w=>w.body(qw,200,{"Content-Type":"text/javascript; charset=utf-8"})),v.get("/__models",async w=>{try{let E=await ct();return w.json(E)}catch{return w.json([],200)}}),v.get("/__ai-access",async w=>{try{return w.json(await $o())}catch{return w.json("none",200)}}),h&&v.get("/__source/*",async w=>{let E=await ef.readFile(h,"utf-8").catch(()=>{});return E===void 0?w.text("Not Found",404):new Response(E,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let J=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],G=new Ca;v.get("/proxy/*",async w=>{let E=new URL(w.req.url),L=(E.pathname+E.search).slice(7),N=L.lastIndexOf("https://");return N===-1?w.text("Invalid proxy URL",400):hr(w,L.slice(N))}),f&&Kw(v,`/local/${f.name}/`,f.serveDir),p&&Kw(v,p.mount,p.dir),y&&v.get("/assets/*",async w=>{let{pathname:E}=new URL(w.req.url),R=E.slice(8),L;try{L=decodeURIComponent(R)}catch{return w.text("Not Found",404)}let N=Rf(L);if(N)return w.text(`${N} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{for(let X of y.dirs){let fe=await Yw(L,X,{"Cache-Control":"no-cache"});if(fe)return fe}}catch{return w.text("Not Found",404)}let K=y.remoteBase;return K?w.redirect(K+R,302):w.text("Not Found",404)});async function hr(w,E){let R;try{R=new URL(E)}catch{return w.text("Invalid URL",400)}if(R.protocol!=="https:")return w.text("HTTPS only",400);if(!J.includes(R.hostname))return w.text("Host not allowed",403);let L=await G.get(E);if(L)return new Response(L.body,{status:200,headers:Zd(L.contentType,L.cacheControl)});try{let N=await fetch(E,{headers:{Accept:w.req.header("Accept")||"*/*"},redirect:"follow"});if(!N.ok)return w.text(`Upstream ${N.status}`,N.status);let K=N.headers.get("Content-Type")||void 0,X=N.headers.get("Cache-Control")||void 0;if(N.body){let[fe,ne]=N.body.tee();return(async()=>{try{let re=await new Response(ne).arrayBuffer();await G.set(E,{body:Buffer.from(re),contentType:K,cacheControl:X})}catch{}})(),new Response(fe,{status:N.status,headers:Zd(K,X)})}return new Response(null,{status:N.status,headers:Zd(K,X)})}catch(N){return w.text(`Proxy fetch failed: ${N instanceof Error?N.message:N}`,502)}}(i||o)&&(v.get("/__reload",w=>Z_(w,async E=>{let R=()=>{E.writeSSE({event:"reload",data:""})},L=K=>{E.writeSSE({event:"message",data:JSON.stringify(K)})};i?.on("reload",R),o?.on("message",L);let N={inEditor:oR(w.req.header("user-agent")),open:K=>E.writeSSE({event:"open-url",data:K})};for(M.add(N),o&&o.listenerCount("message")===1&&console.log("[page] connected"),E.onAbort(()=>{i?.removeListener("reload",R),o?.removeListener("message",L),M.delete(N),I=Date.now()}),await E.writeSSE({event:"hello",data:g,retry:Kg});!E.aborted;)await E.sleep(3e4)})),v.use("/__open",C),v.post("/__open",async w=>{let E="";try{E=String((await w.req.json()).url??"")}catch{}if(!iR(E))return w.json({error:"a local http URL is required"},400);let R=[...M].find(L=>L.inEditor);return await R?.open(E),w.json({opened:!!R,pages:M.size})})),v.notFound(async w=>{if(w.req.method!=="GET")return w.text("Not Found",404);let E=new URL(w.req.url);return Jw(E.pathname,E.search)?hr(w,"https://esm.sh"+E.pathname+E.search):w.text("Not Found",404)});let Kt=Q_({fetch:v.fetch,port:s,hostname:tR});return Kt.listening||await new Promise((w,E)=>{let R=L=>E(L);Kt.once("error",R),Kt.once("listening",()=>{Kt.removeListener("error",R),w()})}),{port:s,close:()=>Kt.close(),requestPage:U}}function Zd(n,e){let t=new Headers;return n&&t.set("Content-Type",n),e&&t.set("Cache-Control",e),t.set("Access-Control-Allow-Origin","*"),t.set("Cross-Origin-Resource-Policy","cross-origin"),t}function Kw(n,e,t){n.get(`${e}*`,async r=>{let{pathname:s}=new URL(r.req.url);if(!s.startsWith(e))return r.text("Not Found",404);try{return await Yw(decodeURIComponent(s.slice(e.length)),t)??r.text("Not Found",404)}catch{return r.text("Not Found",404)}})}async function Yw(n,e,t={}){let r=Mo(n,e),s=await ef.readFile(r).catch(()=>{});if(s)return new Response(s,{headers:{"Content-Type":_f(r),...t}})}async function pr(){let n=[];for await(let e of process.stdin)n.push(e);return Buffer.concat(n).toString("utf-8")}function Fs(n){return(n.charCodeAt(0)===65279?n.slice(1):n).replace(/\r\n/g,`
|
|
2589
|
+
`).trimEnd()}function fR(n,e){return new Promise((t,r)=>{let s=new URL(n),i=Vw.request({hostname:s.hostname,port:s.port,path:s.pathname+s.search,method:"POST",headers:{"Content-Type":"text/plain","Content-Length":Buffer.byteLength(e)}},o=>{let a="";o.setEncoding("utf8"),o.on("data",c=>{a+=c}),o.on("end",()=>t({status:o.statusCode??0,text:a}))});i.setTimeout(0),i.on("error",r),i.end(e)})}var pR=n=>{let e=Math.round((Date.now()-n)/6e4);return e<1?"moments ago":e<60?`${e}m ago`:`${Math.round(e/60)}h ago`};async function zw(n,e,t=0){e==="-"&&(e=Fs(await pr()));let r=e!==void 0&&e.startsWith("tb:");r&&t<=0&&(t=jd);let s=e!==void 0&&/^tb:(click|set)( |$)/.test(e),i=$a.resolve(n),o=Mn(await Q(),i)[0];if(!o){let h=(await un(process.cwd()))(i);console.error(h?`No running server for '${n}' \u2014 it last ran ${pR(h)}. Relaunching reuses the same URL (a stale tab is one reload from live): npx typebulb ${n}`:`No running server for '${n}'. Start it first: npx typebulb ${n}`),process.exit(1)}let a=!1,c=async h=>{let g=[h>0?`reply=${h}`:"",s?"solo=1":"",t>0&&!a?"open=1":""].filter(Boolean).join("&"),x=await fR(`${o.url}/__send${g?`?${g}`:""}`,e??"");(x.status<200||x.status>=300)&&(console.error(`send failed: HTTP ${x.status} from ${o.url}/__send`),process.exit(1));try{return JSON.parse(x.text)}catch{return{}}},l={},f=Date.now();try{let h=f+t,g=h;do{if(l=await c(t>0?Math.max(g-Date.now(),1e3):0),(l.clients??0)>0||Date.now()>=g)break;let x=l.opening==="editor"||l.opening==="external";x||l.opening==="pending"?g=Math.max(g,Date.now()+tf):l.opening==="none"&&(g=Math.min(g,h)),x&&!a&&(a=!0,console.error(l.opening==="editor"?`Opened in VS Code via ${l.via}; waiting for the page.`:"Opened in your browser, where the agent mirror is; waiting for the page.")),await new Promise(v=>setTimeout(v,150))}while(!0)}catch(h){console.error(`send failed: ${h instanceof Error?h.message:String(h)}`),process.exit(1)}let u=l.clients??0,d=`${u} page${u===1?"":"s"}`;if(l.refused&&(console.error(`Actuation needs exactly one connected page; ${d} are open on ${o.url} \u2014 close the extras and retry.`),process.exit(1)),u===0){let h=l.droppedMsAgo,g=l.opening==="none"?" and no agent mirror page is open to open one through":"",x=a?" \u2014 the page was opened but never attached; is the browser it opened in still there?":h!==void 0?` \u2014 a page disconnected ${Math.round(h/1e3)}s ago and hasn't reconnected${g}; reload it, or open ${o.url}`:` \u2014 no page has ever connected${g}; share ${o.url} and arm: typebulb wait ${n} --match "[page] connected"`;t>0?console.error(`No page connected after ${((Date.now()-f)/1e3).toFixed(1)}s${x}`):console.error(`Sent, but no page is connected${x}`),r&&process.exit(1);return}console.error(`Sent to ${d}.`);let p=l.results??[],y=l.errors??[];for(let h of y)console.error(`handler error: ${h}`);if(y.length&&process.exit(1),p.length>1&&(console.error(`${p.length} replies from ${d} \u2014 one reply owns stdout: at most one tb.onMessage handler, in one page, may return a value.`),process.exit(1)),p.length===1){if(e!==void 0&&/^tb:png( |$)/.test(e)){let g={};try{g=JSON.parse(p[0])}catch{}typeof g.png!="string"&&(console.error("tb:png replied with an unexpected shape \u2014 an older runtime? (`typebulb logs` lists server versions)"),process.exit(1));let x=tg(i);await uR($a.dirname(x),{recursive:!0}),await dR(x,Buffer.from(g.png,"base64"));let v=[g.via?`inside "${g.via}"`:"",g.backdrop?`backdrop ${g.backdrop}`:""].filter(Boolean);console.error(`canvas ${g.width}\xD7${g.height} \u2192 PNG${v.length?` (${v.join("; ")})`:""}`),console.log(x);return}let h;try{h=JSON.parse(p[0])}catch{h=void 0}console.log(typeof h=="string"?h:p[0])}else l.timedOut&&(r&&(console.error(`No reply to '${e}' within ${t/1e3}s \u2014 reload the page and retry.`),process.exit(1)),console.error(`(no reply within ${t/1e3}s \u2014 slow work needs a larger --wait=ms; a reply that NEVER comes is a done-promise that missed an exit, or a blocked main thread: tb:snapshot runs no page code, so its silence too means blocked)`))}Go();ed();ee();import*as Gw from"fs/promises";async function Xw(n,e){let t=await Gw.readFile(n,"utf-8"),r=vn(t),s=ue[e].path,i=r.files.get(s);i||(console.error(i===void 0?`No **${s}** block in ${n}`:`The **${s}** block in ${n} is empty`),process.exit(2)),process.stdout.write(i.endsWith(`
|
|
2590
2590
|
`)?i:i+`
|
|
2591
|
-
`)}ee();import*as Us from"fs/promises";async function ev(n,e){let t=await Us.readFile(n,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await pr():await Us.readFile(o,"utf-8")}catch(c){Zw(`Cannot read ${i}'s source: ${c instanceof Error?c.message:String(c)}`)}r.push({kind:i,content:Fs(a),label:o==="-"?"stdin":o})}let s;try{s=
|
|
2591
|
+
`)}ee();import*as Us from"fs/promises";async function ev(n,e){let t=await Us.readFile(n,"utf-8"),r=[];for(let{kind:i,source:o}of e){let a;try{a=o==="-"?await pr():await Us.readFile(o,"utf-8")}catch(c){Zw(`Cannot read ${i}'s source: ${c instanceof Error?c.message:String(c)}`)}r.push({kind:i,content:Fs(a),label:o==="-"?"stdin":o})}let s;try{s=hR(t,r)}catch(i){Zw(`${n}: ${i instanceof Error?i.message:String(i)}`)}for(let i of s.upToDate)console.log(`${ue[i].path}: already up to date`);if(s.written.length){await Us.writeFile(n,s.text);for(let i of s.written)console.log(i.action==="removed"?`${ue[i.kind].path}: removed (${i.label} is empty)`:`${ue[i.kind].path}: ${i.action} from ${i.label} (${i.chars.toLocaleString()} chars)`)}}function hR(n,e){let t=vn(n),r=n,s=[],i=[];for(let{kind:o,content:a,label:c}of e){let l=ue[o].path,f=t.files.get(l);if(!a){if(f===void 0){i.push(o);continue}r=Qw(Of(r,o),r,l),s.push({kind:o,action:"removed",chars:0,label:c});continue}if(f!==void 0&&Fs(f)===a){i.push(o);continue}r=Qw(mr(r,o,a),r,l),s.push({kind:o,action:f===void 0?"created":"replaced",chars:a.length,label:c})}return{text:r,written:s,upToDate:i}}function Qw(n,e,t){if(n===e)throw new Error(`the **${t}** block's fence is unterminated; refusing to rewrite inside it`);return n}function Zw(n){console.error(n),process.exit(1)}at();Ge();ee();Wo();import*as Jt from"fs/promises";import*as Ma from"path";import{EventEmitter as tv}from"events";Ae();Zn();async function La(n){let{port:e,portNote:t,makeServerOptions:r,makeEntry:s,displayName:i,stopLog:o}=n,a=await Hw(r(e)).catch(async u=>{if(u?.code!=="EADDRINUSE")throw u;return Uu(e)}),c=`http://localhost:${e}`;await dg(s(e,c)),console.log(`
|
|
2592
2592
|
${i}`),console.log(` ${c}`),t&&console.log(` ${t}`);let l=[],f=async()=>{console.log(`
|
|
2593
2593
|
Shutting down...`),a.close();for(let u of l)try{await u()}catch{}o(),await ts(process.pid),process.exit(0)};return process.on("SIGINT",f),process.on("SIGTERM",f),{port:e,url:c,async handOver({mode:u,fresh:d,replacedLive:p}){if(u==="none")return;let y={fresh:d,external:p?"never":u==="window"?"force":"follow"},h=await a.requestPage(y);for(;h.how==="pending";)await new Promise(g=>setTimeout(g,150)),h=await a.requestPage(y);h.how==="attached"?console.log(` Reusing the open browser tab.
|
|
2594
2594
|
`):h.how==="editor"?console.log(` Opened in VS Code via ${h.via}.
|
|
2595
2595
|
`):h.how==="external"&&console.log(` Opened in your browser.
|
|
2596
|
-
`)},onCleanup(u){l.push(u)}}}Zn();import
|
|
2596
|
+
`)},onCleanup(u){l.push(u)}}}Zn();import mR from"chokidar";var gR={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function qt(n){let{target:e,onChange:t,events:r="change",debounceMs:s=150}=n,i,o=mR.watch(e,gR);o.on("error",c=>console.warn(`watch: ${c instanceof Error?c.message:c} \u2014 continuing`));let a=()=>{i&&clearTimeout(i),i=setTimeout(t,s)};return r==="all"?o.on("all",a):o.on("change",a),()=>{i&&clearTimeout(i),o.close()}}Ae();Jn();async function nv(n,e,t,r){let s=process.cwd(),i=so(process.pid),o=e.watch?new tv:void 0,a=new tv;a.setMaxListeners(0);let c=Oe(e.mode),l=await tu(n);l.length&&console.log(`Replacing the running server for this bulb (pid ${l.map(U=>U.pid).join(", ")})`);let f=(await un(process.cwd()))(n),{port:u,note:d}=await Ko({explicit:e.port,target:{kind:"bulb",file:n},cwd:process.cwd()}),p=1;console.log(Ql(p)),e.batch&&await Xn(n,e.batch),console.log(`Loading ${Ma.basename(n)}...`);let{html:y,bulb:h,serverExports:g}=await Du(n,e.watch,e.trust,r,e.batch);$t(c,n,h.server);let x=[...e.batch?[Bt(n,e.batch)]:[],Bt(n)],v=Qn(Ma.resolve(n)),P=e.trust?void 0:er(h),{port:_,onCleanup:C,handOver:I}=await La({port:u,portNote:d,displayName:h.name,stopLog:i,makeServerOptions:U=>({getHtml:()=>y,basePath:s,fsBase:Mt(n,e.batch),port:U,reloadEmitter:o,messageEmitter:a,getServerExports:()=>g,getBulbBlocks:()=>({infer:h.infer,insight:h.insight,code:h.code,config:h.config,data:h.data}),saveInferenceResult:async(Z,J)=>{let G=await Jt.readFile(n,"utf-8");G=mr(G,"data",Z.join(_m)),G=mr(G,"insight",J),await Jt.writeFile(n,G)},localOverride:r?{name:r.name,serveDir:r.serveDir}:void 0,bulbAssets:{dirs:x,remoteBase:v&&Vs(v.userSlug,v.slug)},sourceFile:n,trusted:e.trust,trustHint:t}),makeEntry:(U,Z)=>({pid:process.pid,port:U,url:Z,file:n,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,batch:e.batch,mode:e.mode,predicted:P})});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(P?` trust: restricted \u2014 this bulb appears to use ${P}; re-run with --trust to enable it:
|
|
2597
2597
|
${t}
|
|
2598
2598
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
2599
2599
|
`),e.watch&&console.log(` Watching for changes...
|
|
2600
2600
|
`);let M,A;if(e.watch&&o){let U=0,Z=Promise.resolve();if(M=qt({target:n,onChange:()=>{let J=++U;Z=Z.then(async()=>{if(J===U)try{console.log("Recompiling...");let G=await Du(n,!0,e.trust,r,e.batch);y=G.html,g=G.serverExports,h=G.bulb,p++,console.log(Ql(p)),o.emit("reload")}catch(G){console.error("Compile error:",G)}})}}),r){let{name:J,serveDir:G}=r;A=qt({target:G,events:"all",onChange:()=>{console.log(`Local package '${J}' changed. Browser reloading...
|
|
2601
2601
|
`),o.emit("reload")}})}for(let J of x)await Jt.stat(J).then(G=>G.isDirectory()).catch(()=>!1)&&C(qt({target:J,events:"all",onChange:()=>{console.log(`Assets changed. Browser reloading...
|
|
2602
|
-
`),o.emit("reload")}}))}M&&C(M),A&&C(A),C(()=>Jt.rm(Bu(n),{force:!0}));let j=l.length>0||Date.now()-f<bu;await I({mode:e.open,fresh:!j,replacedLive:l.some(U=>U.port===_)})}at();import{readFileSync as sv,copyFileSync as
|
|
2602
|
+
`),o.emit("reload")}}))}M&&C(M),A&&C(A),C(()=>Jt.rm(Bu(n),{force:!0}));let j=l.length>0||Date.now()-f<bu;await I({mode:e.open,fresh:!j,replacedLive:l.some(U=>U.port===_)})}at();import{readFileSync as sv,copyFileSync as bR,existsSync as wR}from"fs";import*as he from"path";import{fileURLToPath as vR}from"url";import{EventEmitter as SR}from"events";import kR from"open";Zn();Ae();Jn();var nf=n=>`/agents/${n}/client.js`,yR=`
|
|
2603
2603
|
(() => {
|
|
2604
2604
|
const api = async (name, ...args) => {
|
|
2605
2605
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -2651,17 +2651,17 @@ ${s}
|
|
|
2651
2651
|
${i?"<script>window.__TYPEBULB_WATCH__ = true;</script>":""}
|
|
2652
2652
|
|
|
2653
2653
|
<script>
|
|
2654
|
-
${
|
|
2654
|
+
${yR}
|
|
2655
2655
|
</script>
|
|
2656
2656
|
|
|
2657
2657
|
<script type="module" src="${a}"></script>
|
|
2658
2658
|
</body>
|
|
2659
2659
|
</html>`}async function iv(n){let e=process.cwd(),t=n.agentTarget;tw(t)||(console.error(`Unknown agent '${t}'. Known: ${ur().join(", ")}.`),process.exit(1));let r=await eu(e,t);if(r){console.log(`Mirror '${t}' is already running for this project:
|
|
2660
|
-
${r.url}`),n.open==="window"&&await
|
|
2661
|
-
`);let C=he.join(u,t,"client"),I=he.join(u,"core","client");async function M(){await(await import("esbuild")).build({entryPoints:[he.join(C,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:he.join(f,"client.js")});for(let U of["styles.css","index.html","typebulb.png","typebulb-inv.png"])
|
|
2660
|
+
${r.url}`),n.open==="window"&&await kR(r.url);return}let s=so(process.pid),i=n.watch?new SR:void 0,o=Oe(n.mode),a=await rw(t),c=a.displayName||`${t} mirror`;$t(o,he.join(e,"mirror"));let l=he.dirname(vR(import.meta.url)),f=he.join(l,"agents",t),u=he.join(l,"..","cli","agents"),d=he.join(f,"styles.css"),p=he.join(f,"index.html"),y=()=>rv({name:c,agent:t,styles:sv(d,"utf8"),mountHtml:sv(p,"utf8"),watch:n.watch}),{port:h,note:g}=await Ko({explicit:n.port,target:{kind:"mirror",agent:t},cwd:e}),{port:x,url:v,onCleanup:P,handOver:_}=await La({port:h,portNote:g,displayName:c,stopLog:s,makeServerOptions:j=>({getHtml:y,basePath:e,port:j,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${he.posix.dirname(nf(t))}/`,dir:f}}),makeEntry:(j,U)=>({pid:process.pid,port:j,url:U,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});n.watch&&console.log(` Watching for changes...
|
|
2661
|
+
`);let C=he.join(u,t,"client"),I=he.join(u,"core","client");async function M(){await(await import("esbuild")).build({entryPoints:[he.join(C,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:he.join(f,"client.js")});for(let U of["styles.css","index.html","typebulb.png","typebulb-inv.png"])bR(he.join(I,U),he.join(f,U))}let A;if(n.watch&&i){let j=wR(C),U=!1;A=qt({target:j?u:f,events:"all",onChange:async()=>{if(!U){U=!0;try{j&&await M(),console.log(`Mirror rebuilt. Browser reloading...
|
|
2662
2662
|
`),i.emit("reload")}catch(Z){console.error("Mirror rebuild failed:",Z instanceof Error?Z.message:Z)}finally{U=!1}}}})}await _({mode:n.open,fresh:!1,replacedLive:!1}),P(()=>a.shutdownSwitcher?.()),P(()=>a.shutdownComposer?.()),A&&P(A)}at();Ge();import*as ov from"path";async function av(n,e,t,r,s){let i=Oe(t),o=!1;s&&await Xn(n,s);let a=async()=>{let{bulb:c,config:l}=await qe(n);o||($t(i,n,c.server),o=!0),await Ss(c.server,n,r,l.dependencies,s)};if(console.log(`Running ${ov.basename(n)}...`),await a(),e){console.log(`Watching for changes...
|
|
2663
|
-
`);let c=0,l=Promise.resolve();qt({target:n,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}at();Ge();import{Console as
|
|
2664
|
-
`)}catch(p){qs(p instanceof Error?p.stack??p.message:String(p))}return cv(0)}let u;try{u=await l(...f)}catch(p){qs(p instanceof Error?p.stack??p.message:String(p))}let d=
|
|
2665
|
-
`),cv(0)}function cv(n){process.exitCode=n,setTimeout(()=>process.exit(n),2e3).unref?.()}async function
|
|
2666
|
-
`),process.exit(1)}function
|
|
2667
|
-
${e}`),process.exit(1))}async function
|
|
2663
|
+
`);let c=0,l=Promise.resolve();qt({target:n,onChange:()=>{let f=++c;l=l.then(async()=>{if(f===c)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}at();Ge();import{Console as xR}from"node:console";Ae();async function uv(n,e,t,r,s){PR();try{let p=Mn(await Q(),n)[0];p&&(ro(p.pid,Ye(p.pid).offset),console.error(`note: 'call' boots a fresh server.ts instance; the running server (${p.url}) is not contacted \u2014 state shared with it must live on disk.`))}catch{}let i=Oe(t),{bulb:o,config:a}=await qe(n);o.server||qs("This bulb has no **server.ts** block; nothing to call."),$t(i,n,o.server),s&&await Xn(n,s);let c;try{c=await Ss(o.server,n,r,a.dependencies,s)}catch(p){qs(p instanceof Error?p.message:String(p))}let l=Ia(c,e.fn);if(!l){let p=[...Object.keys(c).filter(y=>typeof c[y]=="function"),...Object.keys(Ra)];qs(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let f=await ER(e);if(Na(l)){try{for await(let p of l(...f))await lv(JSON.stringify(p,dv)+`
|
|
2664
|
+
`)}catch(p){qs(p instanceof Error?p.stack??p.message:String(p))}return cv(0)}let u;try{u=await l(...f)}catch(p){qs(p instanceof Error?p.stack??p.message:String(p))}let d=OR(u);d!==void 0&&await lv(d+`
|
|
2665
|
+
`),cv(0)}function cv(n){process.exitCode=n,setTimeout(()=>process.exit(n),2e3).unref?.()}async function ER(n){if(n.hasArgsFlag){let e=n.argsJson??"";return e==="-"&&(e=await pr()),TR(e)}return AR(n.positional)}function AR(n){return n.map(e=>{try{return JSON.parse(e)}catch{return e}})}function TR(n){let e;try{e=JSON.parse(n)}catch(t){throw new Error(`--args must be a JSON array: ${t instanceof Error?t.message:String(t)}`)}if(!Array.isArray(e))throw new Error(`--args must be a JSON array, got ${e===null?"null":typeof e}`);return e}function OR(n){if(n!==void 0)return JSON.stringify(n,dv,2)}function dv(n,e){return typeof e=="bigint"?e.toString():e}function qs(n){process.stderr.write(n+`
|
|
2666
|
+
`),process.exit(1)}function PR(){let n=new xR(process.stderr,process.stderr);console.log=n.log.bind(n),console.info=n.info.bind(n),console.debug=n.debug.bind(n),console.dir=n.dir.bind(n)}function lv(n){return new Promise((e,t)=>{process.stdout.write(n,r=>r?t(r):e())})}to();for(let n of[process.stdout,process.stderr])n.on("error",e=>{if(e?.code!=="EPIPE")throw e});function fv(n,e){n||(console.error(`This bulb runs server-side Node code (server.ts), which --trust must authorize:
|
|
2667
|
+
${e}`),process.exit(1))}async function CR(){let n=ow(process.argv.slice(2));if(n.version&&(console.log(`typebulb ${Be}`),process.exit(0)),n.help&&(aw(),process.exit(0)),sw(),n.subcommand==="logs"){await Dw(n.file||void 0,{follow:n.follow,clear:n.clear,run:n.run,lines:n.lines});return}if(n.subcommand==="wait"){await jw(n.file||void 0,{match:n.match,timeoutSec:n.timeoutSec});return}if(n.subcommand==="stop"){n.stopScope?await Uw(n.stopScope):await Fw(n.file||void 0);return}if(n.subcommand==="send"){await zw(n.file,n.sendMessage,n.sendWaitMs??0);return}if(n.subcommand==="models"){await Nw(n.mode);return}if(n.subcommand==="slug"){$w(n.slugName);return}if(n.subcommand==="pull"){await $y(n.file||void 0,{force:n.force,mode:n.mode});return}if(n.subcommand==="push"){await My(n.file||void 0,{force:n.force,mode:n.mode});return}if(n.subcommand==="agent"){await(n.agentTarget?iv(n):Iw(Be));return}if(n.subcommand==="trust"||n.subcommand==="untrust"){await Pw(n.file||void 0,n.subcommand==="trust");return}let e;if(!n.file||n.file==="."){let c=await my(process.cwd());c||(console.error("No .bulb.md file found in current directory"),process.exit(1)),e=c}else e=pt.resolve(n.file);if(await pv.access(e).then(()=>!0,()=>!1)||(ur().includes(n.file)&&(console.error(`To open the ${n.file} agent mirror, run: npx typebulb agent:${n.file}`),process.exit(1)),console.error(`File not found: ${e}`+(pt.isAbsolute(n.file)?"":` (resolved from cwd ${process.cwd()})`)),process.exit(1)),e.endsWith(".bulb.md")||(console.error("File must have .bulb.md extension"),process.exit(1)),n.subcommand==="get"){await Xw(e,n.blockKind);return}if(n.subcommand==="put"){await ev(e,n.blockPairs);return}let r=n.file&&n.file!=="."?n.file:pt.relative(process.cwd(),e)||pt.basename(e),s=`npx typebulb --trust ${r.includes(" ")?`"${r}"`:r}`;if(n.subcommand==="predict"){await Ow(e,s);return}let i=!n.noTrust&&dn(e);i&&!n.trust&&console.error("trust: granted from memory (run `typebulb untrust` to revoke)"),n.trust=n.noTrust?!1:n.trust||i;let o;try{o=await qe(e)}catch{}let a;if(n.local){o&&!(n.local.name in(o.config.dependencies??{}))&&(console.error(`--replace: '${n.local.name}' is not a dependency in this bulb's config.json; nothing to replace.`),process.exit(1)),o&&n.subcommand!=="call"&&(!o.bulb.code||n.server)&&console.warn("warning: --replace has no effect in server mode (the override is client-only).");try{a=await hf(n.local)}catch(c){console.error(c instanceof Error?c.message:String(c)),process.exit(1)}console.error(`replace: ${a.name} \u2192 ${pt.relative(process.cwd(),a.dir)||"."}`)}if(n.subcommand==="check"){await Tw(e,a);return}if(n.subcommand==="call"){fv(n.trust,s),await uv(e,{fn:n.fn,positional:n.callArgs,argsJson:n.argsJson,hasArgsFlag:n.hasArgsFlag},n.mode,a,n.batch);return}if(o&&o.bulb.server&&(oo(o.bulb)||n.server)){fv(n.trust,s),await av(e,n.watch,n.mode,a,n.batch);return}await nv(e,n,s,a)}CR().catch(n=>{console.error("Error:",n.message),process.exit(1)});
|