typebulb 0.58.0 → 0.58.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -7
- package/SKILL.md +10 -9
- package/dist/agents/claude/client.js +4 -5
- package/dist/agents/codex/client.js +4 -5
- package/dist/agents/pi/client.js +4 -5
- package/dist/dts/tbTypings.d.ts.map +1 -1
- package/dist/dts/tbTypings.js +284 -281
- package/dist/dts/tbTypings.js.map +1 -1
- package/dist/format/runtimeState.d.ts +9 -8
- package/dist/format/runtimeState.d.ts.map +1 -1
- package/dist/format/runtimeState.js +63 -62
- package/dist/format/runtimeState.js.map +1 -1
- package/dist/index.js +107 -54
- package/dist/render.js +4 -5
- package/dist/servers.js +4 -5
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -62,7 +62,7 @@ ${Wr.indentComment($,t.indent)}`}I===""&&!t.inFlow?R===`
|
|
|
62
62
|
|
|
63
63
|
`):R+=`
|
|
64
64
|
${t.indent}`}else if(!p&&at.isCollection(e)){let $=I[0],A=I.indexOf(`
|
|
65
|
-
`),
|
|
65
|
+
`),K=A!==-1,Q=t.inFlow??e.flow??e.items.length===0;if(K||!Q){let Z=!1;if(K&&($==="&"||$==="!")){let F=I.indexOf(" ");$==="&"&&F!==-1&&F<A&&I[F+1]==="!"&&(F=I.indexOf(" ",F+1)),(F===-1||A<F)&&(Z=!0)}Z||(R=`
|
|
66
66
|
${t.indent}`)}}else(I===""||I[0]===`
|
|
67
67
|
`)&&(R="");return y+=R+I,t.inFlow?x&&r&&r():_&&!x?y+=Wr.lineComment(y,t.indent,c(_)):h&&s&&s(),y}Ip.stringifyPair=ik});var Cl=C(_l=>{"use strict";var $p=ii("process");function ok(n,...e){n==="debug"&&console.log(...e)}function ak(n,e){(n==="debug"||n==="warn")&&(typeof $p.emitWarning=="function"?$p.emitWarning(e):console.warn(e))}_l.debug=ok;_l.warn=ak});var Ci=C(_i=>{"use strict";var Hr=U(),Lp=re(),Pi="<<",Oi={identify:n=>n===Pi||typeof n=="symbol"&&n.description===Pi,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Lp.Scalar(Symbol(Pi)),{addToJSMap:Mp}),stringify:()=>Pi},lk=(n,e)=>(Oi.identify(e)||Hr.isScalar(e)&&(!e.type||e.type===Lp.Scalar.PLAIN)&&Oi.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Oi.tag&&t.default);function Mp(n,e,t){if(t=n&&Hr.isAlias(t)?t.resolve(n.doc):t,Hr.isSeq(t))for(let r of t.items)Rl(n,e,r);else if(Array.isArray(t))for(let r of t)Rl(n,e,r);else Rl(n,e,t)}function Rl(n,e,t){let r=n&&Hr.isAlias(t)?t.resolve(n.doc):t;if(!Hr.isMap(r))throw new Error("Merge sources must be maps or map aliases");let s=r.toJSON(null,n,Map);for(let[i,o]of s)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}_i.addMergeToJSMap=Mp;_i.isMergeKey=lk;_i.merge=Oi});var Nl=C(jp=>{"use strict";var ck=Cl(),Bp=Ci(),uk=Kr(),Dp=U(),Il=kt();function dk(n,e,{key:t,value:r}){if(Dp.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,r);else if(Bp.isMergeKey(n,t))Bp.addMergeToJSMap(n,e,r);else{let s=Il.toJS(t,"",n);if(e instanceof Map)e.set(s,Il.toJS(r,s,n));else if(e instanceof Set)e.add(s);else{let i=fk(t,s,n),o=Il.toJS(r,i,n);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function fk(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Dp.isNode(n)&&t?.doc){let r=uk.createStringifyContext(t.doc,{});r.anchors=new Set;for(let i of t.anchors.keys())r.anchors.add(i.anchor);r.inFlow=!0,r.inStringifyKey=!0;let s=n.toString(r);if(!t.mapKeyWarned){let i=JSON.stringify(s);i.length>40&&(i=i.substring(0,36)+'..."'),ck.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return s}return JSON.stringify(e)}jp.addPairToJSMap=dk});var Tt=C($l=>{"use strict";var Fp=jr(),pk=Np(),hk=Nl(),Ri=U();function mk(n,e,t){let r=Fp.createNode(n,void 0,t),s=Fp.createNode(e,void 0,t);return new Ii(r,s)}var Ii=class n{constructor(e,t=null){Object.defineProperty(this,Ri.NODE_TYPE,{value:Ri.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:r}=this;return Ri.isNode(t)&&(t=t.clone(e)),Ri.isNode(r)&&(r=r.clone(e)),new n(t,r)}toJSON(e,t){let r=t?.mapAsMap?new Map:{};return hk.addPairToJSMap(t,r,this)}toString(e,t,r){return e?.doc?pk.stringifyPair(this,e,t,r):JSON.stringify(this)}};$l.Pair=Ii;$l.createPair=mk});var Ll=C(qp=>{"use strict";var Zt=U(),Up=Kr(),Ni=Fr();function gk(n,e,t){return(e.inFlow??n.flow?bk:yk)(n,e,t)}function yk({comment:n,items:e},t,{blockItemPrefix:r,flowChars:s,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:l,options:{commentString:c}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,f=[];for(let m=0;m<e.length;++m){let h=e[m],y=null;if(Zt.isNode(h))!u&&h.spaceBefore&&f.push(""),$i(t,f,h.commentBefore,u),h.comment&&(y=h.comment);else if(Zt.isPair(h)){let T=Zt.isNode(h.key)?h.key:null;T&&(!u&&T.spaceBefore&&f.push(""),$i(t,f,T.commentBefore,u))}u=!1;let E=Up.stringify(h,d,()=>y=null,()=>u=!0);y&&(E+=Ni.lineComment(E,i,c(y))),u&&y&&(u=!1),f.push(r+E)}let p;if(f.length===0)p=s.start+s.end;else{p=f[0];for(let m=1;m<f.length;++m){let h=f[m];p+=h?`
|
|
68
68
|
${l}${h}`:`
|
|
@@ -82,13 +82,13 @@ ${i.comment}`:r.comment}r=s}n.items[t]=Ji.isPair(r)?r:new Vl.Pair(r)}}else e("Ex
|
|
|
82
82
|
|
|
83
83
|
${o}
|
|
84
84
|
${c}
|
|
85
|
-
`}};rs.YAMLError=ns;rs.YAMLParseError=yc;rs.YAMLWarning=bc;rs.prettifyError=Gx});var is=C(Fh=>{"use strict";function Xx(n,{flow:e,indicator:t,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",f="",p=!1,m=!1,h=null,y=null,E=null,T=null,_=null,x=null,I=null;for(let A of n)switch(m&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(c&&A.type!=="comment"&&A.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),A.type){case"space":!e&&(t!=="doc-start"||r?.type!=="flow-collection")&&A.source.includes(" ")&&(h=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let
|
|
85
|
+
`}};rs.YAMLError=ns;rs.YAMLParseError=yc;rs.YAMLWarning=bc;rs.prettifyError=Gx});var is=C(Fh=>{"use strict";function Xx(n,{flow:e,indicator:t,next:r,offset:s,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",f="",p=!1,m=!1,h=null,y=null,E=null,T=null,_=null,x=null,I=null;for(let A of n)switch(m&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),h&&(c&&A.type!=="comment"&&A.type!=="newline"&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),h=null),A.type){case"space":!e&&(t!=="doc-start"||r?.type!=="flow-collection")&&A.source.includes(" ")&&(h=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let K=A.source.substring(1)||" ";u?u+=f+K:u=K,f="",c=!1;break}case"newline":c?u?u+=A.source:(!x||t!=="seq-item-ind")&&(l=!0):f+=A.source,c=!0,p=!0,(y||E)&&(T=A),d=!0;break;case"anchor":y&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,I??(I=A.offset),c=!1,d=!1,m=!0;break;case"tag":{E&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),E=A,I??(I=A.offset),c=!1,d=!1,m=!0;break}case t:(y||E)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),x&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),x=A,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){_&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=A,c=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),c=!1,d=!1}let R=n[n.length-1],$=R?R.offset+R.source.length:s;return m&&r&&r.type!=="space"&&r.type!=="newline"&&r.type!=="comma"&&(r.type!=="scalar"||r.source!=="")&&i(r.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h&&(c&&h.indent<=o||r?.type==="block-map"||r?.type==="block-seq")&&i(h,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:x,spaceBefore:l,comment:u,hasNewline:p,anchor:y,tag:E,newlineAfterProp:T,end:$,start:I??$}}Fh.resolveProps=Xx});var to=C(Uh=>{"use strict";function wc(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
|
|
86
86
|
`))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(wc(e.key)||wc(e.value))return!0}return!1;default:return!0}}Uh.containsNewline=wc});var vc=C(qh=>{"use strict";var Qx=to();function Zx(n,e,t){if(e?.type==="flow-collection"){let r=e.end[0];r.indent===n&&(r.source==="]"||r.source==="}")&&Qx.containsNewline(e)&&t(r,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}qh.flowIndentCheck=Zx});var Sc=C(Kh=>{"use strict";var Jh=U();function e0(n,e,t){let{uniqueKeys:r}=n.options;if(r===!1)return!1;let s=typeof r=="function"?r:(i,o)=>i===o||Jh.isScalar(i)&&Jh.isScalar(o)&&i.value===o.value;return e.some(i=>s(i.key,t))}Kh.mapIncludes=e0});var Gh=C(zh=>{"use strict";var Wh=Tt(),t0=Ot(),Hh=is(),n0=to(),Yh=vc(),r0=Sc(),Vh="All mapping items must start at the same column";function s0({composeNode:n,composeEmptyNode:e},t,r,s,i){let o=i?.nodeClass??t0.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=r.offset,c=null;for(let d of r.items){let{start:u,key:f,sep:p,value:m}=d,h=Hh.resolveProps(u,{indicator:"explicit-key-ind",next:f??p?.[0],offset:l,onError:s,parentIndent:r.indent,startOnNewline:!0}),y=!h.found;if(y){if(f&&(f.type==="block-seq"?s(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==r.indent&&s(l,"BAD_INDENT",Vh)),!h.anchor&&!h.tag&&!p){c=h.end,h.comment&&(a.comment?a.comment+=`
|
|
87
87
|
`+h.comment:a.comment=h.comment);continue}(h.newlineAfterProp||n0.containsNewline(f))&&s(f??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else h.found?.indent!==r.indent&&s(l,"BAD_INDENT",Vh);t.atKey=!0;let E=h.end,T=f?n(t,f,h,s):e(t,E,u,null,h,s);t.schema.compat&&Yh.flowIndentCheck(r.indent,f,s),t.atKey=!1,r0.mapIncludes(t,a.items,T)&&s(E,"DUPLICATE_KEY","Map keys must be unique");let _=Hh.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:T.range[2],onError:s,parentIndent:r.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=_.end,_.found){y&&(m?.type==="block-map"&&!_.hasNewline&&s(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&h.start<_.found.offset-1024&&s(T.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let x=m?n(t,m,_,s):e(t,l,p,null,_,s);t.schema.compat&&Yh.flowIndentCheck(r.indent,m,s),l=x.range[2];let I=new Wh.Pair(T,x);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}else{y&&s(T.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(T.comment?T.comment+=`
|
|
88
88
|
`+_.comment:T.comment=_.comment);let x=new Wh.Pair(T);t.options.keepSourceTokens&&(x.srcToken=d),a.items.push(x)}}return c&&c<l&&s(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[r.offset,l,c??l],a}zh.resolveBlockMap=s0});var Qh=C(Xh=>{"use strict";var i0=_t(),o0=is(),a0=vc();function l0({composeNode:n,composeEmptyNode:e},t,r,s,i){let o=i?.nodeClass??i0.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=r.offset,c=null;for(let{start:d,value:u}of r.items){let f=o0.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:l,onError:s,parentIndent:r.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||u)u?.type==="block-seq"?s(f.end,"BAD_INDENT","All sequence items must start at the same column"):s(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(a.comment=f.comment);continue}let p=u?n(t,u,f,s):e(t,f.end,d,null,f,s);t.schema.compat&&a0.flowIndentCheck(r.indent,u,s),l=p.range[2],a.items.push(p)}return a.range=[r.offset,l,c??l],a}Xh.resolveBlockSeq=l0});var Fn=C(Zh=>{"use strict";function c0(n,e,t,r){let s="";if(n){let i=!1,o="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{t&&!i&&r(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=l.substring(1)||" ";s?s+=o+d:s=d,o="";break}case"newline":s&&(o+=l),i=!0;break;default:r(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:s,offset:e}}Zh.resolveEnd=c0});var rm=C(nm=>{"use strict";var u0=U(),d0=Tt(),em=Ot(),f0=_t(),p0=Fn(),tm=is(),h0=to(),m0=Sc(),kc="Block collections are not allowed within flow collections",xc=n=>n&&(n.type==="block-map"||n.type==="block-seq");function g0({composeNode:n,composeEmptyNode:e},t,r,s,i){let o=r.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?em.YAMLMap:f0.YAMLSeq),c=new l(t.schema);c.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=r.offset+r.start.source.length;for(let y=0;y<r.items.length;++y){let E=r.items[y],{start:T,key:_,sep:x,value:I}=E,R=tm.resolveProps(T,{flow:a,indicator:"explicit-key-ind",next:_??x?.[0],offset:u,onError:s,parentIndent:r.indent,startOnNewline:!1});if(!R.found){if(!R.anchor&&!R.tag&&!x&&!I){y===0&&R.comma?s(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<r.items.length-1&&s(R.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),R.comment&&(c.comment?c.comment+=`
|
|
89
89
|
`+R.comment:c.comment=R.comment),u=R.end;continue}!o&&t.options.strict&&h0.containsNewline(_)&&s(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)R.comma&&s(R.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(R.comma||s(R.start,"MISSING_CHAR",`Missing , between ${a} items`),R.comment){let $="";e:for(let A of T)switch(A.type){case"comma":case"space":break;case"comment":$=A.source.substring(1);break e;default:break e}if($){let A=c.items[c.items.length-1];u0.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
|
|
90
|
-
`+$:A.comment=$,R.comment=R.comment.substring($.length+1)}}if(!o&&!x&&!R.found){let $=I?n(t,I,R,s):e(t,R.end,x,null,R,s);c.items.push($),u=$.range[2],xc(I)&&s($.range,"BLOCK_IN_FLOW",kc)}else{t.atKey=!0;let $=R.end,A=_?n(t,_,R,s):e(t,$,T,null,R,s);xc(_)&&s(A.range,"BLOCK_IN_FLOW",kc),t.atKey=!1;let
|
|
91
|
-
`+
|
|
90
|
+
`+$:A.comment=$,R.comment=R.comment.substring($.length+1)}}if(!o&&!x&&!R.found){let $=I?n(t,I,R,s):e(t,R.end,x,null,R,s);c.items.push($),u=$.range[2],xc(I)&&s($.range,"BLOCK_IN_FLOW",kc)}else{t.atKey=!0;let $=R.end,A=_?n(t,_,R,s):e(t,$,T,null,R,s);xc(_)&&s(A.range,"BLOCK_IN_FLOW",kc),t.atKey=!1;let K=tm.resolveProps(x??[],{flow:a,indicator:"map-value-ind",next:I,offset:A.range[2],onError:s,parentIndent:r.indent,startOnNewline:!1});if(K.found){if(!o&&!R.found&&t.options.strict){if(x)for(let F of x){if(F===K.found)break;if(F.type==="newline"){s(F,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}R.start<K.found.offset-1024&&s(K.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else I&&("source"in I&&I.source?.[0]===":"?s(I,"MISSING_CHAR",`Missing space after : in ${a}`):s(K.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let Q=I?n(t,I,K,s):K.found?e(t,K.end,x,null,K,s):null;Q?xc(I)&&s(Q.range,"BLOCK_IN_FLOW",kc):K.comment&&(A.comment?A.comment+=`
|
|
91
|
+
`+K.comment:A.comment=K.comment);let Z=new d0.Pair(A,Q);if(t.options.keepSourceTokens&&(Z.srcToken=E),o){let F=c;m0.mapIncludes(t,F.items,A)&&s($,"DUPLICATE_KEY","Map keys must be unique"),F.items.push(Z)}else{let F=new em.YAMLMap(t.schema);F.flow=!0,F.items.push(Z);let ye=(Q??A).range;F.range=[A.range[0],ye[1],ye[2]],c.items.push(F)}u=Q?Q.range[2]:K.end}}let f=o?"}":"]",[p,...m]=r.end,h=u;if(p?.source===f)h=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),E=d?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;s(u,d?"MISSING_CHAR":"BAD_INDENT",E),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let y=p0.resolveEnd(m,h,t.options.strict,s);y.comment&&(c.comment?c.comment+=`
|
|
92
92
|
`+y.comment:c.comment=y.comment),c.range=[r.offset,h,y.offset]}else c.range=[r.offset,h,h];return c}nm.resolveFlowCollection=g0});var im=C(sm=>{"use strict";var y0=U(),b0=re(),w0=Ot(),v0=_t(),S0=Gh(),k0=Qh(),x0=rm();function Ec(n,e,t,r,s,i){let o=t.type==="block-map"?S0.resolveBlockMap(n,e,t,r,i):t.type==="block-seq"?k0.resolveBlockSeq(n,e,t,r,i):x0.resolveFlowCollection(n,e,t,r,i),a=o.constructor;return s==="!"||s===a.tagName?(o.tag=a.tagName,o):(s&&(o.tag=s),o)}function E0(n,e,t,r,s){let i=r.tag,o=i?e.directives.tagName(i.source,f=>s(i,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=r,m=f&&i?f.offset>i.offset?f:i:f??i;m&&(!p||p.offset<m.offset)&&s(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===w0.YAMLMap.tagName&&a==="map"||o===v0.YAMLSeq.tagName&&a==="seq")return Ec(n,e,t,s,o);let l=e.schema.tags.find(f=>f.tag===o&&f.collection===a);if(!l){let f=e.schema.knownTags[o];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?s(i,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):s(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ec(n,e,t,s,o)}let c=Ec(n,e,t,s,o,l),d=l.resolve?.(c,f=>s(i,"TAG_RESOLVE_FAILED",f),e.options)??c,u=y0.isNode(d)?d:new b0.Scalar(d);return u.range=c.range,u.tag=o,l?.format&&(u.format=l.format),u}sm.composeCollection=E0});var Tc=C(om=>{"use strict";var Ac=re();function A0(n,e,t){let r=e.offset,s=T0(e,n.options.strict,t);if(!s)return{value:"",type:null,comment:"",range:[r,r,r]};let i=s.mode===">"?Ac.Scalar.BLOCK_FOLDED:Ac.Scalar.BLOCK_LITERAL,o=e.source?P0(e.source):[],a=o.length;for(let h=o.length-1;h>=0;--h){let y=o[h][1];if(y===""||y==="\r")a=h;else break}if(a===0){let h=s.chomp==="+"&&o.length>0?`
|
|
93
93
|
`.repeat(Math.max(1,o.length-1)):"",y=r+s.length;return e.source&&(y+=e.source.length),{value:h,type:i,comment:s.comment,range:[r,y,y]}}let l=e.indent+s.indent,c=e.offset+s.length,d=0;for(let h=0;h<a;++h){let[y,E]=o[h];if(E===""||E==="\r")s.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(c+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),s.indent===0&&(l=y.length),d=h,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+E.length+1}for(let h=o.length-1;h>=a;--h)o[h][0].length>l&&(a=h+1);let u="",f="",p=!1;for(let h=0;h<d;++h)u+=o[h][0].slice(l)+`
|
|
94
94
|
`;for(let h=d;h<a;++h){let[y,E]=o[h];c+=y.length+E.length+1;let T=E[E.length-1]==="\r";if(T&&(E=E.slice(0,-1)),E&&y.length<l){let x=`Block scalar lines must not be less indented than their ${s.indent?"explicit indentation indicator":"first line"}`;t(c-E.length-(T?2:1),"BAD_INDENT",x),y=""}i===Ac.Scalar.BLOCK_LITERAL?(u+=f+y.slice(l)+E,f=`
|
|
@@ -159,7 +159,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
159
159
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
160
160
|
`,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let r=!this.onKeyLine&&this.indent===e.indent,s=r&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(s&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":s||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):s||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Ct(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Dm(t.key)&&!Ct(t.sep,"newline")){let o=Un(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(Ct(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Un(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||s?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Ct(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);s||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Ct(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else r&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let r="end"in t.value?t.value.end:void 0;(Array.isArray(r)?r[r.length-1]:void 0)?.type==="comment"?r?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){Array.prototype.push.apply(s,t.start),s.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Ct(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let r=this.startBlockValue(e);if(r){this.stack.push(r);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let r;do yield*this.pop(),r=this.peek(1);while(r?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:s,sep:[]}):t.sep?this.stack.push(s):Object.assign(t,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let r=this.startBlockValue(e);r?this.stack.push(r):(yield*this.pop(),yield*this.step())}else{let r=this.peek(2);if(r.type==="block-map"&&(this.type==="map-value-ind"&&r.indent===e.indent||this.type==="newline"&&!r.items[r.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&r.type!=="flow-collection"){let s=ao(r),i=Un(s);Bm(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
|
|
161
161
|
`)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
|
|
162
|
-
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ao(e),r=Un(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=ao(e),r=Un(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};jm.Parser=Wc});var Km=C(us=>{"use strict";var Fm=Ic(),xE=ts(),cs=ss(),EE=Cl(),AE=U(),TE=Kc(),Um=Hc();function qm(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new TE.LineCounter||null,prettyErrors:e}}function PE(n,e={}){let{lineCounter:t,prettyErrors:r}=qm(e),s=new Um.Parser(t?.addNewLine),i=new Fm.Composer(e),o=Array.from(i.compose(s.parse(n)));if(r&&t)for(let a of o)a.errors.forEach(cs.prettifyError(n,t)),a.warnings.forEach(cs.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Jm(n,e={}){let{lineCounter:t,prettyErrors:r}=qm(e),s=new Um.Parser(t?.addNewLine),i=new Fm.Composer(e),o=null;for(let a of i.compose(s.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new cs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(o.errors.forEach(cs.prettifyError(n,t)),o.warnings.forEach(cs.prettifyError(n,t))),o}function OE(n,e,t){let r;typeof e=="function"?r=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Jm(n,t);if(!s)return null;if(s.warnings.forEach(i=>EE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},t))}function _E(n,e,t){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(n===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return AE.isDocument(n)&&!r?n.toString(t):new xE.Document(n,r,t).toString(t)}us.parse=OE;us.parseAllDocuments=PE;us.parseDocument=Jm;us.stringify=_E});var Hm=C(
|
|
162
|
+
`,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=ao(e),r=Un(t);return r.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=ao(e),r=Un(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:r,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(r=>r.type==="newline"||r.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};jm.Parser=Wc});var Km=C(us=>{"use strict";var Fm=Ic(),xE=ts(),cs=ss(),EE=Cl(),AE=U(),TE=Kc(),Um=Hc();function qm(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new TE.LineCounter||null,prettyErrors:e}}function PE(n,e={}){let{lineCounter:t,prettyErrors:r}=qm(e),s=new Um.Parser(t?.addNewLine),i=new Fm.Composer(e),o=Array.from(i.compose(s.parse(n)));if(r&&t)for(let a of o)a.errors.forEach(cs.prettifyError(n,t)),a.warnings.forEach(cs.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Jm(n,e={}){let{lineCounter:t,prettyErrors:r}=qm(e),s=new Um.Parser(t?.addNewLine),i=new Fm.Composer(e),o=null;for(let a of i.compose(s.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new cs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return r&&t&&(o.errors.forEach(cs.prettifyError(n,t)),o.warnings.forEach(cs.prettifyError(n,t))),o}function OE(n,e,t){let r;typeof e=="function"?r=e:t===void 0&&e&&typeof e=="object"&&(t=e);let s=Jm(n,t);if(!s)return null;if(s.warnings.forEach(i=>EE.warn(s.options.logLevel,i)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:r},t))}function _E(n,e,t){let r=null;if(typeof e=="function"||Array.isArray(e)?r=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let s=Math.round(t);t=s<1?void 0:s>8?{indent:8}:{indent:s}}if(n===void 0){let{keepUndefined:s}=t??e??{};if(!s)return}return AE.isDocument(n)&&!r?n.toString(t):new xE.Document(n,r,t).toString(t)}us.parse=OE;us.parseAllDocuments=PE;us.parseDocument=Jm;us.stringify=_E});var Hm=C(W=>{"use strict";var CE=Ic(),RE=ts(),IE=fc(),Yc=ss(),NE=Dr(),Rt=U(),$E=Tt(),LE=re(),ME=Ot(),BE=_t(),DE=io(),jE=qc(),FE=Kc(),UE=Hc(),lo=Km(),Wm=$r();W.Composer=CE.Composer;W.Document=RE.Document;W.Schema=IE.Schema;W.YAMLError=Yc.YAMLError;W.YAMLParseError=Yc.YAMLParseError;W.YAMLWarning=Yc.YAMLWarning;W.Alias=NE.Alias;W.isAlias=Rt.isAlias;W.isCollection=Rt.isCollection;W.isDocument=Rt.isDocument;W.isMap=Rt.isMap;W.isNode=Rt.isNode;W.isPair=Rt.isPair;W.isScalar=Rt.isScalar;W.isSeq=Rt.isSeq;W.Pair=$E.Pair;W.Scalar=LE.Scalar;W.YAMLMap=ME.YAMLMap;W.YAMLSeq=BE.YAMLSeq;W.CST=DE;W.Lexer=jE.Lexer;W.LineCounter=FE.LineCounter;W.Parser=UE.Parser;W.parse=lo.parse;W.parseAllDocuments=lo.parseAllDocuments;W.parseDocument=lo.parseDocument;W.stringify=lo.stringify;W.visit=Wm.visit;W.visitAsync=Wm.visitAsync});function JE(n){try{return JSON.parse(n.trim()),!0}catch{return!1}}function KE(n){let e=n.trim();if(!e.startsWith("<"))return!1;let t=e.match(qE);return t?Nr(e,t[1])!==null:!1}function WE(n){let e=n.trim();if(!e.match(/^(---|#|\w+:|-)/)||"[{<".includes(e[0]))return!1;try{let t=Ym.parse(e);return t!==null&&typeof t=="object"}catch{return!1}}function Vm(n){return JE(n)||KE(n)||WE(n)}var Ym,qE,Vc=v(()=>{sp();Ym=zv(Hm(),1),qE=/<([a-zA-Z_][\w.-]*)/});function HE(n){if(!n?.trim())return[];let e=n.replace(/\r\n/g,`
|
|
163
163
|
`),t=e.trim();if(Vm(t))return[{text:t,startLine:1,endLine:e.split(`
|
|
164
164
|
`).length}];let r=e.split(`
|
|
165
165
|
`),s=[],i=0,o=-1,a=0,l=()=>{if(o>=i){let c=r.slice(i,o+1).join(`
|
|
@@ -302,7 +302,7 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
|
|
|
302
302
|
`),l=i.filter(u=>u.type==="tool_use").map(u=>({id:u.id??"",name:u.name??"",input:u.input??{}}));if(o||a||l.length){let u=Date.parse(e.timestamp??""),f=!isNaN(u)&&u>=t;r.push({type:"assistant",text:o,thinking:a,tools:l,live:f})}let c=e.message?.usage??e.usage,d=c&&{in:c.input_tokens??0,out:c.output_tokens??0,cached:c.cache_read_input_tokens??0,cacheCreate:c.cache_creation_input_tokens??0};return{events:r,usage:d,model:e.message?.model}}return{events:r}}chainWorking(e){let t;for(let o of e)(o.type==="user"||o.type==="assistant")&&(t=o);if(!t)return!1;if(t.type==="user"){try{let o=t.message?.content,a=typeof o=="string"?o:Array.isArray(o)?o.filter(c=>c&&c.type==="text").map(c=>c.text??"").join(""):"";if(!(Array.isArray(o)&&o.some(c=>c&&c.type==="tool_result"))&&a.trim()&&Nt(a)==="")return!1}catch{}return!0}let s=(Array.isArray(t.message?.content)?t.message.content:[]).filter(o=>o.type==="tool_use").map(o=>o.id);if(s.length===0)return!1;let i=new Set;for(let o of e){let a=o.message?.content;if(Array.isArray(a))for(let l of a)l.type==="tool_result"&&l.tool_use_id&&i.add(l.tool_use_id)}return s.some(o=>o&&!i.has(o))}sessionAlive(e){return SA(e)}readPreview(e){return vA(e)}searchText(e){if(!e||ps(e)||e.type!=="user"&&e.type!=="assistant")return"";let t=e.message?.content,r="";if(typeof t=="string")r=Nt(t);else if(Array.isArray(t)){let s=t;r=e.type==="user"?s.map(ru).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 kA,readdirSync as xA,openSync as EA,readSync as AA,closeSync as TA,existsSync as PA}from"fs";import{basename as OA,join as ou,resolve as _A}from"path";import{homedir as bg}from"os";function RA(n){let e=n.trimStart();return CA.some(t=>e.startsWith(t))}function ms(n,e){return Array.isArray(n)?n.map(t=>typeof t?.text=="string"?e&&RA(t.text)?"":Ae(t.text):t?.type==="input_image"&&typeof t.image_url=="string"&&t.image_url.startsWith("data:")?``:"").filter(Boolean).join(`
|
|
303
303
|
`):""}function IA(n){return typeof n=="string"?Ae(n):ms(n,!1)}function NA(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 $A(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 vg(n,e){let t;try{t=EA(n,"r")}catch{return}try{let r=Buffer.alloc(e),s=AA(t,r,0,e,0);return{text:r.subarray(0,s).toString("utf8"),bytes:s}}finally{TA(t)}}function LA(n){let t=vg(n,65536);if(t===void 0)return;let r=t.text.indexOf(`
|
|
304
304
|
`);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 CA,wg,Wn,au=v(()=>{"use strict";fs();mo();CA=["<permissions instructions>","<apps_instructions>","<plugins_instructions>","<skills_instructions>","<recommended_plugins>","<environment_context>","<user_instructions>"];wg=n=>{let e=_A(n);return process.platform==="win32"?e.toLowerCase():e},Wn=class extends It{constructor(t=ou(bg(),".codex","sessions")){super();this.root=t}displayName="Codex Mirror";#e=0;#s;#t=new Map;detectsSelf(){return!!process.env.CODEX_THREAD_ID}detectsInstalled(){return PA(ou(bg(),".codex"))}sessionsDir(t){return this.root}listSessionFiles(t){let r=wg(t),s=[];for(let i of this.#r()){let o;try{let l=kA(i);if(!l.isFile())continue;o=l.mtimeMs}catch{continue}let a=this.#t.get(i);if(a===void 0){if(a=LA(i),a===void 0)continue;this.#t.set(i,a)}wg(a)===r&&s.push({sessionId:OA(i,".jsonl"),file:i,mtime:o})}return s}#r(){let t=[],r=s=>{try{return xA(s).map(i=>ou(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=ms(i.content,!0).trim();a&&s.push({type:"user",text:a})}else if(i.role==="assistant"){let a=ms(i.content,!1);a&&s.push({type:"assistant",text:a,thinking:"",tools:[],live:o()})}return{events:s}}if(i.type==="reasoning"){let a=ms(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"?NA(i.input):$A(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=IA(i.output);return s.push({type:"tool_result",id:i.call_id??"",content:a,isError:!1,digest:qe(a)}),{events:s}}return{events:s}}if(t.type==="event_msg"){if(i.type==="token_count"){let a=i.info?.last_token_usage;if(!a)return{events:s};let l={in:Math.max(0,(a.input_tokens??0)-(a.cached_input_tokens??0)),out:a.output_tokens??0,cached:a.cached_input_tokens??0,cacheCreate:a.cache_write_input_tokens??0};return{events:s,usage:l}}return{events:s}}return t.type==="turn_context"?{events:s,model:i.model}:{events:s}}chainWorking(t){let r=!1;for(let s of t){if(s.type!=="event_msg")continue;let i=s.payload?.type;i==="task_started"?r=!0:(i==="task_complete"||i==="turn_aborted")&&(r=!1)}return r}sessionAlive(){}readPreview(t){for(let r of(vg(t,256*1024)?.text??"").split(`
|
|
305
|
-
`))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"?"":ms(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as MA}from"fs";import{createHash as BA}from"crypto";import{join as bo,resolve as DA}from"path";import{homedir as jA}from"os";function $t(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?bo(n,".."):bo(jA(),".typebulb")}function lt(){Sg||(Sg=!0,console.error(`${$t()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function ct(){return process.env.TYPEBULB_SERVERS_DIR||bo($t(),"servers")}function kg(n){let e=se(n),t=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return bo($t(),"canvas",`${t}-${gs(n)}.png`)}function gs(n){return BA("sha1").update(se(n)).digest("hex").slice(0,8)}function se(n){let e=DA(n),t=e;try{t=MA.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function xg(n,e){let t=se(n),r=se(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Sg,et=v(()=>{"use strict";Sg=!1});import*as Tg from"net";import{mkdir as FA,readFile as UA,writeFile as Pg}from"fs/promises";import{existsSync as qA}from"fs";import{join as Og}from"path";function Rg(){return Og($t(),"blocks")}function lu(n){return Og(Rg(),`${n}.json`)}function vo(n){return new Promise(e=>{let t=Tg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function HA(n){for(let e=n;e<65535;e++)if(await vo(e))return e;throw new Error(`No free port found above ${n}`)}async function cu(n){let{listBulbServers:e}=await Promise.resolve().then(()=>(Re(),Ig)),t=(await e()).find(s=>s.port===n),r=t?` (pid ${t.pid}, ${t.agent?`agent:${t.agent}`:t.file})`:"";console.error(`port ${n} in use${r}`),process.exit(1)}async function So(n){try{let e=JSON.parse(await UA(lu(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function ko(n,e){try{return await Pg(lu(n),JSON.stringify(e,null,2)),!0}catch{return lt(),!1}}async function YA(n){let e=se(n);try{await FA(Rg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Cg;o++)t.push(_g+o*sn);let r=await Promise.all(t.map(async o=>({base:o,block:await So(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 Pg(lu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await So(o))?.cwd===e)return o;l.code!=="EEXIST"&<();continue}if(!qA(a.cwd))return await ko(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Eg(o.block)-Eg(a.block))[0];if(i)return await ko(i.base,s)?i.base:void 0}function Eg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function VA(n,e){let t=await So(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Ag(t),a=o.has(0)?KA:0;for(;a>wo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await ko(n,t),a}let r=se(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Ag(t);for(s=wo;s<sn&&i.has(s);)s++;if(s>=sn){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:wo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await ko(n,t),s}function Ag(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function Hn(n,e){let t=await YA(e);return t===void 0?void 0:t+await VA(t,n)}async function on(n){let e=se(n);for(let t=0;t<Cg;t++){let r=await So(_g+t*sn);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function xo(n){if(n.explicit!==void 0)return await vo(n.explicit)||await cu(n.explicit),n.target.kind==="bulb"&&await Hn(n.target,n.cwd),{port:n.explicit};let e=await Hn(n.target,n.cwd);if(e!==void 0){let r=e-e%sn,s=Date.now()+WA;do{if(await vo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=wo;i<sn;i++){let o=r+i;if(o!==e&&await vo(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await HA(JA),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var _g,sn,Cg,JA,wo,KA,WA,an=v(()=>{"use strict";et();_g=20100,sn=100,Cg=19,JA=23e3,wo=1,KA=sn-1,WA=3e3});var Ie,Eo=v(()=>{"use strict";Ie="0.58.
|
|
305
|
+
`))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"?"":ms(t.payload.content,r==="user").replace(/\s+/g," ").trim()}}});import{realpathSync as MA}from"fs";import{createHash as BA}from"crypto";import{join as bo,resolve as DA}from"path";import{homedir as jA}from"os";function $t(){let n=process.env.TYPEBULB_SERVERS_DIR;return n?bo(n,".."):bo(jA(),".typebulb")}function lt(){Sg||(Sg=!0,console.error(`${$t()} not writable \u2014 continuing stateless: ports won't stick, caches stay cold, and typebulb logs/wait/send/stop may not see this run`))}function ct(){return process.env.TYPEBULB_SERVERS_DIR||bo($t(),"servers")}function kg(n){let e=se(n),t=e.slice(e.lastIndexOf("/")+1).replace(/\.bulb\.md$/,"");return bo($t(),"canvas",`${t}-${gs(n)}.png`)}function gs(n){return BA("sha1").update(se(n)).digest("hex").slice(0,8)}function se(n){let e=DA(n),t=e;try{t=MA.native(e)}catch{}return(process.platform==="win32"?t.toLowerCase():t).replace(/\\/g,"/")}function xg(n,e){let t=se(n),r=se(e);return t.startsWith(r.endsWith("/")?r:r+"/")?!t.includes("/node_modules/"):!1}var Sg,et=v(()=>{"use strict";Sg=!1});import*as Tg from"net";import{mkdir as FA,readFile as UA,writeFile as Pg}from"fs/promises";import{existsSync as qA}from"fs";import{join as Og}from"path";function Rg(){return Og($t(),"blocks")}function lu(n){return Og(Rg(),`${n}.json`)}function vo(n){return new Promise(e=>{let t=Tg.createServer();t.once("error",()=>e(!1)),t.listen(n,"127.0.0.1",()=>t.close(()=>e(!0)))})}async function HA(n){for(let e=n;e<65535;e++)if(await vo(e))return e;throw new Error(`No free port found above ${n}`)}async function cu(n){let{listBulbServers:e}=await Promise.resolve().then(()=>(Re(),Ig)),t=(await e()).find(s=>s.port===n),r=t?` (pid ${t.pid}, ${t.agent?`agent:${t.agent}`:t.file})`:"";console.error(`port ${n} in use${r}`),process.exit(1)}async function So(n){try{let e=JSON.parse(await UA(lu(n),"utf8"));return e&&typeof e.cwd=="string"?{cwd:e.cwd,slots:e.slots??{},mirrors:e.mirrors??{}}:void 0}catch{return}}async function ko(n,e){try{return await Pg(lu(n),JSON.stringify(e,null,2)),!0}catch{return lt(),!1}}async function YA(n){let e=se(n);try{await FA(Rg(),{recursive:!0})}catch{return}let t=[];for(let o=0;o<Cg;o++)t.push(_g+o*sn);let r=await Promise.all(t.map(async o=>({base:o,block:await So(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 Pg(lu(o),JSON.stringify(s,null,2),{flag:"wx"}),o}catch(l){if((await So(o))?.cwd===e)return o;l.code!=="EEXIST"&<();continue}if(!qA(a.cwd))return await ko(o,s)?o:void 0}let i=r.filter(o=>!!o.block).sort((o,a)=>Eg(o.block)-Eg(a.block))[0];if(i)return await ko(i.base,s)?i.base:void 0}function Eg(n){return Object.values(n.slots).reduce((e,t)=>Math.max(e,t.usedAt??0),0)}async function VA(n,e){let t=await So(n)??{cwd:"",slots:{},mirrors:{}};if(e.kind==="mirror"){let i=t.mirrors[e.agent];if(i!==void 0)return i;let o=Ag(t),a=o.has(0)?KA:0;for(;a>wo&&o.has(a);)a--;return t.mirrors[e.agent]=a,await ko(n,t),a}let r=se(e.file),s=t.slots[r]?.offset;if(s===void 0){let i=Ag(t);for(s=wo;s<sn&&i.has(s);)s++;if(s>=sn){let o=Object.entries(t.slots).sort((a,l)=>(a[1].usedAt??0)-(l[1].usedAt??0))[0];s=o?o[1].offset:wo,o&&delete t.slots[o[0]]}}return t.slots[r]={offset:s,usedAt:Date.now()},await ko(n,t),s}function Ag(n){return new Set([...Object.values(n.mirrors),...Object.values(n.slots).map(e=>e.offset)])}async function Hn(n,e){let t=await YA(e);return t===void 0?void 0:t+await VA(t,n)}async function on(n){let e=se(n);for(let t=0;t<Cg;t++){let r=await So(_g+t*sn);if(r?.cwd===e)return s=>r.slots[se(s)]?.usedAt??0}return()=>0}async function xo(n){if(n.explicit!==void 0)return await vo(n.explicit)||await cu(n.explicit),n.target.kind==="bulb"&&await Hn(n.target,n.cwd),{port:n.explicit};let e=await Hn(n.target,n.cwd);if(e!==void 0){let r=e-e%sn,s=Date.now()+WA;do{if(await vo(e))return{port:e};await new Promise(i=>setTimeout(i,150))}while(Date.now()<s);for(let i=wo;i<sn;i++){let o=r+i;if(o!==e&&await vo(o))return{port:o,note:`(slot ${e} was busy)`}}}return{port:await HA(JA),note:e===void 0?"(no port block available)":"(this project's block was full)"}}var _g,sn,Cg,JA,wo,KA,WA,an=v(()=>{"use strict";et();_g=20100,sn=100,Cg=19,JA=23e3,wo=1,KA=sn-1,WA=3e3});var Ie,Eo=v(()=>{"use strict";Ie="0.58.2"});var Ig={};oi(Ig,{agentViewerCommand:()=>qg,bulbServerCommand:()=>Ug,clearServerLog:()=>hu,findProjectViewer:()=>Po,isAlive:()=>Yn,isMirror:()=>me,isProjectBulb:()=>wu,isProjectMirror:()=>Gn,launchAgentViewer:()=>ku,launchBulbServer:()=>ws,listBulbServers:()=>X,probePageCount:()=>Su,readServerLog:()=>Ke,readWaitCursor:()=>To,recordDenial:()=>bu,registerServer:()=>yu,relayOpen:()=>vu,runMarker:()=>mu,serverLogPath:()=>zn,serversForBulb:()=>cn,sliceRunLog:()=>gu,startServerLog:()=>bs,stopBulbServer:()=>Vn,stopServer:()=>Lt,stopServersForBulb:()=>Oo,typebulbBinPath:()=>Xn,unregisterServer:()=>ln,writeWaitCursor:()=>ys});import{spawn as Ng}from"child_process";import{readdir as zA,readFile as Mg,writeFile as Bg,unlink as uu,mkdir as GA}from"fs/promises";import{mkdirSync as Dg,writeFileSync as Ao,appendFileSync as XA,readFileSync as du}from"fs";import*as Te from"path";import{fileURLToPath as QA}from"url";function fu(n){return Te.join(ct(),`${n}.json`)}function zn(n){return Te.join(ct(),`${n}.log`)}function pu(n){return Te.join(ct(),`${n}.wait.json`)}function jg(n){try{let e=JSON.parse(du(pu(n),"utf8"));return e.cursors&&typeof e.cursors=="object"?e.cursors:{}}catch{return{}}}function To(n,e=""){let t=jg(n)[e];return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function ys(n,e,t=""){try{Dg(ct(),{recursive:!0});let r=jg(n);r[t]=e,Ao(pu(n),JSON.stringify({cursors:r}))}catch{}}function bs(n){let e=zn(n);try{Dg(ct(),{recursive:!0}),Ao(e,"")}catch{return()=>{}}let t=process.stdout.write.bind(process.stdout),r=process.stderr.write.bind(process.stderr),s=0,i=!1,o=a=>{if(!i)try{let l=typeof a=="string"?Buffer.from(a,"utf8"):Buffer.from(a);if(XA(e,l),s+=l.length,s>2*$g){let c=du(e),d=c.subarray(Math.max(0,c.length-$g));Ao(e,d),s=d.length}}catch{i=!0}};return process.stdout.write=((a,...l)=>(o(a),t(a,...l))),process.stderr.write=((a,...l)=>(o(a),r(a,...l))),()=>{process.stdout.write=t,process.stderr.write=r}}function hu(n){try{Ao(zn(n),"")}catch{}}function Ke(n,e=0){try{let t=du(zn(n)),r=e>=0&&e<=t.length?e:0;return{text:t.subarray(r).toString("utf8"),offset:t.length}}catch{return{text:"",offset:0}}}function mu(n){return`\u2500\u2500 run ${n} \u2500\u2500 ${new Date().toTimeString().slice(0,8)}`}function eT(n){let e=ZA.exec(n);return e?Number(e[1]):void 0}function gu(n,e){let t=n.split(`
|
|
306
306
|
`),r=[];if(t.forEach((o,a)=>{let l=eT(o);l!==void 0&&r.push({id:l,idx:a})}),!r.length)return e==="latest"?n:"";let s=e==="latest"?r[r.length-1]:r.find(o=>o.id===e);if(!s)return"";let i=r.find(o=>o.idx>s.idx);return t.slice(s.idx,i?i.idx:t.length).join(`
|
|
307
307
|
`)}function Yn(n){try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}async function yu(n){try{await GA(ct(),{recursive:!0}),await Bg(fu(n.pid),JSON.stringify({version:Ie,...n}))}catch{lt()}}async function bu(n,e){let t=fu(n);try{let r=JSON.parse(await Mg(t,"utf8"));if(r.denied===e)return;r.denied=e,await Bg(t,JSON.stringify(r))}catch{}}async function ln(n){await uu(fu(n)).catch(()=>{}),await uu(zn(n)).catch(()=>{}),await uu(pu(n)).catch(()=>{})}function me(n){return n.agent!=null}function Gn(n,e){return me(n)&&n.cwd!=null&&se(n.cwd)===se(e)}function wu(n,e){return!me(n)&&xg(n.file,e)}async function X(n){let e;try{e=await zA(ct())}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 Mg(Te.join(ct(),s),"utf8"))}catch{await ln(i);return}o&&typeof o.pid=="number"&&Yn(o.pid)?t.push(o):await ln(i)})),(n?t.filter(s=>wu(s,n)):t).sort((s,i)=>s.startedAt-i.startedAt)}async function Po(n,e){return(await X()).find(t=>Gn(t,n)&&(e?t.agent===e:!0))}async function vu(n,e){let t=new URL(n).port,r=(await X()).filter(a=>String(a.port)!==t),s=r.filter(a=>Gn(a,e)),i=r.filter(a=>wu(a,e)),o=0;for(let a of[...s,...i])try{let l=await fetch(`${a.url}/__open`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n}),signal:AbortSignal.timeout(2e3)});if(!l.ok)continue;let{opened:c,pages:d}=await l.json();if(c)return{where:"editor",via:a.agent?"the agent mirror":`${Te.basename(a.file)}'s page`};me(a)&&(o+=d??0)}catch{}return o>0?{where:"external"}:void 0}async function Vn(n){try{process.kill(n,"SIGTERM")}catch{}await ln(n)}async function Su(n){try{let e=await fetch(`${n.url}/__pages`,{signal:AbortSignal.timeout(tT)});if(!e.ok)return;let{pages:t}=await e.json();return typeof t=="number"?t:void 0}catch{return}}async function Lt(n,e=me(n)?"keep":"close"){try{let t=await fetch(`${n.url}/__stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({pages:e}),signal:AbortSignal.timeout(Lg)});if(!t.ok)throw new Error(`/__stop ${t.status}`);let{closed:r=0,stuck:s=0}=await t.json(),i=Date.now()+Lg;for(;Yn(n.pid)&&Date.now()<i;)await Fg(100);return Yn(n.pid)?(await Vn(n.pid),"killed"):(await ln(n.pid),{closed:r,stuck:s})}catch{return await Vn(n.pid),"killed"}}function cn(n,e){let t=se(e);return n.filter(r=>!me(r)&&r.pid!==process.pid&&se(r.file)===t)}async function Oo(n,e){let t=cn(await X(),n);for(let r of t)await Lt(r,e!==void 0&&r.port===e?"keep":"close");return t}function nT(n,e,t){(process.platform==="win32"?Ng("cmd",["/c","start","","/b",n,...e],{cwd:t,stdio:"ignore",windowsHide:!0}):Ng(n,e,{cwd:t,detached:!0,stdio:"ignore"})).unref()}function Xn(){return Te.join(Te.dirname(QA(import.meta.url)),"index.js")}function Ug(n,e={}){return{command:process.execPath,args:[Xn(),...e.trust?["--trust"]:[],...e.batch?["--batch",e.batch]:[],...e.mode?["--mode",e.mode]:[],n,...e.open===!1?["--no-open"]:[]]}}function qg(n){return{command:process.execPath,args:[Xn(),`agent:${n}`,"--no-open"]}}async function Jg(n,e,t,r){let s=await n();if(s)return s;nT(e.command,e.args,t);let i=Date.now()+2e4;for(;Date.now()<i;){await Fg(150);let o=await n();if(o)return o}throw new Error(`Launched ${r} but it did not register within 20s.`)}async function ws(n,e={}){let t=e.cwd??process.cwd(),r=Te.resolve(t,n),s=await Hn({kind:"bulb",file:r},t),[i]=await Oo(r,s),o={...e,batch:e.batch??i?.batch,mode:e.mode??i?.mode};return Jg(async()=>cn(await X(),r)[0],Ug(n,o),t,Te.basename(n))}async function ku(n,e=process.cwd()){return Jg(()=>Po(e,n),qg(n),e,`the ${n} mirror`)}var $g,ZA,Lg,tT,Fg,Re=v(()=>{"use strict";et();an();Eo();$g=1e6;ZA=/^── run (\d+) ── /;Lg=6e3,tT=500;Fg=n=>new Promise(e=>setTimeout(e,n))});function Qn(n){return{...Uf(n),server:n.files.get("server.ts")??""}}function _o(n){return!!n.server&&!n.code}var vs=v(()=>{"use strict";ee();ee()});function Co(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 xu(n){return qn(Co(n)??"bulb")||"bulb"}var Eu=v(()=>{"use strict";ee()});import{transform as rT}from"sucrase";function Au(n,e={}){let t=e.serverOnly?["typescript"]:["typescript","jsx"];try{let{code:r}=rT(n,{transforms:t,jsxRuntime:"automatic",jsxImportSource:e.jsxImportSource||"react",production:!0});return{code:r}}catch(r){return{code:"",error:String(r)}}}var Kg=v(()=>{});function Tu(n){let e=n.split(""),t=(i,o)=>{for(let a=i;a<o&&a<e.length;a++)e[a]!==`
|
|
308
308
|
`&&(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]!==`
|
|
@@ -483,7 +483,7 @@ const something = require('module-name') // NOT SUPPORTED!
|
|
|
483
483
|
**Fix:** Replace all \`require()\` calls with ES6 \`import\` statements at the top of the file.`}var un,dn,iT,oT,Ro=v(()=>{Hg();un=["client"],dn=["client","server"],iT=[{type:"DYNAMIC_IMPORT",pattern:/\bimport\s*\(\s*['"`]/,targets:un},{type:"COMMONJS_REQUIRE",pattern:/\brequire\s*\(\s*['"`]/,targets:dn},{type:"JS_EXTENSION_IMPORT",pattern:/from\s+['"][^'"]*\/[^'"]*\.js['"]/,targets:un},{type:"URL_IMPORT",pattern:/from\s+['"]https?:\/\//,targets:un},{type:"VERSION_SPECIFIER_IMPORT",pattern:/from\s+['"][^'"]*@[\d^~]/,targets:un},{type:"REDUNDANT_TB_DECLARATION",pattern:/declare\s+(const|var|let)\s+tb\b/,targets:dn},{type:"CONST_ENUM",pattern:/\bconst\s+enum\b/,targets:dn},{type:"NAMESPACE_DECLARATION",pattern:/\bnamespace\s+\w+/,targets:dn},{type:"COMMONJS_EXPORT_EQUALS",pattern:/\bexport\s*=/,targets:dn},{type:"COMMONJS_IMPORT_EQUALS",pattern:/\bimport\s+\w+\s*=/,targets:dn},{type:"MODULE_DECLARATION",pattern:/\bmodule\s+\w+\s*\{/,targets:dn},{type:"CSS_FILE_IMPORT",pattern:/(?:from|import)\s+['"][^'"]*\.css['"]/,targets:un},{type:"NAVIGATION",pattern:/window\.(location\.(reload|assign|replace)\s*\(|open\s*\()/,targets:un},{type:"NAVIGATION",pattern:/window\.location(\.href)?\s*=[^=]/,targets:un}],oT=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});function dT(n){return n.map(e=>`${e.type} (line ${e.lineNumber}): ${e.message.split(`
|
|
484
484
|
`)[0]}`).join(`
|
|
485
485
|
`)}function zg(n,e){let t=Ss(n,{target:"client",dependencies:e}).filter(r=>r.type==="UNDECLARED_IMPORT");if(t.length)throw new Error(`Lint failed:
|
|
486
|
-
${dT(t)}`)}var Gg=v(()=>{"use strict";Ro()});var Mt,ks,Pu,xs=v(()=>{Mt="https://esm.sh",ks="https://cdn.jsdelivr.net/npm/",Pu="https://data.jsdelivr.com/v1/package/npm/"});function Xg(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D,Zn,Qg,Es=v(()=>{xs();D=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=Zn(t??s.version),this.subpath=Zn(r??s.subpath)}static parse(e){let t=Xg(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Qg(t[1]??""),a=Zn(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Qg(t[0]),o=Zn(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(Mt).host,s=new URL(ks).host;if(t.host===r){let i=Xg(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:Zn(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},Zn=n=>n&&n.length?n:void 0,Qg=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),Zn(n.slice(e+1))]}});async function ke(n){try{return await n()}catch{return}}var Io=v(()=>{});function fn(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ou(n){return n.startsWith("./")?n:`./${n}`}var As,_u=v(()=>{Es();Io();xs();As=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`${ks}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(fn(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(",")),`${Mt}/${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),`${Mt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await ke(()=>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 ke(()=>this.http.getJson(`${Pu}${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:d,peerDependencies:u,peerDependenciesMeta:f}=r;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new D(`${e}@${t}`)),i=await ke(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),l=o(i.peerDependencies),c=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,l,c),{name:e,version:t,dependencies:a,peerDependencies:l,peerDependenciesMeta:c}}}});var Zg,Ts,Cu,fT,Ps,No=v(()=>{Zg=n=>n.startsWith("@types/"),Ts=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!Zg(e)),Cu=n=>Object.keys(n?.dependencies||{}).filter(e=>!Zg(e)),fT=n=>Ts(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),Ps=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 fT(i.meta))!r.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),l=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:l})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Ts(i.meta))),r=new Map;for(let i of e)for(let o of Cu(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:Ts(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var Os,Ru=v(()=>{Es();Io();Os=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await ke(()=>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 ke(()=>this.cdn.fetchVersionsIndex(e));if(o?.versions?.length){let a=this.semver.selectBestVersion(o.versions,{range:t,distTags:o.distTags});if(a){let l=await i(a);if(l)return l}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 l=await ke(()=>this.cdn.fetchVersionsIndex(e));if(l?.versions?.length){let c=await i(this.semver.selectBestVersion(l.versions,{range:t,distTags:l.distTags}));if(c)return c}}}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 ke(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as pT,parse as hT}from"es-module-lexer";var er,Iu=v(()=>{Es();xs();No();er=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 pT;let[s]=hT(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:l,autoAddedPeers:c}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...c.map(u=>u.name)],a,l);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let r=t[e],s=await this.version.resolveExactForRoot(e,r);if(!s)throw new Error(`Cannot resolve ${r?`${e}@${r}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,r){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let m=s.get(D.rootOf(p));return new D(p).withVersion(m.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),l=[],c=new Set,d=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let m=D.rootOf(p),h=s.get(m),{isPeerRoot:y,hasPeers:E,isSharedDep:T}=r.get(m),_=a.has(m),x=p!==m,R=!(y||T)&&(_||!E),$=this.singletonDepsOf(h,o),A=x&&d.has(m);A&&u.add(m);let J=A?[...$,m]:$.length?$:void 0;l.push([p,this.cdn.buildEsmUrl(i(p),{bundle:R,external:J})]),c.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(c.has(p)||l.push([p,this.cdn.buildEsmUrl(i(p),{})]),l.push([`${p}/`,`${Mt}/${i(p)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Ts(e.meta),...Cu(e.meta)])].filter(r=>t.has(r))}};er.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as ey,satisfies as mT,maxSatisfying as ty,major as gT,valid as yT,validRange as bT}from"semver";var $o,pn,Nu=v(()=>{$o=class{cmp(e,t){return e===t?0:ey(e,t)?1:ey(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!mT(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=ty(e,r,{includePrerelease:!1});if(a)return a}return ty(e,r,{includePrerelease:!0})??void 0}majorOf(e){return gT(e)}isExactVersion(e){return yT(e)!==null}isRange(e){return bT(e)!==null}},pn=new $o});function wT(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var hn,ny=v(()=>{Io();hn=class{constructor(e){this.store=e}async isNegative(e){let t=await ke(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await ke(()=>this.store.get(e)))?.attempts||0)+1;await ke(()=>this.store.set(e,{until:Date.now()+wT(r),attempts:r}))}async clearNegative(e){await ke(()=>this.store.delete(e))}}});function ry(n,e){let t=new As(n,e),r=new Ps(t),s=new Os(n,t,pn);return{packageService:new er(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var ut=v(()=>{_u();No();Ru();Iu();Nu();Es();Nu();xs();_u();No();Ru();Iu();ny()});import*as $u from"fs/promises";import*as sy from"crypto";function We(n){return sy.createHash("sha1").update(n).digest("hex")}async function dt(n){try{return JSON.parse(await $u.readFile(n,"utf8"))}catch{return}}async function Lo(n){try{return await $u.readFile(n,"utf8")}catch{return}}var tr=v(()=>{"use strict"});import*as Dt from"fs/promises";import*as ft from"path";import*as oy from"os";function ne(){return Lu||(Lu=ST().catch(()=>lt())),Lu}function Bo(n,e){return ft.join(vT,We(n),e)}async function ST(){await Dt.mkdir(Bt,{recursive:!0});let n=ft.join(Bt,"version.json");if((await dt(n))?.version===iy)return;let t=await Dt.readdir(Bt).catch(()=>[]);await Promise.all(t.map(r=>Dt.rm(ft.join(Bt,r),{recursive:!0,force:!0}))),await Dt.writeFile(n,JSON.stringify({version:iy})+`
|
|
486
|
+
${dT(t)}`)}var Gg=v(()=>{"use strict";Ro()});var Mt,ks,Pu,xs=v(()=>{Mt="https://esm.sh",ks="https://cdn.jsdelivr.net/npm/",Pu="https://data.jsdelivr.com/v1/package/npm/"});function Xg(n){let e=(n||"").replace(/^\/+/,"").replace(/\/+$/,"");return e?e.split("/"):[]}var D,Zn,Qg,Es=v(()=>{xs();D=class n{constructor(e,t,r){let s=typeof e=="string"?n.parse(e):e;this.name=s.name,this.version=Zn(t??s.version),this.subpath=Zn(r??s.subpath)}static parse(e){let t=Xg(e||"");if(!t.length)return new n({name:""});if(t[0].startsWith("@")){let s=t[0],[i,o]=Qg(t[1]??""),a=Zn(t.slice(2).join("/"));return new n({name:`${s}/${i}`,version:o,subpath:a})}else{let[s,i]=Qg(t[0]),o=Zn(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(Mt).host,s=new URL(ks).host;if(t.host===r){let i=Xg(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:Zn(e),subpath:this.subpath})}static isBare(e){return!e||e.startsWith(".")||e.startsWith("/")?!1:!/^[a-z][a-z0-9+.-]*:/i.test(e)}},Zn=n=>n&&n.length?n:void 0,Qg=n=>{let e=n.indexOf("@");return e<0?[n,void 0]:[n.slice(0,e),Zn(n.slice(e+1))]}});async function ke(n){try{return await n()}catch{return}}var Io=v(()=>{});function fn(n){let e=n||"";return e.startsWith("./")?e.slice(2):e.replace(/^\/+/,"")}function Ou(n){return n.startsWith("./")?n:`./${n}`}var As,_u=v(()=>{Es();Io();xs();As=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`${ks}${t.name}${t.version?`@${t.version}`:""}/`}file(e,t){return new URL(fn(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(",")),`${Mt}/${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),`${Mt}/${e}`]);return this.pinCache.set(e,{value:s,ts:t}),s}async tryResolveFromUrls(e){for(let t of e){let r=await ke(()=>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 ke(()=>this.http.getJson(`${Pu}${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:d,peerDependencies:u,peerDependenciesMeta:f}=r;return{name:e,version:t,dependencies:d,peerDependencies:u,peerDependenciesMeta:f}}let s=this.packageJson(new D(`${e}@${t}`)),i=await ke(()=>this.http.getJson(s));if(!i)return;let o=d=>d&&Object.keys(d).length?d:void 0,a=o(i.dependencies),l=o(i.peerDependencies),c=o(i.peerDependenciesMeta);return await this.cache.setMeta(e,t,a,l,c),{name:e,version:t,dependencies:a,peerDependencies:l,peerDependenciesMeta:c}}}});var Zg,Ts,Cu,fT,Ps,No=v(()=>{Zg=n=>n.startsWith("@types/"),Ts=n=>Object.keys(n?.peerDependencies||{}).filter(e=>!Zg(e)),Cu=n=>Object.keys(n?.dependencies||{}).filter(e=>!Zg(e)),fT=n=>Ts(n).filter(e=>!n?.peerDependenciesMeta?.[e]?.optional),Ps=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 fT(i.meta))!r.has(o)&&!s.some(a=>a.name===o)&&s.push({name:o,requiredBy:i.name});for(let{name:i,requiredBy:o}of s)try{let a=await t(i),l=await this.cdn.fetchPackageMeta(i,a);r.set(i,{name:i,version:a,meta:l})}catch(a){console.warn(`[typebulb] Failed to resolve peer "${i}" for "${o}":`,a)}return{allRoots:[...r.values()],autoAddedPeers:s.filter(i=>r.has(i.name))}}computeFlags(e){let t=new Set(e.flatMap(i=>Ts(i.meta))),r=new Map;for(let i of e)for(let o of Cu(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:Ts(i.meta).length>0,isSharedDep:s.has(i.name)}]))}}});var Os,Ru=v(()=>{Es();Io();Os=class{constructor(e,t,r){this.cache=e,this.cdn=t,this.semver=r}async learnExactVersion(e){let t=await ke(()=>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 ke(()=>this.cdn.fetchVersionsIndex(e));if(o?.versions?.length){let a=this.semver.selectBestVersion(o.versions,{range:t,distTags:o.distTags});if(a){let l=await i(a);if(l)return l}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 l=await ke(()=>this.cdn.fetchVersionsIndex(e));if(l?.versions?.length){let c=await i(this.semver.selectBestVersion(l.versions,{range:t,distTags:l.distTags}));if(c)return c}}}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 ke(()=>this.resolveExactForRoot(s,i)):void 0;return{effectivePackage:o?r.withVersion(o).format():e,root:s,range:i,pinned:o}}}});import{init as pT,parse as hT}from"es-module-lexer";var er,Iu=v(()=>{Es();xs();No();er=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 pT;let[s]=hT(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:l,autoAddedPeers:c}=await this.peer.resolve(o,u=>this.resolveVersion(u,t)),d=this.buildEntries([...s,...c.map(u=>u.name)],a,l);return{importMap:{imports:Object.fromEntries(d)},prefetchUrls:d.map(([,u])=>u)}}async resolveVersion(e,t){let r=t[e],s=await this.version.resolveExactForRoot(e,r);if(!s)throw new Error(`Cannot resolve ${r?`${e}@${r}`:e}: no matching version is published (the package or version may not exist, or the registry was unreachable).`);return s}buildEntries(e,t,r){let s=new Map(t.map(p=>[p.name,p])),i=p=>{let m=s.get(D.rootOf(p));return new D(p).withVersion(m.version).format()},o=new Set([...r.entries()].filter(([,p])=>p.isPeerRoot||p.isSharedDep).map(([p])=>p)),a=new Set(e.filter(p=>p!==D.rootOf(p)).map(D.rootOf)),l=[],c=new Set,d=new Set(e.filter(p=>p===D.rootOf(p))),u=new Set;for(let p of e){let m=D.rootOf(p),h=s.get(m),{isPeerRoot:y,hasPeers:E,isSharedDep:T}=r.get(m),_=a.has(m),x=p!==m,R=!(y||T)&&(_||!E),$=this.singletonDepsOf(h,o),A=x&&d.has(m);A&&u.add(m);let K=A?[...$,m]:$.length?$:void 0;l.push([p,this.cdn.buildEsmUrl(i(p),{bundle:R,external:K})]),c.add(p)}let f=new Set([...o,...u]);for(let p of f)s.has(p)&&(c.has(p)||l.push([p,this.cdn.buildEsmUrl(i(p),{})]),l.push([`${p}/`,`${Mt}/${i(p)}/`]));return l}singletonDepsOf(e,t){return[...new Set([...Ts(e.meta),...Cu(e.meta)])].filter(r=>t.has(r))}};er.importPatterns=[/\bimport\s+(?:[^'";]*?from\s*)?['"]([^'"]+)['"]/g,/\bexport\s+[^'";]*?from\s*['"]([^'"]+)['"]/g]});import{gt as ey,satisfies as mT,maxSatisfying as ty,major as gT,valid as yT,validRange as bT}from"semver";var $o,pn,Nu=v(()=>{$o=class{cmp(e,t){return e===t?0:ey(e,t)?1:ey(t,e)?-1:0}satisfies(e,t){return!e||!e.trim()?!0:!!mT(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=ty(e,r,{includePrerelease:!1});if(a)return a}return ty(e,r,{includePrerelease:!0})??void 0}majorOf(e){return gT(e)}isExactVersion(e){return yT(e)!==null}isRange(e){return bT(e)!==null}},pn=new $o});function wT(n){return Math.min(9e5*Math.pow(2,Math.max(0,n-1)),864e5)}var hn,ny=v(()=>{Io();hn=class{constructor(e){this.store=e}async isNegative(e){let t=await ke(()=>this.store.get(e));return!!t&&t.until>Date.now()}async recordNegative(e){let r=((await ke(()=>this.store.get(e)))?.attempts||0)+1;await ke(()=>this.store.set(e,{until:Date.now()+wT(r),attempts:r}))}async clearNegative(e){await ke(()=>this.store.delete(e))}}});function ry(n,e){let t=new As(n,e),r=new Ps(t),s=new Os(n,t,pn);return{packageService:new er(s,t,r),versionResolver:s,cdnClient:t,peerResolver:r}}var ut=v(()=>{_u();No();Ru();Iu();Nu();Es();Nu();xs();_u();No();Ru();Iu();ny()});import*as $u from"fs/promises";import*as sy from"crypto";function We(n){return sy.createHash("sha1").update(n).digest("hex")}async function dt(n){try{return JSON.parse(await $u.readFile(n,"utf8"))}catch{return}}async function Lo(n){try{return await $u.readFile(n,"utf8")}catch{return}}var tr=v(()=>{"use strict"});import*as Dt from"fs/promises";import*as ft from"path";import*as oy from"os";function ne(){return Lu||(Lu=ST().catch(()=>lt())),Lu}function Bo(n,e){return ft.join(vT,We(n),e)}async function ST(){await Dt.mkdir(Bt,{recursive:!0});let n=ft.join(Bt,"version.json");if((await dt(n))?.version===iy)return;let t=await Dt.readdir(Bt).catch(()=>[]);await Promise.all(t.map(r=>Dt.rm(ft.join(Bt,r),{recursive:!0,force:!0}))),await Dt.writeFile(n,JSON.stringify({version:iy})+`
|
|
487
487
|
`,"utf8")}var iy,Bt,_s,Cs,Mo,vT,Lu,nr=v(()=>{"use strict";tr();et();iy=1,Bt=ft.join(oy.homedir(),".typebulb","cache"),_s=ft.join(Bt,"packages"),Cs=ft.join(Bt,"proxy"),Mo=ft.join(Bt,"dts"),vT=ft.join(Bt,"emit")});import*as jt from"fs/promises";import*as ay from"path";async function Ne(n,e){let t=`${n}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;try{await jt.mkdir(ay.dirname(n),{recursive:!0}),await jt.writeFile(t,e,"utf8")}catch{lt();return}await jt.rename(t,n).catch(async()=>{await jt.rm(t,{force:!0}).catch(()=>{})})}var Rs=v(()=>{"use strict";et()});var rr,Mu=v(()=>{"use strict";Rs();tr();rr=class{constructor(e){this.filePath=e}mem;loadPromise;load(){return this.mem?Promise.resolve(this.mem):(this.loadPromise||(this.loadPromise=dt(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 Ne(this.filePath,JSON.stringify(Object.fromEntries(e)))}}});import*as uy from"fs/promises";import*as He from"path";function cy(n,e){return He.join(kT,Do(n),encodeURIComponent(e)+".json")}function Do(n){return n.replace(/\//g,"__")}var Bu,ly,kT,xT,jo,dy=v(()=>{"use strict";ut();nr();Rs();Mu();tr();Bu=He.join(_s,"indexes"),ly=He.join(_s,"pinned"),kT=He.join(_s,"meta"),xT=He.join(_s,"negative.json"),jo=class{pinnedMem=new Map;indexMem=new Map;metaMem=new Map;negativeCache=new hn(new rr(xT));async getPinnedExact(e,t){let r=`${e}@${t}`;if(this.pinnedMem.has(r))return this.pinnedMem.get(r);await ne();let s=await Lo(He.join(ly,We(r)+".txt"));return this.pinnedMem.set(r,s),s}async setPinnedExact(e,t,r){let s=`${e}@${t}`;this.pinnedMem.set(s,r),await ne(),await Ne(He.join(ly,We(s)+".txt"),r)}async getIndex(e){if(this.indexMem.has(e))return this.indexMem.get(e);await ne();let t=await dt(He.join(Bu,Do(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 ne(),await Ne(He.join(Bu,Do(e)+".json"),JSON.stringify(s))}async invalidateVersionsCache(e){this.indexMem.delete(e),await uy.rm(He.join(Bu,Do(e)+".json"),{force:!0}).catch(()=>{})}async isNegative(e){return await ne(),this.negativeCache.isNegative(e)}async recordNegative(e){await ne(),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 ne();let s=await dt(cy(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 ne(),await Ne(cy(e,t),JSON.stringify(o))}}});var fy,py=v(()=>{"use strict";fy={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 ET,Fo,hy,my,$L,Du=v(()=>{"use strict";ut();dy();py();ET=new jo,{packageService:Fo,versionResolver:hy,cdnClient:my,peerResolver:$L}=ry(ET,fy)});function Uo(n){return n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function gy(){return` <script>
|
|
488
488
|
${cg}
|
|
489
489
|
(function () {
|
|
@@ -608,8 +608,8 @@ ${cg}
|
|
|
608
608
|
// tb.setData / tb.setInsight (TB-State.md), on the engine both hosts share. The globals and the
|
|
609
609
|
// transport are all this host owns: encoding round-trips to the server because the page carries
|
|
610
610
|
// no fflate on purpose, and the fragment write is the address bar the setters exist to fill.
|
|
611
|
-
// Resolves
|
|
612
|
-
//
|
|
611
|
+
// Resolves once that write has landed, and hands back nothing: the link is then tb.url() like
|
|
612
|
+
// any other. An inline bulb has no address bar, so its swap is page-local and never encodes.
|
|
613
613
|
window.__tbState.init({
|
|
614
614
|
applyData: (chunks) => { window.__TB_DATA__ = chunks; },
|
|
615
615
|
applyInsight: (json) => { window.__TB_INSIGHT__ = json; },
|
|
@@ -627,7 +627,6 @@ ${cg}
|
|
|
627
627
|
// earlier fragment, or the address bar keeps addressing a run the page is no longer
|
|
628
628
|
// showing \u2014 and a reload would silently revert to it.
|
|
629
629
|
history.replaceState(null, '', location.pathname + location.search + hash);
|
|
630
|
-
return hash ? location.href : undefined;
|
|
631
630
|
});
|
|
632
631
|
}
|
|
633
632
|
});
|
|
@@ -824,8 +823,8 @@ ${cg}
|
|
|
824
823
|
if (inferRunning) return Promise.reject(new Error('Inference already in progress'));
|
|
825
824
|
inferRunning = true;
|
|
826
825
|
// Data to preview: the explicit arg, else undefined \u2014 the modal then seeds from the SOURCE
|
|
827
|
-
// chunks
|
|
828
|
-
//
|
|
826
|
+
// chunks the page currently holds, else the SOURCE chunks from /__infer-info \u2014 the same
|
|
827
|
+
// precedence .com's modal seeds by (TB-Inference.md, "Data seed").
|
|
829
828
|
let data = opts.data;
|
|
830
829
|
if (data !== undefined && !Array.isArray(data)) data = [data];
|
|
831
830
|
return new Promise((resolve, reject) => {
|
|
@@ -2005,11 +2004,11 @@ Reply with the summary alone.
|
|
|
2005
2004
|
|
|
2006
2005
|
[snipped for brevity]
|
|
2007
2006
|
|
|
2008
|
-
`+n.slice(n.length-t)}});function LO(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 $b,Lb=v(()=>{"use strict";$b=(n,e)=>LO(n,{key:e,desc:!0})});import{existsSync as Mb,openSync as MO,readSync as BO,closeSync as DO,statSync as Sr,readdirSync as Bb,watchFile as jO,unwatchFile as Db,mkdirSync as FO,writeFileSync as UO,readFileSync as Aa,unlinkSync as qO,rmSync as JO}from"fs";import{stat as KO}from"fs/promises";import{dirname as WO,join as xn,resolve as jb}from"path";function zO(n){if(!Number.isInteger(n))return!0;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function kr(n){let e={cwd:G,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,r,s=0;function i(){if(e.file){for(let g of t)if(g.file===e.file)return g;return}return r}function o(g){let S={d:n.createDriver(e.cwd,g),file:g,id:`new:${++s}`,startedAt:Date.now()};return t.add(S),e.file||(r=S),S}function a(){let g=[...t].filter(w=>w.file);if(!g.length)return[];let S=new Map(n.listSessionFiles(e.cwd).map(w=>[w.file,w.sessionId]));return g.map(w=>{let O=S.get(w.file);return{rec:w,sessionId:O??w.id,pending:O===void 0}})}let l=()=>a().filter(g=>g.pending&&g.rec.prompt!==void 0);async function c(g){t.delete(g),r===g&&(r=void 0);try{await g.d.dispose()}catch(S){console.error("[composer] dispose:",V(S))}}function d(){let g=i(),S=new Set(l().map(w=>w.rec));for(let w of[...t])w!==g&&(S.has(w)||w.d.streaming||w.d.queue||w.d.error||c(w))}function u(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(r&&!e.file&&r.file){let g=n.listSessionFiles(e.cwd).find(S=>S.file===r.file);g&&A(g)}r&&!e.file&&r.prompt!==void 0&&e.sessionId!==r.id&&($(void 0,r.id),e.everAttached=!0)}let f=g=>xn(g,YO),p=(g,S)=>xn(f(g),`${S}.lock`);function m(g,S){try{let w=p(g,S);if(Date.now()-Sr(w).mtimeMs>=Fb)return!1;try{let O=parseInt(Aa(w,"utf8").trim(),10);if(O===process.pid||!zO(O))return!1}catch{}return!0}catch{return!1}}function h(g,S){if(S)try{FO(f(g),{recursive:!0}),UO(p(g,S),String(process.pid))}catch(w){console.error("[lock] claim failed:",V(w))}}function y(g){try{JO(xn(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function E(g){let S=f(g);if(!Mb(S))return;let w;try{w=Bb(S)}catch{return}let O=Date.now();for(let
|
|
2009
|
-
`))>=0;){let Y=g.partial.slice(0,
|
|
2010
|
-
`).filter(Boolean):await n.walkFiles?.(e.cwd)??[];return(await Promise.all(S.map(async O=>{try{return{f:O,m:(await KO(xn(e.cwd,O))).mtimeMs}}catch{return{f:O,m:0}}}))).sort((O,
|
|
2011
|
-
`)){if(!j.trim())continue;let B=n.parseEntry(j);if(!B)continue;let z=n.searchText(B);z&&O.push({text:z,lower:z.toLowerCase()})}return si.set(g,{mtime:S,turns:O}),O}async function jv(g){let S=g.toLowerCase(),w=[];for(let{sessionId:O,file:
|
|
2012
|
-
`)){if(!B.trim())continue;let z=n.parseEntry(B);if(z)for(let Y of n.apply(z,e.sessionStartMs).events)Y.type==="assistant"&&Y.text.trim()&&(
|
|
2007
|
+
`+n.slice(n.length-t)}});function LO(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 $b,Lb=v(()=>{"use strict";$b=(n,e)=>LO(n,{key:e,desc:!0})});import{existsSync as Mb,openSync as MO,readSync as BO,closeSync as DO,statSync as Sr,readdirSync as Bb,watchFile as jO,unwatchFile as Db,mkdirSync as FO,writeFileSync as UO,readFileSync as Aa,unlinkSync as qO,rmSync as JO}from"fs";import{stat as KO}from"fs/promises";import{dirname as WO,join as xn,resolve as jb}from"path";function zO(n){if(!Number.isInteger(n))return!0;try{return process.kill(n,0),!0}catch(e){return e.code==="EPERM"}}function kr(n){let e={cwd:G,sessionId:"",sessionStartMs:Date.now(),buffer:[],partial:"",offset:0,latest:{in:0,out:0,cached:0,cacheCreate:0},latestModel:null,everAttached:!1,entries:new Map},t=new Set,r,s=0;function i(){if(e.file){for(let g of t)if(g.file===e.file)return g;return}return r}function o(g){let S={d:n.createDriver(e.cwd,g),file:g,id:`new:${++s}`,startedAt:Date.now()};return t.add(S),e.file||(r=S),S}function a(){let g=[...t].filter(w=>w.file);if(!g.length)return[];let S=new Map(n.listSessionFiles(e.cwd).map(w=>[w.file,w.sessionId]));return g.map(w=>{let O=S.get(w.file);return{rec:w,sessionId:O??w.id,pending:O===void 0}})}let l=()=>a().filter(g=>g.pending&&g.rec.prompt!==void 0);async function c(g){t.delete(g),r===g&&(r=void 0);try{await g.d.dispose()}catch(S){console.error("[composer] dispose:",V(S))}}function d(){let g=i(),S=new Set(l().map(w=>w.rec));for(let w of[...t])w!==g&&(S.has(w)||w.d.streaming||w.d.queue||w.d.error||c(w))}function u(){for(let g of t)g.d.sessionFile&&g.file!==g.d.sessionFile&&(g.file=g.d.sessionFile);if(r&&!e.file&&r.file){let g=n.listSessionFiles(e.cwd).find(S=>S.file===r.file);g&&A(g)}r&&!e.file&&r.prompt!==void 0&&e.sessionId!==r.id&&($(void 0,r.id),e.everAttached=!0)}let f=g=>xn(g,YO),p=(g,S)=>xn(f(g),`${S}.lock`);function m(g,S){try{let w=p(g,S);if(Date.now()-Sr(w).mtimeMs>=Fb)return!1;try{let O=parseInt(Aa(w,"utf8").trim(),10);if(O===process.pid||!zO(O))return!1}catch{}return!0}catch{return!1}}function h(g,S){if(S)try{FO(f(g),{recursive:!0}),UO(p(g,S),String(process.pid))}catch(w){console.error("[lock] claim failed:",V(w))}}function y(g){try{JO(xn(g,".claude-bulb"),{recursive:!0,force:!0})}catch{}}function E(g){let S=f(g);if(!Mb(S))return;let w;try{w=Bb(S)}catch{return}let O=Date.now();for(let L of w){if(!L.endsWith(".lock"))continue;let j=xn(S,L);try{let B=Sr(j);O-B.mtimeMs>VO&&qO(j)}catch{}}}function T(g){try{return Sr(g),!1}catch(S){return S.code==="ENOENT"}}function _(){let g=e;if(g.file&&!T(g.file)){h(g.cwd,g.sessionId);return}let S=x(g);S&&A(S)}function x(g){if(!g.everAttached)return I(g.cwd)??R(g.cwd,()=>!0)}function I(g){let S=f(g);if(!Mb(S))return;let w;try{w=Bb(S)}catch{return}let O;for(let j of w)if(j.endsWith(".lock"))try{let B=Sr(xn(S,j));if(Date.now()-B.mtimeMs>=Fb||parseInt(Aa(xn(S,j),"utf8").trim(),10)!==process.pid)continue;(!O||B.mtimeMs>O.mtime)&&(O={sessionId:j.slice(0,-5),mtime:B.mtimeMs})}catch{}if(!O)return;let L=n.listSessionFiles(g).find(j=>j.sessionId===O.sessionId);if(!(!L||T(L.file)))return L}function R(g,S){return n.listSessionFiles(g).sort((w,O)=>O.mtime-w.mtime).find(w=>!m(g,w.sessionId)&&S(w))}function $(g,S){let w=e;if(w.file)try{Db(w.file)}catch{}w.file=g,w.sessionId=S,w.partial="",w.offset=0,w.latest={in:0,out:0,cached:0,cacheCreate:0},w.latestModel=null,w.entries=new Map,w.chainLastId=void 0,w.buffer.push({type:"cleared"}),w.buffer.push({type:"session",sessionId:S})}function A(g){let S=e;r=void 0,$(g.file,g.sessionId),S.everAttached=!0,h(S.cwd,g.sessionId),Q();try{Db(g.file)}catch{}jO(g.file,{interval:200},()=>Q())}function K(){$(void 0,"")}function Q(){let g=e;if(!g.file)return;let S;try{S=Sr(g.file).size}catch{return}if(S<=g.offset)return;let w;try{w=MO(g.file,"r")}catch{return}try{let Y=S-g.offset,Ee=Buffer.alloc(Y),ce=0;for(;ce<Y;){let Tf=BO(w,Ee,ce,Y-ce,g.offset+ce);if(!Tf)break;ce+=Tf}g.offset+=ce,g.partial+=Ee.subarray(0,ce).toString("utf8")}finally{DO(w)}let O,L;for(;(L=g.partial.indexOf(`
|
|
2008
|
+
`))>=0;){let Y=g.partial.slice(0,L);if(g.partial=g.partial.slice(L+1),!Y.trim())continue;let Ee=n.parseEntry(Y);if(!Ee)continue;let ce=n.idOf(Ee);ce&&(g.entries.set(ce,Ee),!n.isSidechain(Ee)&&n.isLeafType(Ee)&&(O=ce))}if(!O)return;let j=[],B=g.entries.get(O),z=!1;for(;B;){if(j.push(B),n.idOf(B)===g.chainLastId){z=!0;break}let Y=n.parentOf(B);B=Y?g.entries.get(Y):void 0}if(z)for(let Y=j.length-2;Y>=0;Y--)de(j[Y]);else{g.chainLastId!==void 0&&(g.buffer.push({type:"cleared"}),g.buffer.push({type:"session",sessionId:g.sessionId}),g.latest={in:0,out:0,cached:0,cacheCreate:0});let Y=new Set(j.map(ce=>n.idOf(ce))),Ee=Z(g.entries);for(let ce=j.length-1;ce>=0;ce--)de(j[ce]),F(n.idOf(j[ce]),Ee,Y)}g.chainLastId=O}function Z(g){let S=new Map;for(let w of g.values()){let O=n.parentOf(w);if(!O)continue;let L=S.get(O);L?L.push(w):S.set(O,[w])}return S}function F(g,S,w){if(!g)return;let O=S.get(g);if(!O)return;let L=O.filter(Y=>!n.isSidechain(Y));if(L.length<2)return;let j=L.filter(Y=>!w.has(n.idOf(Y)));if(!j.length)return;let B=[],z=0;for(let Y of j){let Ee=ye(Y,S);B.push(...Ee.events),z+=Ee.count}z>0&&e.buffer.push({type:"fork",atId:g,count:z,events:B})}function ye(g,S){let w=[],O=[g];for(;O.length;){let B=O.pop();if(n.isSidechain(B))continue;w.push(B);let z=S.get(n.idOf(B)??"");if(z)for(let Y of z)O.push(Y)}w.sort((B,z)=>(Date.parse(n.timestampOf(B)??"")||0)-(Date.parse(n.timestampOf(z)??"")||0));let L=[];for(let B of w)n.isRecoveryNoise(B)||L.push(...n.apply(B,e.sessionStartMs).events);return{count:L.reduce((B,z)=>B+(z.type==="user"||z.type==="assistant"?1:0),0),events:L}}function de(g){try{let{events:S,usage:w,model:O,cost:L}=n.apply(g,e.sessionStartMs);for(let j of S)e.buffer.push(j);S.some(j=>j.type==="assistant")&&i()?.d.clearCompletedDraft(),S.some(j=>j.type==="user")&&i()?.d.clearEcho(),O&&(e.latestModel=O),w&&(e.latest=w),(w||L)&&e.buffer.push({type:"usage",...e.latest,cost:L})}catch(S){console.error("[mirror] skipped malformed entry:",V(S))}}async function _e(){return{cwd:e.cwd,pid:process.pid,composer:!!n.createDriver,elsewhere:await be()}}async function be(){if(n.listSessionFiles(e.cwd).length)return;let g=await kn();if(!g)return;let S=jb(g).toLowerCase();for(let w=jb(e.cwd);w.toLowerCase()!==S;){let O=WO(w);if(O===w)return;w=O;let L=n.listSessionFiles(w).length;if(L)return{dir:w,count:L}}}be().then(g=>{g&&console.log(`No sessions for ${e.cwd} \u2014 ${g.count} exist for ${g.dir}. Launched from a subfolder? Relaunch from the project root.`)}).catch(()=>{});let te=new ba;async function ri(g,S){te.accept(g,S)&&console.log(S)}function Gt(){let g=n.sessionAlive(e.sessionId,e.cwd);if(g!==void 0)return g;if(!e.file)return!1;try{return Date.now()-Sr(e.file).mtimeMs<1e4}catch{return!1}}function b(){return n.chainWorking([...e.entries.values()])&&Gt()}function k(){!n.createDriver||i()||e.latestModel||b()||o(e.file)}async function P(g){let S=e;_(),u(),k(),d();let w=i();for(let B of t)B!==w&&B.d.dialog;let O=a().filter(B=>B.rec.d.streaming).map(B=>B.sessionId),L=b(),j=n.createDriver?{streaming:!!w?.d.streaming,foreign:!w&&L,draft:w?.d.draft??null,echo:w?.d.echo??null,status:w?.d.status??null,dialog:w?.d.dialog??null,queue:w?.d.queue??null,stats:w?.d.stats??null,model:w?.d.model??null,error:w?.d.error}:void 0;return{events:S.buffer.slice(g),cursor:S.buffer.length,working:!!w?.d.streaming||L,latestModel:S.latestModel,composer:j,busy:O}}async function N(){_(),u();let g=i();if(g?.d.error&&!g.d.streaming&&(await c(g),g=void 0),!g){if(b())return{ok:!1,error:"the agent is mid-turn in a terminal \u2014 watch only"};g=o(e.file)}let S=g;return{ok:!0,d:S.d,markSent:w=>{S.prompt===void 0&&(S.prompt=w)}}}async function M(g,S){if(!n.createDriver)return{ok:!1,error:"not supported"};let w=String(g??"").trim();if(!w)return{ok:!1,error:"empty message"};let O=await N();if(!O.ok)return O;let L=await O.d.send(w,S);return L.ok&&O.markSent(w),L}async function q(g,S){let w=i();return w?w.d.respondUi(String(g??""),S??{}):{ok:!1,error:"no dialog pending"}}async function J(g,S){if(!n.createDriver)return{ok:!1,error:"not supported"};if(!g||typeof g.type!="string")return{ok:!1,error:"bad command"};if(S?.spawn){let O=await N();return O.ok?O.d.rpc(g):O}let w=i();return!w||w.d.error?{ok:!1,error:"not running"}:w.d.rpc(g)}async function we(){let g=i();if(g)try{await g.d.stop()}catch(S){console.error("[composer] stop:",V(S))}return{ok:!0}}async function H(){return n.createDriver?(u(),!e.file&&r&&r.prompt===void 0&&!r.d.streaming&&!r.d.error?{ok:!0}:(r?.d.error&&await c(r),r=void 0,K(),o(void 0),d(),{ok:!0})):{ok:!1,error:"not supported"}}async function le(){if(!n.createDriver)return[];let g=await Ge(["ls-files","--cached","--others","--exclude-standard"],e.cwd).catch(()=>null),S=g!==null?g.split(`
|
|
2009
|
+
`).filter(Boolean):await n.walkFiles?.(e.cwd)??[];return(await Promise.all(S.map(async O=>{try{return{f:O,m:(await KO(xn(e.cwd,O))).mtimeMs}}catch{return{f:O,m:0}}}))).sort((O,L)=>L.m-O.m).map(O=>O.f)}function xe(){for(let g of[...t])c(g)}async function _r(g){return n.createDriver?Pb(e.cwd,g):{ok:!1,error:"not supported"}}async function Xt(g){return Ob(e.cwd,String(g??""))}async function St(g,S){return Ib(String(g??""),String(S??""))}async function el(){let g=n.listSessionFiles(e.cwd).map(({sessionId:w,file:O,mtime:L})=>({sessionId:w,mtime:L,preview:n.readPreview(O)})),S=l().map(w=>({sessionId:w.sessionId,mtime:w.rec.startedAt,preview:w.rec.prompt??"",pending:!0}));return $b([...g,...S],w=>w.mtime)}let si=new Map;function Dv(g,S){let w=si.get(g);if(w&&w.mtime===S)return w.turns;let O=[],L="";try{L=Aa(g,"utf8")}catch{return[]}for(let j of L.split(`
|
|
2010
|
+
`)){if(!j.trim())continue;let B=n.parseEntry(j);if(!B)continue;let z=n.searchText(B);z&&O.push({text:z,lower:z.toLowerCase()})}return si.set(g,{mtime:S,turns:O}),O}async function jv(g){let S=g.toLowerCase(),w=[];for(let{sessionId:O,file:L,mtime:j}of n.listSessionFiles(e.cwd).sort((B,z)=>z.mtime-B.mtime)){let{hitCount:B,snippet:z}=va(Dv(L,j),S);if(B&&(w.push({sessionId:O,mtime:j,preview:n.readPreview(L),hitCount:B,snippet:z}),w.length>=GO))break}return w}let Ef=800,Af=new Map;function Fv(g,S){let w=Af.get(g);if(w&&w.mtime===S)return w.text;let O="";try{O=Aa(g,"utf8")}catch{return""}let L="";for(let B of O.split(`
|
|
2011
|
+
`)){if(!B.trim())continue;let z=n.parseEntry(B);if(z)for(let Y of n.apply(z,e.sessionStartMs).events)Y.type==="assistant"&&Y.text.trim()&&(L=Y.text.trim())}let j=L.length>Ef?L.slice(0,Ef).trimEnd()+"\u2026":L;return Af.set(g,{mtime:S,text:j}),j}async function Uv(g){let S=n.listSessionFiles(e.cwd).find(w=>w.sessionId===g);return{text:S?Fv(S.file,S.mtime):""}}async function qv(g){let S=e,w=n.listSessionFiles(S.cwd).find(O=>O.sessionId===g);if(!w){let O=l().find(L=>L.sessionId===g)?.rec;return O?((r!==O||S.sessionId!==O.id)&&(r=O,$(void 0,O.id),S.everAttached=!0,d()),{ok:!0}):{ok:!1,error:"session not found"}}return w.file===S.file?{ok:!0}:(A(w),u(),d(),{ok:!0})}return y(e.cwd),E(e.cwd),_(),{info:_e,poll:P,logInlineStatus:ri,listSessions:el,searchSessions:jv,sessionPeek:Uv,attach:qv,composerSend:M,composerStop:we,composerNew:H,composerFiles:le,composerUiRespond:q,composerRpc:J,composerPaste:_r,composerPasteRead:Xt,summarizeTurn:St,shutdownComposer:xe}}var HO,YO,Fb,VO,GO,Ta=v(()=>{"use strict";Kt();vb();qs();Pd();_b();Nb();Lb();HO=".typebulb",YO=`${HO}/locks`,Fb=5e3,VO=6e4;GO=50});import{existsSync as Id,mkdirSync as XO,readFileSync as Ub,writeFileSync as QO}from"fs";import{join as En,isAbsolute as ZO}from"path";async function $d(n,e){let t=ZO(n)?n:En(G,n);return Id(t)?(cd(t,e),{ok:!0}):{ok:!1,error:"file not found"}}async function Ld(n){let e=G,t=ld(n),r=En(e,"typebulbs");XO(r,{recursive:!0});let s=xu(t),i=`${s}.bulb.md`;for(let c=2;Id(En(r,i))&&Ub(En(r,i),"utf8")!==t;c++)i=`${s}-${c}.bulb.md`;let o=En(r,i);Id(o)||QO(o,t);let a=En("typebulbs",i),l=await ws(a,{cwd:e,open:!1});return{ok:!0,file:a,pid:l.pid,url:l.url}}async function Md(){return X(G)}async function Bd(n){let e=(await X()).find(t=>t.pid===n);return e?{ok:!0,outcome:await Lt(e)}:(await Vn(n),{ok:!0})}async function Dd(){let n=await on(G);return aa(G).filter(e=>!e.serverOnly).map(e=>({...e,trusted:vn(e.path),batches:od(e.path),lastRunAt:n(e.path)}))}async function jd(n){let e=n.toLowerCase(),t=[];for(let r of aa(G).filter(s=>!s.serverOnly).sort((s,i)=>i.mtime-s.mtime)){let s="";try{s=Ub(r.path,"utf8")}catch{continue}let i=[];for(let l of s.split(`
|
|
2013
2012
|
`)){let c=l.replace(/\s+/g," ").trim();c&&i.push({text:c,lower:c.toLowerCase()})}let{hitCount:o,snippet:a}=va(i,e);o&&t.push({path:r.path,hitCount:o,snippet:a})}return t}async function Fd(n,e,t){let r=G;e!=null&&mr(n,e);let s=await ws(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 Ud(n){return{cap:await ad(n)}}async function qd(n,e){return mr(n,e),{ok:!0}}async function Jd(n,e){return Ke(n,e)}async function Kd(){return Js&&Date.now()-Js.fetchedAt<=t_?Js.samples:(_d??=n_().finally(()=>{_d=null}),_d)}async function n_(){try{let n=await fetch(`${e_}/api/scripts/u/samples?stubs`,{signal:AbortSignal.timeout(Jb)});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:cl(i.config)}));return Js={samples:s,fetchedAt:Date.now()},s}catch{return Js?.samples??[]}}async function Wd(n){return Nd.test(n)?Wb(qb,"samples",n,!0):{ok:!1,error:"bad slug"}}async function Yd(){let n=Hd();if(!n)return{bulbs:[]};let e=`${Pa()}
|
|
2014
2013
|
${n}`;return Wt?.key===e&&Date.now()-Wt.fetchedAt<=r_?{user:Wt.user,bulbs:Wt.bulbs}:(Cd??=s_(e,n).finally(()=>{Cd=null}),Cd)}async function Rd(n,e,t){let r=await fetch(`${n}${e}`,{headers:t,signal:AbortSignal.timeout(Jb)});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 s_(n,e){let t={Authorization:`Bearer ${e}`};try{let r=Pa(),s;try{s=await Rd(r,"/api/me",t)}catch{let a=new URL(r);r=`${a.protocol}//api.${a.host}`,s=await Rd(r,"/api/me",t)}let o=(await Rd(r,"/api/scripts/list",t)).filter(a=>a.userSlug===s.slug&&!a.isTemplate).map(a=>({slug:a.slug,name:a.name,description:cl(a.config)}));return Wt={key:n,user:s.slug,bulbs:o,fetchedAt:Date.now()},{user:s.slug,bulbs:o}}catch{return Wt?.key===n?{user:Wt.user,bulbs:Wt.bulbs}:{bulbs:[]}}}async function Vd(n,e,t=!1){return!Nd.test(e)||!Nd.test(n)?{ok:!1,error:"bad slug"}:Wb(Pa(),n,e,t)}async function Wb(n,e,t,r){let s=ca(e,t);try{let i=await fa({origin:n,userSlug:e,slug:t,dest:En(G,s)},{force:r,token:Hd(),timeoutMs:Kb});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 zd(n,e=!1){let t=Hd();if(!t)return{ok:!1,error:"no TYPEBULB_TOKEN in .env"};try{let r=da(n,G,Pa()),s=await ha(r,{token:t,force:e,timeoutMs:Kb});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 e_,qb,t_,Jb,Kb,Js,_d,Nd,r_,Wt,Cd,Pa,Hd,Oa=v(()=>{"use strict";br();Kt();Pd();ee();e_="https://api.typebulb.com",qb="https://typebulb.com",t_=3600*1e3,Jb=5e3,Kb=15e3,Js=null,_d=null;Nd=/^[a-z0-9][a-z0-9-]*$/,r_=300*1e3,Wt=null,Cd=null,Pa=()=>ea("TYPEBULB_ORIGIN",G)||qb,Hd=()=>ea("TYPEBULB_TOKEN",G)});import{readFileSync as Qd,writeFileSync as Yb,mkdirSync as i_,appendFileSync as Vb,rmSync as Hb}from"fs";import{join as Ra,dirname as o_}from"path";import{createServer as a_}from"http";function Ht(n){try{return JSON.parse(Qd(n,"utf8"))}catch{return null}}function Ca(n,e){i_(o_(n),{recursive:!0}),Yb(n,JSON.stringify(e,null,2)+`
|
|
2015
2014
|
`)}function Gb(n,e,t){let r=Ra(n,".gitignore"),s="";try{s=Qd(r,"utf8")}catch{}let i=new Set(s.split(/\r?\n/).map(l=>l.trim())),o=e.filter(l=>!i.has(l));if(!o.length)return;let a=s&&!s.endsWith(`
|
|
@@ -2229,27 +2228,28 @@ Examples:
|
|
|
2229
2228
|
*/
|
|
2230
2229
|
insight<T = unknown>(): T | undefined;`,PC=`
|
|
2231
2230
|
/**
|
|
2232
|
-
* Replace the data this run is working on
|
|
2231
|
+
* Replace the data this run is working on.
|
|
2233
2232
|
*
|
|
2234
2233
|
* Updates what \`tb.data()\` / \`tb.json()\` return for the rest of this page, and writes the
|
|
2235
|
-
* result into the URL fragment so the address bar addresses this run
|
|
2236
|
-
* \`data.txt\` is never touched: a reload without the fragment goes back
|
|
2234
|
+
* result into the URL fragment, so the address bar addresses this run and \`tb.url()\` carries
|
|
2235
|
+
* it. The bulb's source \`data.txt\` is never touched: a reload without the fragment goes back
|
|
2236
|
+
* to the file.
|
|
2237
2237
|
*
|
|
2238
2238
|
* @param chunks - The new data chunks (a bare string is treated as one chunk)
|
|
2239
|
-
* @returns
|
|
2240
|
-
*
|
|
2239
|
+
* @returns Resolves once the address bar reflects the write. Data too large to fit a URL
|
|
2240
|
+
* (~60KB encoded) still swaps, but carries no fragment: pass what a share needs, not
|
|
2241
|
+
* necessarily everything.
|
|
2241
2242
|
*/
|
|
2242
|
-
setData(chunks: string | string[]): Promise<
|
|
2243
|
+
setData(chunks: string | string[]): Promise<void>;
|
|
2243
2244
|
/**
|
|
2244
|
-
* Replace the insight this run is working on
|
|
2245
|
+
* Replace the insight this run is working on.
|
|
2245
2246
|
*
|
|
2246
2247
|
* The \`tb.insight()\` counterpart of \`setData\`, with the same fragment behavior and the same
|
|
2247
2248
|
* rule: runtime only, never the bulb's source \`insight.json\`.
|
|
2248
2249
|
*
|
|
2249
2250
|
* @param value - Any JSON-serializable value
|
|
2250
|
-
* @returns The shareable URL, or undefined (see \`setData\`)
|
|
2251
2251
|
*/
|
|
2252
|
-
setInsight(value: unknown): Promise<
|
|
2252
|
+
setInsight(value: unknown): Promise<void>;`,Pw=`options: {
|
|
2253
2253
|
messages: Array<{ role: "user" | "assistant"; content: string }>;
|
|
2254
2254
|
system?: string;
|
|
2255
2255
|
/** Reasoning effort: 0=minimal, 1=low, 2=med, 3=high, 4=xhigh. Mapped to each provider's native mechanism (OpenAI/OpenRouter reasoning effort, Gemini thinking level, Anthropic adaptive thinking). 0 reaches the vendor's explicit off switch, and floors to a little thinking only on always-thinking models. 4 reaches the rung above high where the vendor has one (OpenAI/OpenRouter xhigh, Anthropic max) and clamps to high where it doesn't (Gemini) \u2014 never an error. Pin 1 (low) for most work; pick 0 deliberately, when you want the raw model or latency is the constraint. Omitting is NOT off \u2014 it buys the model's own default (medium on GPT-5.6), which reasons and bills invisibly. Ignored on the courtesy model, which runs at the level Typebulb sets. */
|
|
@@ -2405,9 +2405,11 @@ type AiAccess = "own" | "courtesy" | "none";
|
|
|
2405
2405
|
/**
|
|
2406
2406
|
* Get the canonical URL of this bulb.
|
|
2407
2407
|
*
|
|
2408
|
-
* Returns the parent typebulb.com URL (including
|
|
2409
|
-
*
|
|
2410
|
-
*
|
|
2408
|
+
* Returns the parent typebulb.com URL (including query and \`#tb=\` fragment), resolving
|
|
2409
|
+
* correctly from inside the cross-origin sandbox iframe. That is the published \`/full\` page
|
|
2410
|
+
* even while authoring in the IDE, because it is the link someone you send it to can open.
|
|
2411
|
+
* Locally it is the served localhost URL. Use this instead of \`location.href\` or
|
|
2412
|
+
* \`document.referrer\`.
|
|
2411
2413
|
*
|
|
2412
2414
|
* @returns The full canonical URL
|
|
2413
2415
|
*/
|
|
@@ -2475,6 +2477,7 @@ const CSS = '\\n' +
|
|
|
2475
2477
|
'.body { padding: 0 16px; overflow-y: auto; flex: 1; display: flex; flex-direction: column; gap: 10px; }\\n' +
|
|
2476
2478
|
'.model { color: var(--muted); }\\n' +
|
|
2477
2479
|
'.model.err { color: var(--err); }\\n' +
|
|
2480
|
+
'.note { color: var(--muted); }\\n' +
|
|
2478
2481
|
'label { font-weight: 600; }\\n' +
|
|
2479
2482
|
'.tabs { display: flex; gap: 4px; }\\n' +
|
|
2480
2483
|
'.tab { font: inherit; padding: 4px 10px; border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; color: inherit; cursor: pointer; opacity: .6; }\\n' +
|
|
@@ -2530,7 +2533,8 @@ function chunkLabel(chunk, i, titles) {
|
|
|
2530
2533
|
* after an error included); onError on each displayed terminal error; onCancel when the user
|
|
2531
2534
|
* closes before any completion. runtimeState() returns the wire pair for what a prior run actually
|
|
2532
2535
|
* set \u2014 a slot nobody set is absent from it, so an empty pair means nothing was \u2014 which is what
|
|
2533
|
-
* Save files and what gates these controls.
|
|
2536
|
+
* Save files and what gates these controls. With no infer.md block the same call opens the Bulb
|
|
2537
|
+
* state panel instead: the run half dropped, the state half kept (TB-Inference.md).
|
|
2534
2538
|
*/
|
|
2535
2539
|
export function runInference(ctx) {
|
|
2536
2540
|
var host = document.createElement('div');
|
|
@@ -2588,26 +2592,42 @@ export function runInference(ctx) {
|
|
|
2588
2592
|
foot.appendChild(cancel);
|
|
2589
2593
|
|
|
2590
2594
|
// Build the whole view once the seed arrives (a localhost roundtrip; the shimmer covers it).
|
|
2591
|
-
//
|
|
2592
|
-
// chunks from the server \u2014 never the page's post-run runtime data.
|
|
2595
|
+
// The same reply decides which view it is: no infer.md block, no run half (buildConfirm).
|
|
2593
2596
|
fetch('/__infer-info').then(function (r) { return r.json(); })
|
|
2594
2597
|
.catch(function () { return {}; })
|
|
2595
2598
|
.then(function (info) { buildConfirm(info || {}); });
|
|
2596
2599
|
}
|
|
2597
2600
|
|
|
2598
|
-
function
|
|
2599
|
-
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
2600
|
-
inferCfg = info.inference || {};
|
|
2601
|
-
if (inferCfg.title) title.textContent = inferCfg.title;
|
|
2601
|
+
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
2602
2602
|
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2603
|
+
// One line naming what Save would file, in the blocks it writes. Only what it writes: a slot
|
|
2604
|
+
// nobody set is left out rather than reported as untouched, which draws the eye to a non-event.
|
|
2605
|
+
function stateSummary(rt) {
|
|
2606
|
+
var chunks = rt.data || [];
|
|
2607
|
+
var hasInsight = 'insight' in rt;
|
|
2608
|
+
if (!chunks.length && !hasInsight) {
|
|
2609
|
+
return 'Nothing set: this page is showing the bulb\\u2019s own data.txt and insight.json';
|
|
2610
|
+
}
|
|
2611
|
+
if (!chunks.length) return 'Save writes insight.json';
|
|
2612
|
+
var chars = 0;
|
|
2613
|
+
for (var i = 0; i < chunks.length; i++) chars += chunks[i].length;
|
|
2614
|
+
var d = 'data.txt (' + (chunks.length > 1 ? chunks.length + ' chunks, ' : '')
|
|
2615
|
+
+ formatCount(chars) + ' chars)';
|
|
2616
|
+
return 'Save writes ' + d + (hasInsight ? ' and insight.json' : '');
|
|
2617
|
+
}
|
|
2608
2618
|
|
|
2619
|
+
// The data view: an editor for a run, a read-only readout in the Bulb state panel, where edits
|
|
2620
|
+
// would go nowhere (Save posts the pair, never a textarea) and the tab strip is the best display
|
|
2621
|
+
// of a multi-chunk slot there is.
|
|
2622
|
+
// Seeding is explicit ctx.data (an argument, or a retry's edits) > what the
|
|
2623
|
+
// page currently holds > the bulb's SOURCE chunks from the server. Runtime ahead of source so a
|
|
2624
|
+
// reopen shows the chunks the page is actually on, matching .com; the explicit argument ahead of
|
|
2625
|
+
// both, where .com puts the slot first and so loses tb.infer({ data }) after a prior run. An
|
|
2626
|
+
// emptied chunk does not come back this way (run() drops it) \u2014 Discard run is what does.
|
|
2627
|
+
function buildEditor(info, rt, readOnly) {
|
|
2609
2628
|
var chunks = ctx.data && ctx.data.length ? ctx.data
|
|
2610
|
-
: (
|
|
2629
|
+
: (rt.data && rt.data.length ? rt.data
|
|
2630
|
+
: (info.data && info.data.length ? info.data : ['']));
|
|
2611
2631
|
var titles = dataTitles();
|
|
2612
2632
|
// Multi-chunk: .com's shape \u2014 a tab per chunk (label + live char count), one textarea visible.
|
|
2613
2633
|
var multi = chunks.length > 1;
|
|
@@ -2615,7 +2635,6 @@ export function runInference(ctx) {
|
|
|
2615
2635
|
var counts = [];
|
|
2616
2636
|
var strip = multi ? el('div', 'tabs') : null;
|
|
2617
2637
|
if (strip) body.appendChild(strip);
|
|
2618
|
-
function formatCount(n) { return n < 10000 ? String(n) : Math.round(n / 1000) + 'K'; }
|
|
2619
2638
|
function selectTab(i) {
|
|
2620
2639
|
tabBtns.forEach(function (b, j) { b.className = j === i ? 'tab on' : 'tab'; });
|
|
2621
2640
|
areas.forEach(function (a, j) { a.style.display = j === i ? '' : 'none'; });
|
|
@@ -2631,10 +2650,11 @@ export function runInference(ctx) {
|
|
|
2631
2650
|
tabBtns.push(tab);
|
|
2632
2651
|
strip.appendChild(tab);
|
|
2633
2652
|
} else {
|
|
2634
|
-
body.appendChild(el('label', '', titles[0] || 'Data to process'));
|
|
2653
|
+
body.appendChild(el('label', '', titles[0] || (readOnly ? 'data.txt' : 'Data to process')));
|
|
2635
2654
|
}
|
|
2636
2655
|
var ta = document.createElement('textarea');
|
|
2637
2656
|
ta.value = chunk;
|
|
2657
|
+
ta.readOnly = !!readOnly;
|
|
2638
2658
|
if (!chunk) ta.placeholder = 'Paste data to process (optional)\\u2026';
|
|
2639
2659
|
ta.addEventListener('input', function () {
|
|
2640
2660
|
// 2 blank lines IS the chunk separator \u2014 collapse pasted 3+ so text can't silently split (.com parity)
|
|
@@ -2646,16 +2666,43 @@ export function runInference(ctx) {
|
|
|
2646
2666
|
body.appendChild(ta);
|
|
2647
2667
|
});
|
|
2648
2668
|
if (multi) selectTab(0);
|
|
2649
|
-
|
|
2650
|
-
|
|
2651
|
-
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
function buildConfirm(info) {
|
|
2672
|
+
body.textContent = ''; foot.textContent = ''; areas = [];
|
|
2673
|
+
var rt = ctx.runtimeState();
|
|
2674
|
+
// No infer.md: nothing here can run, so the modal is the page's state surface and nothing else
|
|
2675
|
+
// (TB-Inference.md). Same actions, minus the run \u2014 and the config.inference title stays out of
|
|
2676
|
+
// it, because it names a run that cannot happen.
|
|
2677
|
+
var stateOnly = info.hasInfer === false;
|
|
2678
|
+
inferCfg = stateOnly ? {} : (info.inference || {});
|
|
2679
|
+
if (stateOnly) title.textContent = 'Bulb state';
|
|
2680
|
+
else if (inferCfg.title) title.textContent = inferCfg.title;
|
|
2681
|
+
|
|
2682
|
+
var runBtn = null;
|
|
2683
|
+
if (!stateOnly) {
|
|
2684
|
+
var model = el('div', 'model');
|
|
2685
|
+
runBtn = el('button', 'run', inferCfg.submitTitle || 'Run');
|
|
2686
|
+
if (info.error) { model.textContent = info.error; model.className = 'model err'; runBtn.disabled = true; }
|
|
2687
|
+
else if (info.model) model.textContent = info.model + ' \\u00b7 ' + info.provider;
|
|
2688
|
+
else model.textContent = 'Model info unavailable';
|
|
2689
|
+
buildEditor(info, rt, false);
|
|
2690
|
+
// The model line reads as a footnote to the action, not a header to the data \u2014 under the
|
|
2691
|
+
// textareas, above the buttons.
|
|
2692
|
+
body.appendChild(model);
|
|
2693
|
+
}
|
|
2694
|
+
// The panel reads out what tb.data() answers: the slot when a setter filled it, the file's
|
|
2695
|
+
// chunks when none did. Skipped only when there is neither, where the caption says so instead.
|
|
2696
|
+
else if ((rt.data && rt.data.length) || (info.data && info.data.length)) buildEditor(info, rt, true);
|
|
2697
|
+
// What Save would file, beside the button that files it: Save posts the runtime pair and never
|
|
2698
|
+
// the textareas above it. In the state panel this line is the whole of the body.
|
|
2699
|
+
if (stateOnly || Object.keys(rt).length) body.appendChild(el('div', 'note', stateSummary(rt)));
|
|
2652
2700
|
|
|
2653
2701
|
// Actions over a prior run. Save and Discard follow the RUN (runtime state), share follows the
|
|
2654
2702
|
// FRAGMENT: filing has no size ceiling, only the URL does, so an over-ceiling run that minted no
|
|
2655
2703
|
// link is still savable (TB-State.md, "The ceiling bounds sharing, not saving").
|
|
2656
2704
|
// Any key means a slot was set: the pair carries only what someone wrote, so counting keys
|
|
2657
2705
|
// asks that without restating which slots exist or how an unset one is spelled.
|
|
2658
|
-
var rt = ctx.runtimeState();
|
|
2659
2706
|
if (Object.keys(rt).length) {
|
|
2660
2707
|
var grp = el('div', 'leftgrp');
|
|
2661
2708
|
// Drop the run from the address bar. Both actions below leave the page holding the run it is
|
|
@@ -2710,6 +2757,12 @@ export function runInference(ctx) {
|
|
|
2710
2757
|
foot.appendChild(grp);
|
|
2711
2758
|
}
|
|
2712
2759
|
|
|
2760
|
+
if (stateOnly) {
|
|
2761
|
+
var closeBtn = el('button', '', 'Close');
|
|
2762
|
+
closeBtn.addEventListener('click', function () { close('cancel'); });
|
|
2763
|
+
foot.appendChild(closeBtn);
|
|
2764
|
+
return;
|
|
2765
|
+
}
|
|
2713
2766
|
var cancel = el('button', '', 'Cancel');
|
|
2714
2767
|
cancel.addEventListener('click', function () { close('cancel'); });
|
|
2715
2768
|
foot.appendChild(cancel);
|
|
@@ -2783,9 +2836,9 @@ export function runInference(ctx) {
|
|
|
2783
2836
|
showConfirm();
|
|
2784
2837
|
document.body.appendChild(host);
|
|
2785
2838
|
}
|
|
2786
|
-
`;sr();Re();wn();ra();bn();import{stream as vR}from"hono/streaming";var SR="X-TB-Stream";function ti(n){return n instanceof Pe?{message:n.message,code:n.code,retryable:n.retryable}:{message:n instanceof Error?n.message:"Unknown error",code:"unknown",retryable:!1}}function za(n,e){return n.header("Content-Type","application/x-ndjson; charset=utf-8"),n.header("Cache-Control","no-cache"),n.header(SR,"1"),vR(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:ti(s)}))}finally{try{await r.return?.()}catch{}}})}var Ga={log:(...n)=>console.log(...n)};function Xa(n,e){let t=n?.[e]??(Object.hasOwn(Ga,e)?Ga[e]:void 0);return typeof t=="function"?t:void 0}function Qa(n){return n.constructor?.name==="AsyncGeneratorFunction"}rd();var kR=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,xR=/[?&]target=/,ER=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function bv(n,e=""){return kR.test(n)?!0:ER.test(n)&&xR.test(e)}var _R="127.0.0.1",CR=new Set(["localhost","127.0.0.1","::1"]),xv=(n,e)=>!!n&&typeof n=="object"&&e in n,wv=n=>{let e={};return Array.isArray(n.data)&&(e.data=n.data),xv(n,"insight")&&(e.insight=n.insight),e},vv=8*1024*1024,RR=0;function IR(n){if(n)try{return new URL(n.includes("://")?n:`http://${n}`).hostname}catch{return}}function Ev(n){let e=IR(n);return!!e&&CR.has(e)}function NR(n){try{let e=new URL(n);return(e.protocol==="http:"||e.protocol==="https:")&&Ev(e.host)}catch{return!1}}function $R(n){return!!n&&/\bCode\/\d/.test(n)&&/\bElectron\//.test(n)}function LR(n,e){if(!e)return!1;try{return new URL(n).host===e}catch{return!1}}function wf(n){return n instanceof Error?n.message:"Unknown error"}var Sv=n=>n.how==="editor"||n.how==="unreached"?n.via:void 0,MR=2e3;async function Av(n){let{getHtml:e,basePath:t,fsBase:r,port:s,reloadEmitter:i,sendChannel:o,getServerExports:a,getBulbBlocks:l,saveInferenceResult:c,localOverride:d,trusted:u=!1,trustHint:f,staticAssets:p,bulbAssets:m,sourceFile:h,bulbKey:y,onStop:E}=n,T=`${process.pid}-${++RR}-${Date.now()}`,_=r??t,x=new AR;x.use("*",async(b,k)=>{if(!Ev(b.req.header("host")))return b.text("Forbidden: untrusted Host",403);await k()}),x.use("*",async(b,k)=>{await k(),b.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),b.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let I=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],R=async(b,k)=>{if(!u){let P=new URL(b.req.url).pathname,N=I.find(([
|
|
2787
|
-
${f}`:"";return b.text(`Forbidden: this capability requires --trust.${
|
|
2788
|
-
`+H.slice(-4e3)),new Pe("LLM output is not valid JSON","parse_error",!0);le.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",le.fixesApplied.join(", ")),yield{kind:"complete",insight:le.parsed,data:
|
|
2839
|
+
`;sr();Re();wn();ra();bn();import{stream as vR}from"hono/streaming";var SR="X-TB-Stream";function ti(n){return n instanceof Pe?{message:n.message,code:n.code,retryable:n.retryable}:{message:n instanceof Error?n.message:"Unknown error",code:"unknown",retryable:!1}}function za(n,e){return n.header("Content-Type","application/x-ndjson; charset=utf-8"),n.header("Cache-Control","no-cache"),n.header(SR,"1"),vR(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:ti(s)}))}finally{try{await r.return?.()}catch{}}})}var Ga={log:(...n)=>console.log(...n)};function Xa(n,e){let t=n?.[e]??(Object.hasOwn(Ga,e)?Ga[e]:void 0);return typeof t=="function"?t:void 0}function Qa(n){return n.constructor?.name==="AsyncGeneratorFunction"}rd();var kR=/^\/(v\d+\/|stable\/|node\/|gh\/|@[^/]+\/[^@/]+@|[^@/]+@)/,xR=/[?&]target=/,ER=/^\/(?:@[^/]+\/)?[^/@]+\/[^/]+/;function bv(n,e=""){return kR.test(n)?!0:ER.test(n)&&xR.test(e)}var _R="127.0.0.1",CR=new Set(["localhost","127.0.0.1","::1"]),xv=(n,e)=>!!n&&typeof n=="object"&&e in n,wv=n=>{let e={};return Array.isArray(n.data)&&(e.data=n.data),xv(n,"insight")&&(e.insight=n.insight),e},vv=8*1024*1024,RR=0;function IR(n){if(n)try{return new URL(n.includes("://")?n:`http://${n}`).hostname}catch{return}}function Ev(n){let e=IR(n);return!!e&&CR.has(e)}function NR(n){try{let e=new URL(n);return(e.protocol==="http:"||e.protocol==="https:")&&Ev(e.host)}catch{return!1}}function $R(n){return!!n&&/\bCode\/\d/.test(n)&&/\bElectron\//.test(n)}function LR(n,e){if(!e)return!1;try{return new URL(n).host===e}catch{return!1}}function wf(n){return n instanceof Error?n.message:"Unknown error"}var Sv=n=>n.how==="editor"||n.how==="unreached"?n.via:void 0,MR=2e3;async function Av(n){let{getHtml:e,basePath:t,fsBase:r,port:s,reloadEmitter:i,sendChannel:o,getServerExports:a,getBulbBlocks:l,saveInferenceResult:c,localOverride:d,trusted:u=!1,trustHint:f,staticAssets:p,bulbAssets:m,sourceFile:h,bulbKey:y,onStop:E}=n,T=`${process.pid}-${++RR}-${Date.now()}`,_=r??t,x=new AR;x.use("*",async(b,k)=>{if(!Ev(b.req.header("host")))return b.text("Forbidden: untrusted Host",403);await k()}),x.use("*",async(b,k)=>{await k(),b.res.headers.set("Cross-Origin-Opener-Policy","same-origin"),b.res.headers.set("Cross-Origin-Embedder-Policy","credentialless")});let I=[["/__fs/*","the filesystem"],["/__api/*","server-side code (server.ts)"],["/__ai","AI (your API keys)"],["/__infer","AI (your API keys)"],["/__infer-save","the filesystem"]],R=async(b,k)=>{if(!u){let P=new URL(b.req.url).pathname,N=I.find(([q])=>q.endsWith("/*")?P.startsWith(q.slice(0,-2)):P===q)?.[1]??"server-side code (server.ts)";bu(process.pid,N);let M=f?`
|
|
2840
|
+
${f}`:"";return b.text(`Forbidden: this capability requires --trust.${M}`,403)}await k()},$=async(b,k)=>{let P=b.req.header("sec-fetch-site");if(P){if(P!=="same-origin")return b.text(`Forbidden: ${P} request`,403)}else{let N=b.req.header("origin");if(N&&!LR(N,b.req.header("host")))return b.text("Forbidden: cross-origin request",403)}await k()};for(let[b]of I)x.use(b,R),x.use(b,$);x.use("/__log",$),x.post("/__log",async b=>{try{let{args:k}=await b.req.json();console.log(...k||[])}catch{}return b.json({ok:!0})});let A=new Ha,K=new Set,Q=new Set,Z=Date.now();A.onArrival(({page:b,firstAttach:k,count:P})=>{o&&P===1&&console.log(Xe.connected),k&&P>1&&b.close("yielded").catch(()=>{})}),o&&A.onSettledEmpty(()=>console.log(Xe.disconnected));let F,ye=0,de=async b=>{let k=Math.max(b.fresh?0:Z,A.lastDropAt);if(await A.whenArrives(mf-(Date.now()-k)))return{how:"attached"};if(Date.now()-ye<MR)return{how:"none"};let P=`http://localhost:${s}#tb-relay`,N=await vu(P,t),M;return N?.where==="editor"?M={how:"editor",via:N.via}:(b.external==="force"||b.external==="follow"&&N?.where==="external")&&(await OR(P),M={how:"external"}),M?await A.whenArrives(ev)?M:{how:"unreached",via:Sv(M)}:(ye=Date.now(),{how:"none"})},_e=b=>A.count>0?Promise.resolve({how:"attached"}):F??=de(b).finally(()=>{F=void 0});if(o){let b=0,k=new Map;x.use("/__send",$),x.post("/__send",async P=>{let N="";try{N=await P.req.text()}catch{}let M=Number(P.req.query("reply"))||0,q=A.count===0&&P.req.query("open")!==void 0?await _e({external:"follow",fresh:!1}):void 0,J=A.count,we=J===0&&A.lastDropAt?Date.now()-A.lastDropAt:void 0,H={clients:J,droppedMsAgo:we,...q?{opening:q.how,via:Sv(q)}:{}};if(P.req.query("solo")!==void 0&&J!==1)return P.json({...H,refused:J>1});if(J===0)return P.json(H);let le=Xt=>{for(let St of A)St.send(Xt).catch(()=>{})};if(M<=0)return le({payload:N}),P.json(H);let xe=++b,_r=await new Promise(Xt=>{let St={expected:J,received:0,results:[],errors:[],finish:si=>{clearTimeout(el),k.delete(xe),Xt({results:St.results,errors:St.errors,timedOut:si})}},el=setTimeout(()=>St.finish(!0),M);k.set(xe,St),le({id:xe,payload:N})});return P.json({...H,..._r})}),x.use("/__send-reply",$),x.post("/__send-reply",async P=>{try{let{id:N,results:M,errors:q}=await P.req.json(),J=k.get(N);J&&(J.results.push(...M??[]),J.errors.push(...q??[]),++J.received>=J.expected&&J.finish(!1))}catch{}return P.json({ok:!0})})}x.get("/",b=>b.html(e())),x.post("/__fs/read",async b=>{try{let{path:k}=await b.req.json(),P=await Ls(k,_,t);return new Response(new Uint8Array(P),{headers:{"Content-Type":"application/octet-stream"}})}catch(k){let P=wf(k);return b.json({error:P},400)}}),x.post("/__fs/write",async b=>{try{let k=b.req.query("path");return k?(await ia(k,new Uint8Array(await b.req.arrayBuffer()),_,t),b.json({success:!0})):b.json({error:"Missing path"},400)}catch(k){let P=wf(k);return b.json({error:P},400)}}),x.post("/__api/:name",async b=>{try{let k=b.req.param("name"),P=Xa(a?.(),k);if(!P)return b.json({error:`API function '${k}' not found`},404);let{args:N}=await b.req.json();if(Qa(P))return za(b,P(...N||[]));let M=await P(...N||[]);return b.json({result:M})}catch(k){let P=wf(k);return b.json({error:P},500)}}),x.post("/__ai",async b=>{try{let{messages:k,system:P,effort:N,provider:M,model:q,webSearch:J,stream:we}=await b.req.json();if(!k||!Array.isArray(k)||k.length===0)return b.json({message:"messages array is required",code:"unknown",retryable:!1},400);let H=gt(M,q);if(typeof H=="string")return b.json({message:H,code:"unknown",retryable:!1},400);let le=await Ut(H,{messages:k,system:P,effort:N,webSearch:J,signal:b.req.raw.signal});if(!le.ok){let Xt=await ar(le,H.protocol);return b.json(Xt,le.status)}if(we)return za(b,yn(le,H.protocol));let{text:xe,usage:_r}=await lr(le,H.protocol);return xe||console.warn("[tb.ai] Empty response from provider"),b.json({text:xe,usage:_r})}catch(k){return b.json(ti(k),500)}}),x.post("/__infer",async b=>{try{let{data:k}=await b.req.json().catch(()=>({})),P=l?.();if(!P?.infer.trim())return b.json({message:"This bulb has no infer.md block.",code:"unknown",retryable:!1},400);let N=gt();if(typeof N=="string")return b.json({message:N,code:"unknown",retryable:!1},400);let M=Array.isArray(k)?k.map(String):[],q=Xu(P,M),J=await Ut(N,{messages:[{role:"user",content:q}],signal:b.req.raw.signal});if(!J.ok){let H=await ar(J,N.protocol);return b.json(H,J.status)}let we=(async function*(){let H="";for await(let xe of yn(J,N.protocol))xe.kind!=="text"||!xe.text||(H+=xe.text,yield{kind:"delta",text:xe.text});let le=Qu(H);if(le.parsed===void 0)throw console.warn(`[tb.infer] output not valid JSON after sanitize; raw output (last 4000 chars):
|
|
2841
|
+
`+H.slice(-4e3)),new Pe("LLM output is not valid JSON","parse_error",!0);le.fixesApplied.length&&console.warn("[tb.infer] sanitized output, fixes applied:",le.fixesApplied.join(", ")),yield{kind:"complete",insight:le.parsed,data:M,fixesApplied:le.fixesApplied}})();return za(b,we)}catch(k){return b.json(ti(k),500)}}),x.post("/__infer-save",async b=>{try{if(!c)return b.json({message:"Save is not available for this server.",code:"unknown",retryable:!1},400);let k=wv(await b.req.json().catch(()=>({})));return Object.keys(k).length?(await c(k.data,xv(k,"insight")?JSON.stringify(k.insight,null,2):void 0),b.json({ok:!0})):b.json({message:"Nothing to save \u2014 this page holds no runtime state.",code:"unknown",retryable:!1},400)}catch(k){return b.json(ti(k),500)}}),x.get("/__infer-info",b=>{let k=l?.(),P=Rr(k?.config??"").inference,N=co(k?.data??""),M=!!k?.infer.trim(),q=gt();return typeof q=="string"?b.json({error:q,inference:P,data:N,hasInfer:M}):b.json({provider:q.protocol,model:q.model,inference:P,data:N,hasInfer:M})}),x.use("/__tb-decode",$),x.post("/__tb-decode",async b=>{let{hash:k}=await b.req.json().catch(()=>({})),P=typeof k=="string"?ed(k):void 0;return b.json(P??{error:"invalid fragment"})}),x.use("/__tb-encode",$),x.post("/__tb-encode",async b=>{let k=Number(b.req.header("content-length"));if(Number.isFinite(k)&&k>vv)return b.json({hash:""});let P=await b.req.text().catch(()=>"");if(P.length>vv)return b.json({hash:""});let N;try{N=JSON.parse(P)}catch{return b.json({hash:""})}return b.json({hash:Zu(wv(N))})}),x.get("/__infer-ui.js",b=>b.body(yv,200,{"Content-Type":"text/javascript; charset=utf-8"})),x.get("/__models",async b=>{try{let k=await mt();return b.json(k)}catch{return b.json([],200)}}),x.get("/__ai-access",async b=>{try{return b.json(await na())}catch{return b.json("none",200)}}),h&&x.get("/__source/*",async b=>{let k=await Sf.readFile(h,"utf-8").catch(()=>{});return k===void 0?b.text("Not Found",404):new Response(k,{headers:{"Content-Type":"text/plain; charset=utf-8"}})});let be=["esm.sh","unpkg.com","cdn.jsdelivr.net","cdnjs.cloudflare.com"],te=new Va;x.get("/proxy/*",async b=>{let k=new URL(b.req.url),N=(k.pathname+k.search).slice(7),M=N.lastIndexOf("https://");return M===-1?b.text("Invalid proxy URL",400):ri(b,N.slice(M))}),d&&kv(x,`/local/${d.name}/`,d.serveDir),p&&kv(x,p.mount,p.dir),m&&x.get("/assets/*",async b=>{let{pathname:k}=new URL(b.req.url),P=k.slice(8),N;try{N=decodeURIComponent(P)}catch{return b.text("Not Found",404)}let M=Gf(N);if(M)return b.text(`${M} is not an asset type: a bulb's code and markup live in the bulb; assets are media and data`,403);try{for(let J of m.dirs){let we=await Tv(N,J,{"Cache-Control":"no-cache"});if(we)return we}}catch{return b.text("Not Found",404)}let q=m.remoteBase;return q?b.redirect(q+P,302):b.text("Not Found",404)});async function ri(b,k){let P;try{P=new URL(k)}catch{return b.text("Invalid URL",400)}if(P.protocol!=="https:")return b.text("HTTPS only",400);if(!be.includes(P.hostname))return b.text("Host not allowed",403);let N=await te.get(k);if(N)return new Response(N.body,{status:200,headers:vf(N.contentType,N.cacheControl)});try{let M=await fetch(k,{headers:{Accept:b.req.header("Accept")||"*/*"},redirect:"follow"});if(!M.ok)return b.text(`Upstream ${M.status}`,M.status);let q=M.headers.get("Content-Type")||void 0,J=M.headers.get("Cache-Control")||void 0;if(M.body){let[we,H]=M.body.tee();return(async()=>{try{let le=await new Response(H).arrayBuffer();await te.set(k,{body:Buffer.from(le),contentType:q,cacheControl:J})}catch{}})(),new Response(we,{status:M.status,headers:vf(q,J)})}return new Response(null,{status:M.status,headers:vf(q,J)})}catch(M){return b.text(`Proxy fetch failed: ${M instanceof Error?M.message:M}`,502)}}(i||o)&&(x.get("/__reload",b=>PR(b,async k=>{let P=b.req.query("bulb")||void 0;if(y&&P&&P!==y){K.has(P)||(K.add(P),console.log(Xe.closed("foreign"))),await k.writeSSE({event:"close",data:"foreign"});return}let N=()=>{k.writeSSE({event:"reload",data:""})};i?.on("reload",N);let M=()=>i?.removeListener("reload",N),q=b.req.query("relay")||void 0,J={inEditor:$R(b.req.header("user-agent")),doc:q,open:H=>k.writeSSE({event:"open-url",data:H}),send:H=>k.writeSSE({event:"message",data:JSON.stringify(H)}),close:H=>(M(),A.closing(J),console.log(Xe.closed(H)),k.writeSSE({event:"close",data:H}))},we=!!q&&!Q.has(q);for(q&&Q.add(q),A.add(J,we),k.onAbort(()=>{M(),A.dropped(J)}),await k.writeSSE({event:"hello",data:T,retry:ju});!k.aborted;)await k.sleep(3e4)})),x.use("/__open",$),x.post("/__open",async b=>{let k="";try{k=String((await b.req.json()).url??"")}catch{}if(!NR(k))return b.json({error:"a local http URL is required"},400);let P=[...A].find(N=>N.inEditor);return await P?.open(k),b.json({opened:!!P,pages:A.count})})),x.use("/__stop",$),x.post("/__stop",async b=>{if(b.req.header("sec-fetch-site")||b.req.header("origin"))return b.text("Forbidden: browser request",403);let k="close";try{let N=await b.req.json();(N?.pages==="keep"||N?.pages==="close")&&(k=N.pages)}catch{}let P=k==="close"?await A.closeAll("stopped"):{told:0,gone:0};return E&&setTimeout(()=>{E({pages:k})},50),b.json({closed:P.gone,stuck:P.told-P.gone,exiting:!!E})}),x.get("/__pages",b=>b.json({pages:A.count})),x.notFound(async b=>{if(b.req.method!=="GET")return b.text("Not Found",404);let k=new URL(b.req.url);return bv(k.pathname,k.search)?ri(b,"https://esm.sh"+k.pathname+k.search):b.text("Not Found",404)});let Gt=TR({fetch:x.fetch,port:s,hostname:_R});return Gt.listening||await new Promise((b,k)=>{let P=N=>k(N);Gt.once("error",P),Gt.once("listening",()=>{Gt.removeListener("error",P),b()})}),{port:s,close:()=>Gt.close(),requestPage:_e,closePages:b=>A.closeAll(b),pageCount:()=>A.count}}function vf(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 kv(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 Tv(decodeURIComponent(s.slice(e.length)),t)??r.text("Not Found",404)}catch{return r.text("Not Found",404)}})}async function Tv(n,e,t={}){let r=sa(n,e),s=await Sf.readFile(r).catch(()=>{});if(s)return new Response(s,{headers:{"Content-Type":zf(r),...t}})}Re();an();async function Za(n){let{port:e,portNote:t,makeServerOptions:r,makeEntry:s,displayName:i,waitTarget:o,stopLog:a}=n,l=`http://localhost:${e}`,c=s(e,l),d=[],u,f=!1,p=async h=>{if(!f){f=!0,console.log(`
|
|
2789
2842
|
Shutting down...`),(h?.pages??(me(c)?"keep":"close"))==="close"&&await u?.closePages("stopped"),u?.close();for(let y of d)try{await y()}catch{}a(),await ln(process.pid),process.exit(0)}},m=await Av({...r(e),onStop:p}).catch(async h=>{if(h?.code!=="EADDRINUSE")throw h;return cu(e)});return u=m,await yu(c),console.log(`
|
|
2790
2843
|
${i}`),console.log(` ${l}`),t&&console.log(` ${t}`),process.on("SIGINT",()=>{p()}),process.on("SIGTERM",()=>{p()}),{port:e,url:l,pageCount:()=>m.pageCount(),async handOver({mode:h,fresh:y,replacedLive:E}){if(h==="none")return;let T={fresh:y,external:E?"never":h==="window"?"force":"follow"},_=await m.requestPage(T);_.how==="attached"?console.log(` Reusing the open browser tab.
|
|
2791
2844
|
`):_.how==="editor"?console.log(` Opened in VS Code via ${_.via}.
|
|
@@ -2794,11 +2847,11 @@ Shutting down...`),(h?.pages??(me(c)?"keep":"close"))==="close"&&await u?.closeP
|
|
|
2794
2847
|
Share ${l}, and wake on the arrival:
|
|
2795
2848
|
typebulb wait ${o} --match "${Xe.connected}"
|
|
2796
2849
|
`)},onCleanup(h){d.push(h)}}}an();import BR from"chokidar";var DR={persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50}};function Vt(n){let{target:e,onChange:t,events:r="change",debounceMs:s=150}=n,i,o=BR.watch(e,DR);o.on("error",l=>console.warn(`watch: ${l instanceof Error?l.message:l} \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()}}Re();et();sr();async function Pv(n,e,t,r){e.port!==void 0&&(console.error("--port isn't supported when running a bulb: a bulb keeps its assigned project port across runs, and moving it strands the open tab."),console.error("It applies to `typebulb agent`. Run the bulb with no --port; `typebulb logs` prints the URL it kept."),process.exit(1));let s=process.cwd(),i=bs(process.pid),o=e.watch?new jR:void 0,a=$e(e.mode),l=(await on(process.cwd()))(n),c=await Hn({kind:"bulb",file:n},process.cwd()),d=await Oo(n,c);d.length&&console.log(`Replacing the running server for this bulb (pid ${d.map(de=>de.pid).join(", ")})`);let u=d.length>0||Date.now()-l<yy,{port:f,note:p}=await xo({target:{kind:"bulb",file:n},cwd:process.cwd()});c!==void 0&&f!==c&&u&&(console.error(`
|
|
2797
|
-
Port ${c} is this bulb's, and a page of it may be waiting there, but something else took it.`),console.error("Free that port and relaunch; starting elsewhere would leave that page running with no way to reach it."),process.exit(1));let m=0,h=()=>console.log(mu(++m));h(),e.batch&&await fr(n,e.batch),console.log(`Loading ${On.basename(n)}...`);let{html:y,bulb:E,serverExports:T}=await id(n,e.watch,e.trust,r,e.batch);Ft(a,n,E.server);let _=[...e.batch?[Jt(n,e.batch)]:[],Jt(n)],x=pr(On.resolve(n)),I=e.trust?void 0:hr(E),{port:R,onCleanup:$,handOver:A,pageCount:
|
|
2850
|
+
Port ${c} is this bulb's, and a page of it may be waiting there, but something else took it.`),console.error("Free that port and relaunch; starting elsewhere would leave that page running with no way to reach it."),process.exit(1));let m=0,h=()=>console.log(mu(++m));h(),e.batch&&await fr(n,e.batch),console.log(`Loading ${On.basename(n)}...`);let{html:y,bulb:E,serverExports:T}=await id(n,e.watch,e.trust,r,e.batch);Ft(a,n,E.server);let _=[...e.batch?[Jt(n,e.batch)]:[],Jt(n)],x=pr(On.resolve(n)),I=e.trust?void 0:hr(E),{port:R,onCleanup:$,handOver:A,pageCount:K}=await Za({port:f,portNote:p,displayName:E.name,stopLog:i,makeServerOptions:de=>({getHtml:()=>y,basePath:s,fsBase:qt(n,e.batch),port:de,reloadEmitter:o,sendChannel:!0,getServerExports:()=>T,getBulbBlocks:()=>({infer:E.infer,insight:E.insight,code:E.code,config:E.config,data:E.data}),saveInferenceResult:async(_e,be)=>{let te=await zt.readFile(n,"utf-8");_e!==void 0&&(te=Cr(te,"data",_e.join(zm))),be!==void 0&&(te=Cr(te,"insight",be)),await zt.writeFile(n,te)},localOverride:r?{name:r.name,serveDir:r.serveDir}:void 0,bulbAssets:{dirs:_,remoteBase:x&&di(x.userSlug,x.slug)},sourceFile:n,bulbKey:gs(n),trusted:e.trust,trustHint:t}),makeEntry:(de,_e)=>({pid:process.pid,port:de,url:_e,file:n,cwd:process.cwd(),startedAt:Date.now(),trust:e.trust,batch:e.batch,mode:e.mode,predicted:I}),waitTarget:On.relative(process.cwd(),n)||On.basename(n)});e.trust?console.log(" trust: granted (filesystem, AI, server.ts enabled)"):console.log(I?` trust: restricted \u2014 this bulb appears to use ${I}; re-run with --trust to enable it:
|
|
2798
2851
|
${t}
|
|
2799
2852
|
`:` trust: restricted \u2014 re-run with --trust to enable filesystem / AI / server.ts
|
|
2800
2853
|
`),e.watch&&console.log(` Watching for changes...
|
|
2801
|
-
`);let Q,Z,F=()=>{
|
|
2854
|
+
`);let Q,Z,F=()=>{K()===0&&console.log(" No page attached \u2014 nothing reloaded; this change is not live."),o?.emit("reload")},ye=de=>{console.log(de),h(),F()};if(e.watch&&o){let de=0,_e=Promise.resolve();if(Q=Vt({target:n,onChange:()=>{let be=++de;_e=_e.then(async()=>{if(be===de)try{console.log("Recompiling...");let te=await id(n,!0,e.trust,r,e.batch);y=te.html,T=te.serverExports,E=te.bulb,te.buildError||h(),F()}catch(te){console.error("Recompile failed:",te)}})}}),r){let{name:be,serveDir:te}=r;Z=Vt({target:te,events:"all",onChange:()=>ye(`Local package '${be}' changed.`)})}for(let be of _)await zt.stat(be).then(te=>te.isDirectory()).catch(()=>!1)&&$(Vt({target:be,events:"all",onChange:()=>ye("Assets changed.")}))}Q&&$(Q),Z&&$(Z),$(()=>zt.rm(sd(n),{force:!0})),await A({mode:e.open,fresh:!u,replacedLive:d.some(de=>de.port===R)})}ht();import{readFileSync as xf,copyFileSync as UR,existsSync as qR}from"fs";import*as pe from"path";import{fileURLToPath as JR}from"url";import{EventEmitter as KR}from"events";import WR from"open";an();Re();sr();var kf=n=>`/agents/${n}/client.js`,FR=`
|
|
2802
2855
|
(() => {
|
|
2803
2856
|
const api = async (name, ...args) => {
|
|
2804
2857
|
const resp = await fetch('/__api/' + name, {
|
|
@@ -2860,7 +2913,7 @@ ${FR}
|
|
|
2860
2913
|
</body>
|
|
2861
2914
|
</html>`}async function _v(n){let e=process.cwd(),t=n.agentTarget;vw(t)||(console.error(`Unknown agent '${t}'. Known: ${Er().join(", ")}.`),process.exit(1));let r=await Po(e,t);if(r){console.log(`Mirror '${t}' is already running for this project:
|
|
2862
2915
|
${r.url}`),n.open==="window"&&await WR(r.url);return}let s=bs(process.pid),i=n.watch?new KR:void 0,o=$e(n.mode),a=await kw(t),l=a.displayName||`${t} mirror`;Ft(o,pe.join(e,"mirror"));let c=pe.dirname(JR(import.meta.url)),d=pe.join(c,"agents",t),u=pe.join(c,"..","cli","agents"),f=pe.join(d,"styles.css"),p=pe.join(d,"katex.min.css"),m=pe.join(d,"index.html"),h=()=>Ov({name:l,agent:t,styles:xf(f,"utf8"),katex:xf(p,"utf8"),mountHtml:xf(m,"utf8"),watch:n.watch}),{port:y,note:E}=await xo({explicit:n.port,target:{kind:"mirror",agent:t},cwd:e}),{port:T,url:_,onCleanup:x,handOver:I,pageCount:R}=await Za({port:y,portNote:E,displayName:l,stopLog:s,waitTarget:"agent",makeServerOptions:Z=>({getHtml:h,basePath:e,port:Z,reloadEmitter:i,getServerExports:()=>a,trusted:!0,staticAssets:{mount:`${pe.posix.dirname(kf(t))}/`,dir:d}}),makeEntry:(Z,F)=>({pid:process.pid,port:Z,url:F,file:`agent:${t}`,cwd:e,startedAt:Date.now(),trust:!0,agent:t})});n.watch&&console.log(` Watching for changes...
|
|
2863
|
-
`);let $=pe.join(u,t,"client"),A=pe.join(u,"core","client");async function
|
|
2916
|
+
`);let $=pe.join(u,t,"client"),A=pe.join(u,"core","client");async function K(){await(await import("esbuild")).build({entryPoints:[pe.join($,"index.ts")],bundle:!0,platform:"browser",format:"esm",outfile:pe.join(d,"client.js")});for(let F of["styles.css","index.html","typebulb.png","typebulb-inv.png"])UR(pe.join(A,F),pe.join(d,F))}let Q;if(n.watch&&i){let Z=qR($),F=!1;Q=Vt({target:Z?u:d,events:"all",onChange:async()=>{if(!F){F=!0;try{Z&&await K(),console.log(R()?`Mirror rebuilt. Reloading.
|
|
2864
2917
|
`:`Mirror rebuilt. No tab open on it \u2014 nobody is reading this.
|
|
2865
2918
|
`),i.emit("reload")}catch(ye){console.error("Mirror rebuild failed:",ye instanceof Error?ye.message:ye)}finally{F=!1}}}})}await I({mode:n.open,fresh:!1,replacedLive:!1}),x(()=>a.shutdownSwitcher?.()),x(()=>a.shutdownComposer?.()),Q&&x(Q)}ht();rt();import*as Cv from"path";async function Rv(n,e,t,r,s){let i=$e(t),o=!1;s&&await fr(n,s);let a=async()=>{let{bulb:l,config:c}=await ze(n);o||(Ft(i,n,l.server),o=!0),await Ms(l.server,n,r,c.dependencies,s)};if(console.log(`Running ${Cv.basename(n)}...`),await a(),e){console.log(`Watching for changes...
|
|
2866
2919
|
`);let l=0,c=Promise.resolve();Vt({target:n,onChange:()=>{let d=++l;c=c.then(async()=>{if(d===l)try{console.log("Re-running..."),await a()}catch(u){console.error("Error:",u)}})}})}}ht();rt();import{Console as HR}from"node:console";Re();async function $v(n,e,t,r,s){XR();try{let p=cn(await X(),n)[0];p&&(ys(p.pid,Ke(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=$e(t),{bulb:o,config:a}=await ze(n);o.server||ni("This bulb has no **server.ts** block; nothing to call."),Ft(i,n,o.server),s&&await fr(n,s);let l;try{l=await Ms(o.server,n,r,a.dependencies,s)}catch(p){ni(p instanceof Error?p.message:String(p))}let c=Xa(l,e.fn);if(!c){let p=[...Object.keys(l).filter(m=>typeof l[m]=="function"),...Object.keys(Ga)];ni(`Function '${e.fn}' not found. Available: ${p.length?p.join(", "):"(none)"}.`)}let d=await YR(e);if(Qa(c)){try{for await(let p of c(...d))await Nv(JSON.stringify(p,Lv)+`
|