@north-light/crouter 0.3.308 → 0.3.309

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.
Files changed (45) hide show
  1. package/dist/clients/attach/viewer.js +9 -9
  2. package/dist/commands/__tests__/node-message.test.js +13 -0
  3. package/dist/commands/canvas-history/grep.js +1 -1
  4. package/dist/commands/canvas-history/read.js +1 -1
  5. package/dist/commands/canvas-history/search.js +1 -1
  6. package/dist/commands/memory/__tests__/command-selector-and-mutation-guards.test.js +20 -0
  7. package/dist/commands/memory/edit.js +8 -11
  8. package/dist/commands/node-inspect-artifacts.js +2 -2
  9. package/dist/commands/push.js +1 -1
  10. package/dist/core/__tests__/canvas-inbox-watcher.test.js +3 -3
  11. package/dist/core/__tests__/human-deliver.test.js +1 -1
  12. package/dist/core/__tests__/integration/broker-wedge-supervision.test.d.ts +1 -0
  13. package/dist/core/__tests__/integration/broker-wedge-supervision.test.js +102 -0
  14. package/dist/core/__tests__/integration/refresh-stall-recycle.test.js +68 -2
  15. package/dist/core/__tests__/seam/inbox-reference-guidance.test.d.ts +1 -0
  16. package/dist/core/__tests__/seam/inbox-reference-guidance.test.js +70 -0
  17. package/dist/core/canvas/__tests__/session-window.test.d.ts +1 -0
  18. package/dist/core/canvas/__tests__/session-window.test.js +70 -0
  19. package/dist/core/canvas/browse/app.js +52 -27
  20. package/dist/core/canvas/browse/render.js +11 -2
  21. package/dist/core/canvas/render-source.js +63 -25
  22. package/dist/core/command.js +15 -0
  23. package/dist/core/feed/inbox.js +6 -4
  24. package/dist/core/runtime/bearings-render.js +3 -3
  25. package/dist/core/runtime/broker/inbox.js +6 -4
  26. package/dist/core/runtime/fleet.js +1 -1
  27. package/dist/core/runtime/placement.d.ts +1 -1
  28. package/dist/core/runtime/placement.js +1 -1
  29. package/dist/core/runtime/tmux-driver.d.ts +7 -0
  30. package/dist/core/runtime/tmux-driver.js +20 -0
  31. package/dist/core/substrate/on-read.d.ts +6 -4
  32. package/dist/core/substrate/on-read.js +14 -6
  33. package/dist/core/substrate/surface-match.d.ts +12 -4
  34. package/dist/core/substrate/surface-match.js +19 -10
  35. package/dist/daemon/api/handlers/canvas.js +3 -3
  36. package/dist/daemon/reconcilers/broker-supervision.d.ts +14 -2
  37. package/dist/daemon/reconcilers/broker-supervision.js +109 -57
  38. package/dist/daemon/reconcilers/storage-maintenance.d.ts +5 -0
  39. package/dist/daemon/reconcilers/storage-maintenance.js +31 -8
  40. package/dist/pi-extensions/__tests__/pre-command-gate.test.js +10 -10
  41. package/dist/pi-extensions/canvas-doc-substrate.js +11 -5
  42. package/dist/shared/generated-context.d.ts +2 -0
  43. package/dist/shared/generated-context.js +6 -0
  44. package/package.json +1 -1
  45. package/runtime.lock.json +5 -5
@@ -1521,8 +1521,8 @@ ${n.comment}`:n.comment}this.doc.range[2]=n.offset;break}default:this.errors.pus
1521
1521
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
1522
1522
  `,n)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else if(n.sep)n.sep.push(this.sourceToken);else{if(this.atIndentedComment(n.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){cHe(s,n.start),s.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,s=i&&(n.sep||n.explicitKey)&&this.type!=="seq-item-ind",a=[];if(s&&n.sep&&!n.value){let u=[];for(let p=0;p<n.sep.length;++p){let f=n.sep[p];switch(f.type){case"newline":u.push(p);break;case"space":break;case"comment":f.indent>e.indent&&(u.length=0);break;default:u.length=0}}u.length>=2&&(a=n.sep.splice(u[1]))}switch(this.type){case"anchor":case"tag":s||n.value?(a.push(this.sourceToken),e.items.push({start:a}),this.onKeyLine=!0):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"explicit-key-ind":!n.sep&&!n.explicitKey?(n.start.push(this.sourceToken),n.explicitKey=!0):s||n.value?(a.push(this.sourceToken),e.items.push({start:a,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(n.explicitKey)if(n.sep)if(n.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(fq(n.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(Ecr(n.key)&&!fq(n.sep,"newline")){let u=ede(n.start),p=n.key,f=n.sep;f.push(this.sourceToken),delete n.key,delete n.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:u,key:p,sep:f}]})}else a.length>0?n.sep=n.sep.concat(a,this.sourceToken):n.sep.push(this.sourceToken);else if(fq(n.start,"newline"))Object.assign(n,{key:null,sep:[this.sourceToken]});else{let u=ede(n.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:u,key:null,sep:[this.sourceToken]}]})}else n.sep?n.value||s?e.items.push({start:a,key:null,sep:[this.sourceToken]}):fq(n.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let u=this.flowScalar(this.type);s||n.value?(e.items.push({start:a,key:u,sep:[]}),this.onKeyLine=!0):n.sep?this.stack.push(u):(Object.assign(n,{key:u,sep:[]}),this.onKeyLine=!0);return}default:{let u=this.startBlockValue(e);if(u){if(u.type==="block-seq"){if(!n.explicitKey&&n.sep&&!fq(n.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 i&&e.items.push({start:a});this.stack.push(u);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let n=e.items[e.items.length-1];switch(this.type){case"newline":if(n.value){let i="end"in n.value?n.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else n.start.push(this.sourceToken);return;case"space":case"comment":if(n.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(n.start,e.indent)){let s=e.items[e.items.length-2]?.value?.end;if(Array.isArray(s)){cHe(s,n.start),s.push(this.sourceToken),e.items.pop();return}}n.start.push(this.sourceToken)}return;case"anchor":case"tag":if(n.value||this.indent<=e.indent)break;n.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;n.value||fq(n.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let n=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!n||n.sep?e.items.push({start:[this.sourceToken]}):n.start.push(this.sourceToken);return;case"map-value-ind":!n||n.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):Object.assign(n,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!n||n.value?e.items.push({start:[this.sourceToken]}):n.sep?n.sep.push(this.sourceToken):n.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);!n||n.value?e.items.push({start:[],key:s,sep:[]}):n.sep?this.stack.push(s):Object.assign(n,{key:s,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let s=aHe(i),a=ede(s);Scr(e);let u=e.end.splice(1,e.end.length);u.push(this.sourceToken);let p={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:a,key:e,sep:u}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=p}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let n=this.source.indexOf(`
1523
1523
  `)+1;for(;n!==0;)this.onNewLine(this.offset+n),n=this.source.indexOf(`
1524
- `,n)+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 n=aHe(e),i=ede(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=aHe(e),i=ede(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.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())}}};Ccr.Parser=K$t});var Dcr=an(yCe=>{"use strict";var Tcr=L$t(),mgs=lCe(),_Ce=dCe(),hgs=O5t(),ggs=Eh(),_gs=J$t(),kcr=Y$t();function Icr(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new _gs.LineCounter||null,prettyErrors:e}}function ygs(t,e={}){let{lineCounter:n,prettyErrors:i}=Icr(e),s=new kcr.Parser(n?.addNewLine),a=new Tcr.Composer(e),u=Array.from(a.compose(s.parse(t)));if(i&&n)for(let p of u)p.errors.forEach(_Ce.prettifyError(t,n)),p.warnings.forEach(_Ce.prettifyError(t,n));return u.length>0?u:Object.assign([],{empty:!0},a.streamInfo())}function Pcr(t,e={}){let{lineCounter:n,prettyErrors:i}=Icr(e),s=new kcr.Parser(n?.addNewLine),a=new Tcr.Composer(e),u=null;for(let p of a.compose(s.parse(t),!0,t.length))if(!u)u=p;else if(u.options.logLevel!=="silent"){u.errors.push(new _Ce.YAMLParseError(p.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(u.errors.forEach(_Ce.prettifyError(t,n)),u.warnings.forEach(_Ce.prettifyError(t,n))),u}function bgs(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let s=Pcr(t,n);if(!s)return null;if(s.warnings.forEach(a=>hgs.warn(s.options.logLevel,a)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:i},n))}function Ags(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(t===void 0){let{keepUndefined:s}=n??e??{};if(!s)return}return ggs.isDocument(t)&&!i?t.toString(n):new mgs.Document(t,i,n).toString(n)}yCe.parse=bgs;yCe.parseAllDocuments=ygs;yCe.parseDocument=Pcr;yCe.stringify=Ags});var DX=an(Hg=>{"use strict";var vgs=L$t(),xgs=lCe(),wgs=_$t(),X$t=dCe(),Sgs=z1e(),mq=Eh(),Egs=lq(),Cgs=Yv(),Tgs=pq(),kgs=dq(),Igs=sHe(),Pgs=z$t(),Dgs=J$t(),Rgs=Y$t(),lHe=Dcr(),Rcr=Q1e();Hg.Composer=vgs.Composer;Hg.Document=xgs.Document;Hg.Schema=wgs.Schema;Hg.YAMLError=X$t.YAMLError;Hg.YAMLParseError=X$t.YAMLParseError;Hg.YAMLWarning=X$t.YAMLWarning;Hg.Alias=Sgs.Alias;Hg.isAlias=mq.isAlias;Hg.isCollection=mq.isCollection;Hg.isDocument=mq.isDocument;Hg.isMap=mq.isMap;Hg.isNode=mq.isNode;Hg.isPair=mq.isPair;Hg.isScalar=mq.isScalar;Hg.isSeq=mq.isSeq;Hg.Pair=Egs.Pair;Hg.Scalar=Cgs.Scalar;Hg.YAMLMap=Tgs.YAMLMap;Hg.YAMLSeq=kgs.YAMLSeq;Hg.CST=Igs;Hg.Lexer=Pgs.Lexer;Hg.LineCounter=Dgs.LineCounter;Hg.Parser=Rgs.Parser;Hg.parse=lHe.parse;Hg.parseAllDocuments=lHe.parseAllDocuments;Hg.parseDocument=lHe.parseDocument;Hg.stringify=lHe.stringify;Hg.visit=Rcr.visit;Hg.visitAsync=Rcr.visitAsync});var lfr=an((jIc,cfr)=>{var bq=Or("constants"),sws=process.cwd,bJe=null,ows=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return bJe||(bJe=sws.call(process)),bJe};try{process.cwd()}catch{}typeof process.chdir=="function"&&(PUt=process.chdir,process.chdir=function(t){bJe=null,PUt.call(process,t)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,PUt));var PUt;cfr.exports=aws;function aws(t){bq.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&e(t),t.lutimes||n(t),t.chown=a(t.chown),t.fchown=a(t.fchown),t.lchown=a(t.lchown),t.chmod=i(t.chmod),t.fchmod=i(t.fchmod),t.lchmod=i(t.lchmod),t.chownSync=u(t.chownSync),t.fchownSync=u(t.fchownSync),t.lchownSync=u(t.lchownSync),t.chmodSync=s(t.chmodSync),t.fchmodSync=s(t.fchmodSync),t.lchmodSync=s(t.lchmodSync),t.stat=p(t.stat),t.fstat=p(t.fstat),t.lstat=p(t.lstat),t.statSync=f(t.statSync),t.fstatSync=f(t.fstatSync),t.lstatSync=f(t.lstatSync),t.chmod&&!t.lchmod&&(t.lchmod=function(m,b,x){x&&process.nextTick(x)},t.lchmodSync=function(){}),t.chown&&!t.lchown&&(t.lchown=function(m,b,x,k){k&&process.nextTick(k)},t.lchownSync=function(){}),ows==="win32"&&(t.rename=typeof t.rename!="function"?t.rename:(function(m){function b(x,k,I){var C=Date.now(),D=0;m(x,k,function R(F){if(F&&(F.code==="EACCES"||F.code==="EPERM"||F.code==="EBUSY")&&Date.now()-C<6e4){setTimeout(function(){t.stat(k,function(L,U){L&&L.code==="ENOENT"?m(x,k,R):I(F)})},D),D<100&&(D+=10);return}I&&I(F)})}return Object.setPrototypeOf&&Object.setPrototypeOf(b,m),b})(t.rename)),t.read=typeof t.read!="function"?t.read:(function(m){function b(x,k,I,C,D,R){var F;if(R&&typeof R=="function"){var L=0;F=function(U,Y,V){if(U&&U.code==="EAGAIN"&&L<10)return L++,m.call(t,x,k,I,C,D,F);R.apply(this,arguments)}}return m.call(t,x,k,I,C,D,F)}return Object.setPrototypeOf&&Object.setPrototypeOf(b,m),b})(t.read),t.readSync=typeof t.readSync!="function"?t.readSync:(function(m){return function(b,x,k,I,C){for(var D=0;;)try{return m.call(t,b,x,k,I,C)}catch(R){if(R.code==="EAGAIN"&&D<10){D++;continue}throw R}}})(t.readSync);function e(m){m.lchmod=function(b,x,k){m.open(b,bq.O_WRONLY|bq.O_SYMLINK,x,function(I,C){if(I){k&&k(I);return}m.fchmod(C,x,function(D){m.close(C,function(R){k&&k(D||R)})})})},m.lchmodSync=function(b,x){var k=m.openSync(b,bq.O_WRONLY|bq.O_SYMLINK,x),I=!0,C;try{C=m.fchmodSync(k,x),I=!1}finally{if(I)try{m.closeSync(k)}catch{}else m.closeSync(k)}return C}}function n(m){bq.hasOwnProperty("O_SYMLINK")&&m.futimes?(m.lutimes=function(b,x,k,I){m.open(b,bq.O_SYMLINK,function(C,D){if(C){I&&I(C);return}m.futimes(D,x,k,function(R){m.close(D,function(F){I&&I(R||F)})})})},m.lutimesSync=function(b,x,k){var I=m.openSync(b,bq.O_SYMLINK),C,D=!0;try{C=m.futimesSync(I,x,k),D=!1}finally{if(D)try{m.closeSync(I)}catch{}else m.closeSync(I)}return C}):m.futimes&&(m.lutimes=function(b,x,k,I){I&&process.nextTick(I)},m.lutimesSync=function(){})}function i(m){return m&&function(b,x,k){return m.call(t,b,x,function(I){_(I)&&(I=null),k&&k.apply(this,arguments)})}}function s(m){return m&&function(b,x){try{return m.call(t,b,x)}catch(k){if(!_(k))throw k}}}function a(m){return m&&function(b,x,k,I){return m.call(t,b,x,k,function(C){_(C)&&(C=null),I&&I.apply(this,arguments)})}}function u(m){return m&&function(b,x,k){try{return m.call(t,b,x,k)}catch(I){if(!_(I))throw I}}}function p(m){return m&&function(b,x,k){typeof x=="function"&&(k=x,x=null);function I(C,D){D&&(D.uid<0&&(D.uid+=4294967296),D.gid<0&&(D.gid+=4294967296)),k&&k.apply(this,arguments)}return x?m.call(t,b,x,I):m.call(t,b,I)}}function f(m){return m&&function(b,x){var k=x?m.call(t,b,x):m.call(t,b);return k&&(k.uid<0&&(k.uid+=4294967296),k.gid<0&&(k.gid+=4294967296)),k}}function _(m){if(!m||m.code==="ENOSYS")return!0;var b=!process.getuid||process.getuid()!==0;return!!(b&&(m.code==="EINVAL"||m.code==="EPERM"))}}});var dfr=an((WIc,pfr)=>{var ufr=Or("stream").Stream;pfr.exports=cws;function cws(t){return{ReadStream:e,WriteStream:n};function e(i,s){if(!(this instanceof e))return new e(i,s);ufr.call(this);var a=this;this.path=i,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,s=s||{};for(var u=Object.keys(s),p=0,f=u.length;p<f;p++){var _=u[p];this[_]=s[_]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}t.open(this.path,this.flags,this.mode,function(m,b){if(m){a.emit("error",m),a.readable=!1;return}a.fd=b,a.emit("open",b),a._read()})}function n(i,s){if(!(this instanceof n))return new n(i,s);ufr.call(this),this.path=i,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,s=s||{};for(var a=Object.keys(s),u=0,p=a.length;u<p;u++){var f=a[u];this[f]=s[f]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=t.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var mfr=an((QIc,ffr)=>{"use strict";ffr.exports=uws;var lws=Object.getPrototypeOf||function(t){return t.__proto__};function uws(t){if(t===null||typeof t!="object")return t;if(t instanceof Object)var e={__proto__:lws(t)};else var e=Object.create(null);return Object.getOwnPropertyNames(t).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}});var MUt=an((qIc,NUt)=>{var xb=Or("fs"),pws=lfr(),dws=dfr(),fws=mfr(),AJe=Or("util"),pE,xJe;typeof Symbol=="function"&&typeof Symbol.for=="function"?(pE=Symbol.for("graceful-fs.queue"),xJe=Symbol.for("graceful-fs.previous")):(pE="___graceful-fs.queue",xJe="___graceful-fs.previous");function mws(){}function _fr(t,e){Object.defineProperty(t,pE,{get:function(){return e}})}var UX=mws;AJe.debuglog?UX=AJe.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(UX=function(){var t=AJe.format.apply(AJe,arguments);t="GFS4: "+t.split(/\n/).join(`
1525
- GFS4: `),console.error(t)});xb[pE]||(hfr=global[pE]||[],_fr(xb,hfr),xb.close=(function(t){function e(n,i){return t.call(xb,n,function(s){s||gfr(),typeof i=="function"&&i.apply(this,arguments)})}return Object.defineProperty(e,xJe,{value:t}),e})(xb.close),xb.closeSync=(function(t){function e(n){t.apply(xb,arguments),gfr()}return Object.defineProperty(e,xJe,{value:t}),e})(xb.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){UX(xb[pE]),Or("assert").equal(xb[pE].length,0)}));var hfr;global[pE]||_fr(global,xb[pE]);NUt.exports=DUt(fws(xb));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!xb.__patched&&(NUt.exports=DUt(xb),xb.__patched=!0);function DUt(t){pws(t),t.gracefulify=DUt,t.createReadStream=Y,t.createWriteStream=V;var e=t.readFile;t.readFile=n;function n(ne,he,De){return typeof he=="function"&&(De=he,he=null),We(ne,he,De);function We(Me,ze,wt,yt){return e(Me,ze,function(Re){Re&&(Re.code==="EMFILE"||Re.code==="ENFILE")?dde([We,[Me,ze,wt],Re,yt||Date.now(),Date.now()]):typeof wt=="function"&&wt.apply(this,arguments)})}}var i=t.writeFile;t.writeFile=s;function s(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return i(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var a=t.appendFile;a&&(t.appendFile=u);function u(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return a(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var p=t.copyFile;p&&(t.copyFile=f);function f(ne,he,De,We){return typeof De=="function"&&(We=De,De=0),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return p(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var _=t.readdir;t.readdir=b;var m=/^v[0-5]\./;function b(ne,he,De){typeof he=="function"&&(De=he,he=null);var We=m.test(process.version)?function(wt,yt,Re,je){return _(wt,Me(wt,yt,Re,je))}:function(wt,yt,Re,je){return _(wt,yt,Me(wt,yt,Re,je))};return We(ne,he,De);function Me(ze,wt,yt,Re){return function(je,ct){je&&(je.code==="EMFILE"||je.code==="ENFILE")?dde([We,[ze,wt,yt],je,Re||Date.now(),Date.now()]):(ct&&ct.sort&&ct.sort(),typeof yt=="function"&&yt.call(this,je,ct))}}}if(process.version.substr(0,4)==="v0.8"){var x=dws(t);R=x.ReadStream,L=x.WriteStream}var k=t.ReadStream;k&&(R.prototype=Object.create(k.prototype),R.prototype.open=F);var I=t.WriteStream;I&&(L.prototype=Object.create(I.prototype),L.prototype.open=U),Object.defineProperty(t,"ReadStream",{get:function(){return R},set:function(ne){R=ne},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WriteStream",{get:function(){return L},set:function(ne){L=ne},enumerable:!0,configurable:!0});var C=R;Object.defineProperty(t,"FileReadStream",{get:function(){return C},set:function(ne){C=ne},enumerable:!0,configurable:!0});var D=L;Object.defineProperty(t,"FileWriteStream",{get:function(){return D},set:function(ne){D=ne},enumerable:!0,configurable:!0});function R(ne,he){return this instanceof R?(k.apply(this,arguments),this):R.apply(Object.create(R.prototype),arguments)}function F(){var ne=this;te(ne.path,ne.flags,ne.mode,function(he,De){he?(ne.autoClose&&ne.destroy(),ne.emit("error",he)):(ne.fd=De,ne.emit("open",De),ne.read())})}function L(ne,he){return this instanceof L?(I.apply(this,arguments),this):L.apply(Object.create(L.prototype),arguments)}function U(){var ne=this;te(ne.path,ne.flags,ne.mode,function(he,De){he?(ne.destroy(),ne.emit("error",he)):(ne.fd=De,ne.emit("open",De))})}function Y(ne,he){return new t.ReadStream(ne,he)}function V(ne,he){return new t.WriteStream(ne,he)}var z=t.open;t.open=te;function te(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return z(ze,wt,yt,function(ct,Qt){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}return t}function dde(t){UX("ENQUEUE",t[0].name,t[1]),xb[pE].push(t),RUt()}var vJe;function gfr(){for(var t=Date.now(),e=0;e<xb[pE].length;++e)xb[pE][e].length>2&&(xb[pE][e][3]=t,xb[pE][e][4]=t);RUt()}function RUt(){if(clearTimeout(vJe),vJe=void 0,xb[pE].length!==0){var t=xb[pE].shift(),e=t[0],n=t[1],i=t[2],s=t[3],a=t[4];if(s===void 0)UX("RETRY",e.name,n),e.apply(null,n);else if(Date.now()-s>=6e4){UX("TIMEOUT",e.name,n);var u=n.pop();typeof u=="function"&&u.call(null,i)}else{var p=Date.now()-a,f=Math.max(a-s,1),_=Math.min(f*1.2,100);p>=_?(UX("RETRY",e.name,n),e.apply(null,n.concat([s]))):xb[pE].push(t)}vJe===void 0&&(vJe=setTimeout(RUt,0))}}});var bfr=an((GIc,yfr)=>{function FN(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}yfr.exports=FN;FN.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};FN.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};FN.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1;var i=this,s=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},n);return this._options.unref&&s.unref(),!0};FN.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};FN.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};FN.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};FN.prototype.start=FN.prototype.try;FN.prototype.errors=function(){return this._errors};FN.prototype.attempts=function(){return this._attempts};FN.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,i=0;i<this._errors.length;i++){var s=this._errors[i],a=s.message,u=(t[a]||0)+1;t[a]=u,u>=n&&(e=s,n=u)}return e}});var Afr=an(jX=>{var hws=bfr();jX.operation=function(t){var e=jX.timeouts(t);return new hws(e,{forever:t&&t.forever,unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};jX.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],s=0;s<e.retries;s++)i.push(this.createTimeout(s,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(s,e)),i.sort(function(a,u){return a-u}),i};jX.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};jX.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var i in t)typeof t[i]=="function"&&n.push(i)}for(var s=0;s<n.length;s++){var a=n[s],u=t[a];t[a]=function(f){var _=jX.operation(e),m=Array.prototype.slice.call(arguments,1),b=m.pop();m.push(function(x){_.retry(x)||(x&&(arguments[0]=_.mainError()),b.apply(this,arguments))}),_.attempt(function(){f.apply(t,m)})}.bind(t,u),t[a].options=e}}});var xfr=an((zIc,vfr)=>{vfr.exports=Afr()});var wfr=an((HIc,wJe)=>{wJe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&wJe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&wJe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var kfr=an((JIc,hde)=>{var $0=global.process,WX=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};WX($0)?(Sfr=Or("assert"),fde=wfr(),Efr=/^win/i.test($0.platform),JCe=Or("events"),typeof JCe!="function"&&(JCe=JCe.EventEmitter),$0.__signal_exit_emitter__?oS=$0.__signal_exit_emitter__:(oS=$0.__signal_exit_emitter__=new JCe,oS.count=0,oS.emitted={}),oS.infinite||(oS.setMaxListeners(1/0),oS.infinite=!0),hde.exports=function(t,e){if(!WX(global.process))return function(){};Sfr.equal(typeof t,"function","a callback must be provided for exit handler"),mde===!1&&OUt();var n="exit";e&&e.alwaysLast&&(n="afterexit");var i=function(){oS.removeListener(n,t),oS.listeners("exit").length===0&&oS.listeners("afterexit").length===0&&SJe()};return oS.on(n,t),i},SJe=function(){!mde||!WX(global.process)||(mde=!1,fde.forEach(function(e){try{$0.removeListener(e,EJe[e])}catch{}}),$0.emit=CJe,$0.reallyExit=FUt,oS.count-=1)},hde.exports.unload=SJe,QX=function(e,n,i){oS.emitted[e]||(oS.emitted[e]=!0,oS.emit(e,n,i))},EJe={},fde.forEach(function(t){EJe[t]=function(){if(WX(global.process)){var n=$0.listeners(t);n.length===oS.count&&(SJe(),QX("exit",null,t),QX("afterexit",null,t),Efr&&t==="SIGHUP"&&(t="SIGINT"),$0.kill($0.pid,t))}}}),hde.exports.signals=function(){return fde},mde=!1,OUt=function(){mde||!WX(global.process)||(mde=!0,oS.count+=1,fde=fde.filter(function(e){try{return $0.on(e,EJe[e]),!0}catch{return!1}}),$0.emit=Tfr,$0.reallyExit=Cfr)},hde.exports.load=OUt,FUt=$0.reallyExit,Cfr=function(e){WX(global.process)&&($0.exitCode=e||0,QX("exit",$0.exitCode,null),QX("afterexit",$0.exitCode,null),FUt.call($0,$0.exitCode))},CJe=$0.emit,Tfr=function(e,n){if(e==="exit"&&WX(global.process)){n!==void 0&&($0.exitCode=n);var i=CJe.apply(this,arguments);return QX("exit",$0.exitCode,null),QX("afterexit",$0.exitCode,null),i}else return CJe.apply(this,arguments)}):hde.exports=function(){return function(){}};var Sfr,fde,Efr,JCe,oS,SJe,QX,EJe,mde,OUt,FUt,Cfr,CJe,Tfr});var Pfr=an((KIc,LUt)=>{"use strict";var Ifr=Symbol();function gws(t,e,n){let i=e[Ifr];if(i)return e.stat(t,(a,u)=>{if(a)return n(a);n(null,u.mtime,i)});let s=new Date(Math.ceil(Date.now()/1e3)*1e3+5);e.utimes(t,s,s,a=>{if(a)return n(a);e.stat(t,(u,p)=>{if(u)return n(u);let f=p.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(e,Ifr,{value:f}),n(null,p.mtime,f)})})}function _ws(t){let e=Date.now();return t==="s"&&(e=Math.ceil(e/1e3)*1e3),new Date(e)}LUt.exports.probe=gws;LUt.exports.getMtime=_ws});var Ofr=an((YIc,YCe)=>{"use strict";var yws=Or("path"),UUt=MUt(),bws=xfr(),Aws=kfr(),Dfr=Pfr(),K8={};function KCe(t,e){return e.lockfilePath||`${t}.lock`}function jUt(t,e,n){if(!e.realpath)return n(null,yws.resolve(t));e.fs.realpath(t,n)}function $Ut(t,e,n){let i=KCe(t,e);e.fs.mkdir(i,s=>{if(!s)return Dfr.probe(i,e.fs,(a,u,p)=>{if(a)return e.fs.rmdir(i,()=>{}),n(a);n(null,u,p)});if(s.code!=="EEXIST")return n(s);if(e.stale<=0)return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:t}));e.fs.stat(i,(a,u)=>{if(a)return a.code==="ENOENT"?$Ut(t,{...e,stale:0},n):n(a);if(!Rfr(u,e))return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:t}));Nfr(t,e,p=>{if(p)return n(p);$Ut(t,{...e,stale:0},n)})})})}function Rfr(t,e){return t.mtime.getTime()<Date.now()-e.stale}function Nfr(t,e,n){e.fs.rmdir(KCe(t,e),i=>{if(i&&i.code!=="ENOENT")return n(i);n()})}function TJe(t,e){let n=K8[t];n.updateTimeout||(n.updateDelay=n.updateDelay||e.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,e.fs.stat(n.lockfilePath,(i,s)=>{let a=n.lastUpdate+e.stale<Date.now();if(i)return i.code==="ENOENT"||a?BUt(t,n,Object.assign(i,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,TJe(t,e));if(!(n.mtime.getTime()===s.mtime.getTime()))return BUt(t,n,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let p=Dfr.getMtime(n.mtimePrecision);e.fs.utimes(n.lockfilePath,p,p,f=>{let _=n.lastUpdate+e.stale<Date.now();if(!n.released){if(f)return f.code==="ENOENT"||_?BUt(t,n,Object.assign(f,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,TJe(t,e));n.mtime=p,n.lastUpdate=Date.now(),n.updateDelay=null,TJe(t,e)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function BUt(t,e,n){e.released=!0,e.updateTimeout&&clearTimeout(e.updateTimeout),K8[t]===e&&delete K8[t],e.options.onCompromised(n)}function vws(t,e,n){e={stale:1e4,update:null,realpath:!0,retries:0,fs:UUt,onCompromised:i=>{throw i},...e},e.retries=e.retries||0,e.retries=typeof e.retries=="number"?{retries:e.retries}:e.retries,e.stale=Math.max(e.stale||0,2e3),e.update=e.update==null?e.stale/2:e.update||0,e.update=Math.max(Math.min(e.update,e.stale/2),1e3),jUt(t,e,(i,s)=>{if(i)return n(i);let a=bws.operation(e.retries);a.attempt(()=>{$Ut(s,e,(u,p,f)=>{if(a.retry(u))return;if(u)return n(a.mainError());let _=K8[s]={lockfilePath:KCe(s,e),mtime:p,mtimePrecision:f,options:e,lastUpdate:Date.now()};TJe(s,e),n(null,m=>{if(_.released)return m&&m(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));Mfr(s,{...e,realpath:!1},m)})})})})}function Mfr(t,e,n){e={fs:UUt,realpath:!0,...e},jUt(t,e,(i,s)=>{if(i)return n(i);let a=K8[s];if(!a)return n(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));a.updateTimeout&&clearTimeout(a.updateTimeout),a.released=!0,delete K8[s],Nfr(s,e,n)})}function xws(t,e,n){e={stale:1e4,realpath:!0,fs:UUt,...e},e.stale=Math.max(e.stale||0,2e3),jUt(t,e,(i,s)=>{if(i)return n(i);e.fs.stat(KCe(s,e),(a,u)=>a?a.code==="ENOENT"?n(null,!1):n(a):n(null,!Rfr(u,e)))})}function wws(){return K8}Aws(()=>{for(let t in K8){let e=K8[t].options;try{e.fs.rmdirSync(KCe(t,e))}catch{}}});YCe.exports.lock=vws;YCe.exports.unlock=Mfr;YCe.exports.check=xws;YCe.exports.getLocks=wws});var Lfr=an((XIc,Ffr)=>{"use strict";var Sws=MUt();function Ews(t){let e=["mkdir","realpath","stat","rmdir","utimes"],n={...t};return e.forEach(i=>{n[i]=(...s)=>{let a=s.pop(),u;try{u=t[`${i}Sync`](...s)}catch(p){return a(p)}a(null,u)}}),n}function Cws(t){return(...e)=>new Promise((n,i)=>{e.push((s,a)=>{s?i(s):n(a)}),t(...e)})}function Tws(t){return(...e)=>{let n,i;if(e.push((s,a)=>{n=s,i=a}),t(...e),n)throw n;return i}}function kws(t){if(t={...t},t.fs=Ews(t.fs||Sws),typeof t.retries=="number"&&t.retries>0||t.retries&&typeof t.retries.retries=="number"&&t.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return t}Ffr.exports={toPromise:Cws,toSync:Tws,toSyncOptions:kws}});var $fr=an((ZIc,Aq)=>{"use strict";var gde=Ofr(),{toPromise:kJe,toSync:IJe,toSyncOptions:WUt}=Lfr();async function Bfr(t,e){let n=await kJe(gde.lock)(t,e);return kJe(n)}function Iws(t,e){let n=IJe(gde.lock)(t,WUt(e));return IJe(n)}function Pws(t,e){return kJe(gde.unlock)(t,e)}function Dws(t,e){return IJe(gde.unlock)(t,WUt(e))}function Rws(t,e){return kJe(gde.check)(t,e)}function Nws(t,e){return IJe(gde.check)(t,WUt(e))}Aq.exports=Bfr;Aq.exports.lock=Bfr;Aq.exports.unlock=Pws;Aq.exports.lockSync=Iws;Aq.exports.unlockSync=Dws;Aq.exports.check=Rws;Aq.exports.checkSync=Nws});function nie(){return process.env.CRTR_PROFILE_ID}function Uj(){return process.env.CRTR_HOME}var _Ts=5*6e4;var yTs=300*1e3;var bTs=60*1e3;function Aun(){let t=process.env.CRTR_PIDFILE;return t!==void 0&&t!==""?t:void 0}function vun(){return process.env.CRTR_NO_DAEMON_AUTOSTART==="1"}var ATs=5*6e4;import{existsSync as Fjr,readFileSync as Ljr}from"node:fs";import{dirname as xun,join as Bjr,parse as $jr}from"node:path";import{fileURLToPath as Ujr}from"node:url";function jjr(t,e){let n=xun(t),i=$jr(n).root;for(;;){let s=Bjr(n,"package.json");if(Fjr(s))try{if(JSON.parse(Ljr(s,"utf8")).name===e)return n}catch{return null}if(n===i)return null;n=xun(n)}}function wun(){let t="@earendil-works/pi-coding-agent",e;try{e=Ujr(import.meta.resolve(t))}catch(i){throw new Error(`crouter install is missing bundled ${t}; reinstall @north-light/crouter. ${i.message}`)}let n=jjr(e,t);if(n===null)throw new Error(`could not locate bundled ${t} package root from ${e}`);return n}try{process.env.PI_PACKAGE_DIR=wun()}catch{}UP();var Qjr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>';function GLe(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Sun(t){let e=GLe(t.title),n=GLe(t.heading),i=GLe(t.message),s=t.details?GLe(t.details):void 0;return`<!doctype html>
1524
+ `,n)+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 n=aHe(e),i=ede(n);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let n=aHe(e),i=ede(n);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,n){return this.type!=="comment"||this.indent<=n?!1:e.every(i=>i.type==="newline"||i.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())}}};Ccr.Parser=K$t});var Dcr=an(yCe=>{"use strict";var Tcr=L$t(),mgs=lCe(),_Ce=dCe(),hgs=O5t(),ggs=Eh(),_gs=J$t(),kcr=Y$t();function Icr(t){let e=t.prettyErrors!==!1;return{lineCounter:t.lineCounter||e&&new _gs.LineCounter||null,prettyErrors:e}}function ygs(t,e={}){let{lineCounter:n,prettyErrors:i}=Icr(e),s=new kcr.Parser(n?.addNewLine),a=new Tcr.Composer(e),u=Array.from(a.compose(s.parse(t)));if(i&&n)for(let p of u)p.errors.forEach(_Ce.prettifyError(t,n)),p.warnings.forEach(_Ce.prettifyError(t,n));return u.length>0?u:Object.assign([],{empty:!0},a.streamInfo())}function Pcr(t,e={}){let{lineCounter:n,prettyErrors:i}=Icr(e),s=new kcr.Parser(n?.addNewLine),a=new Tcr.Composer(e),u=null;for(let p of a.compose(s.parse(t),!0,t.length))if(!u)u=p;else if(u.options.logLevel!=="silent"){u.errors.push(new _Ce.YAMLParseError(p.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&n&&(u.errors.forEach(_Ce.prettifyError(t,n)),u.warnings.forEach(_Ce.prettifyError(t,n))),u}function bgs(t,e,n){let i;typeof e=="function"?i=e:n===void 0&&e&&typeof e=="object"&&(n=e);let s=Pcr(t,n);if(!s)return null;if(s.warnings.forEach(a=>hgs.warn(s.options.logLevel,a)),s.errors.length>0){if(s.options.logLevel!=="silent")throw s.errors[0];s.errors=[]}return s.toJS(Object.assign({reviver:i},n))}function Ags(t,e,n){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:n===void 0&&e&&(n=e),typeof n=="string"&&(n=n.length),typeof n=="number"){let s=Math.round(n);n=s<1?void 0:s>8?{indent:8}:{indent:s}}if(t===void 0){let{keepUndefined:s}=n??e??{};if(!s)return}return ggs.isDocument(t)&&!i?t.toString(n):new mgs.Document(t,i,n).toString(n)}yCe.parse=bgs;yCe.parseAllDocuments=ygs;yCe.parseDocument=Pcr;yCe.stringify=Ags});var DX=an(Hg=>{"use strict";var vgs=L$t(),xgs=lCe(),wgs=_$t(),X$t=dCe(),Sgs=z1e(),mq=Eh(),Egs=lq(),Cgs=Yv(),Tgs=pq(),kgs=dq(),Igs=sHe(),Pgs=z$t(),Dgs=J$t(),Rgs=Y$t(),lHe=Dcr(),Rcr=Q1e();Hg.Composer=vgs.Composer;Hg.Document=xgs.Document;Hg.Schema=wgs.Schema;Hg.YAMLError=X$t.YAMLError;Hg.YAMLParseError=X$t.YAMLParseError;Hg.YAMLWarning=X$t.YAMLWarning;Hg.Alias=Sgs.Alias;Hg.isAlias=mq.isAlias;Hg.isCollection=mq.isCollection;Hg.isDocument=mq.isDocument;Hg.isMap=mq.isMap;Hg.isNode=mq.isNode;Hg.isPair=mq.isPair;Hg.isScalar=mq.isScalar;Hg.isSeq=mq.isSeq;Hg.Pair=Egs.Pair;Hg.Scalar=Cgs.Scalar;Hg.YAMLMap=Tgs.YAMLMap;Hg.YAMLSeq=kgs.YAMLSeq;Hg.CST=Igs;Hg.Lexer=Pgs.Lexer;Hg.LineCounter=Dgs.LineCounter;Hg.Parser=Rgs.Parser;Hg.parse=lHe.parse;Hg.parseAllDocuments=lHe.parseAllDocuments;Hg.parseDocument=lHe.parseDocument;Hg.stringify=lHe.stringify;Hg.visit=Rcr.visit;Hg.visitAsync=Rcr.visitAsync});var lfr=an((qIc,cfr)=>{var bq=Or("constants"),sws=process.cwd,bJe=null,ows=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){return bJe||(bJe=sws.call(process)),bJe};try{process.cwd()}catch{}typeof process.chdir=="function"&&(PUt=process.chdir,process.chdir=function(t){bJe=null,PUt.call(process,t)},Object.setPrototypeOf&&Object.setPrototypeOf(process.chdir,PUt));var PUt;cfr.exports=aws;function aws(t){bq.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)&&e(t),t.lutimes||n(t),t.chown=a(t.chown),t.fchown=a(t.fchown),t.lchown=a(t.lchown),t.chmod=i(t.chmod),t.fchmod=i(t.fchmod),t.lchmod=i(t.lchmod),t.chownSync=u(t.chownSync),t.fchownSync=u(t.fchownSync),t.lchownSync=u(t.lchownSync),t.chmodSync=s(t.chmodSync),t.fchmodSync=s(t.fchmodSync),t.lchmodSync=s(t.lchmodSync),t.stat=p(t.stat),t.fstat=p(t.fstat),t.lstat=p(t.lstat),t.statSync=f(t.statSync),t.fstatSync=f(t.fstatSync),t.lstatSync=f(t.lstatSync),t.chmod&&!t.lchmod&&(t.lchmod=function(m,b,x){x&&process.nextTick(x)},t.lchmodSync=function(){}),t.chown&&!t.lchown&&(t.lchown=function(m,b,x,k){k&&process.nextTick(k)},t.lchownSync=function(){}),ows==="win32"&&(t.rename=typeof t.rename!="function"?t.rename:(function(m){function b(x,k,I){var C=Date.now(),D=0;m(x,k,function R(F){if(F&&(F.code==="EACCES"||F.code==="EPERM"||F.code==="EBUSY")&&Date.now()-C<6e4){setTimeout(function(){t.stat(k,function(L,U){L&&L.code==="ENOENT"?m(x,k,R):I(F)})},D),D<100&&(D+=10);return}I&&I(F)})}return Object.setPrototypeOf&&Object.setPrototypeOf(b,m),b})(t.rename)),t.read=typeof t.read!="function"?t.read:(function(m){function b(x,k,I,C,D,R){var F;if(R&&typeof R=="function"){var L=0;F=function(U,Y,V){if(U&&U.code==="EAGAIN"&&L<10)return L++,m.call(t,x,k,I,C,D,F);R.apply(this,arguments)}}return m.call(t,x,k,I,C,D,F)}return Object.setPrototypeOf&&Object.setPrototypeOf(b,m),b})(t.read),t.readSync=typeof t.readSync!="function"?t.readSync:(function(m){return function(b,x,k,I,C){for(var D=0;;)try{return m.call(t,b,x,k,I,C)}catch(R){if(R.code==="EAGAIN"&&D<10){D++;continue}throw R}}})(t.readSync);function e(m){m.lchmod=function(b,x,k){m.open(b,bq.O_WRONLY|bq.O_SYMLINK,x,function(I,C){if(I){k&&k(I);return}m.fchmod(C,x,function(D){m.close(C,function(R){k&&k(D||R)})})})},m.lchmodSync=function(b,x){var k=m.openSync(b,bq.O_WRONLY|bq.O_SYMLINK,x),I=!0,C;try{C=m.fchmodSync(k,x),I=!1}finally{if(I)try{m.closeSync(k)}catch{}else m.closeSync(k)}return C}}function n(m){bq.hasOwnProperty("O_SYMLINK")&&m.futimes?(m.lutimes=function(b,x,k,I){m.open(b,bq.O_SYMLINK,function(C,D){if(C){I&&I(C);return}m.futimes(D,x,k,function(R){m.close(D,function(F){I&&I(R||F)})})})},m.lutimesSync=function(b,x,k){var I=m.openSync(b,bq.O_SYMLINK),C,D=!0;try{C=m.futimesSync(I,x,k),D=!1}finally{if(D)try{m.closeSync(I)}catch{}else m.closeSync(I)}return C}):m.futimes&&(m.lutimes=function(b,x,k,I){I&&process.nextTick(I)},m.lutimesSync=function(){})}function i(m){return m&&function(b,x,k){return m.call(t,b,x,function(I){_(I)&&(I=null),k&&k.apply(this,arguments)})}}function s(m){return m&&function(b,x){try{return m.call(t,b,x)}catch(k){if(!_(k))throw k}}}function a(m){return m&&function(b,x,k,I){return m.call(t,b,x,k,function(C){_(C)&&(C=null),I&&I.apply(this,arguments)})}}function u(m){return m&&function(b,x,k){try{return m.call(t,b,x,k)}catch(I){if(!_(I))throw I}}}function p(m){return m&&function(b,x,k){typeof x=="function"&&(k=x,x=null);function I(C,D){D&&(D.uid<0&&(D.uid+=4294967296),D.gid<0&&(D.gid+=4294967296)),k&&k.apply(this,arguments)}return x?m.call(t,b,x,I):m.call(t,b,I)}}function f(m){return m&&function(b,x){var k=x?m.call(t,b,x):m.call(t,b);return k&&(k.uid<0&&(k.uid+=4294967296),k.gid<0&&(k.gid+=4294967296)),k}}function _(m){if(!m||m.code==="ENOSYS")return!0;var b=!process.getuid||process.getuid()!==0;return!!(b&&(m.code==="EINVAL"||m.code==="EPERM"))}}});var dfr=an((GIc,pfr)=>{var ufr=Or("stream").Stream;pfr.exports=cws;function cws(t){return{ReadStream:e,WriteStream:n};function e(i,s){if(!(this instanceof e))return new e(i,s);ufr.call(this);var a=this;this.path=i,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=64*1024,s=s||{};for(var u=Object.keys(s),p=0,f=u.length;p<f;p++){var _=u[p];this[_]=s[_]}if(this.encoding&&this.setEncoding(this.encoding),this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!="number")throw TypeError("end must be a Number");if(this.start>this.end)throw new Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){a._read()});return}t.open(this.path,this.flags,this.mode,function(m,b){if(m){a.emit("error",m),a.readable=!1;return}a.fd=b,a.emit("open",b),a._read()})}function n(i,s){if(!(this instanceof n))return new n(i,s);ufr.call(this),this.path=i,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,s=s||{};for(var a=Object.keys(s),u=0,p=a.length;u<p;u++){var f=a[u];this[f]=s[f]}if(this.start!==void 0){if(typeof this.start!="number")throw TypeError("start must be a Number");if(this.start<0)throw new Error("start must be >= zero");this.pos=this.start}this.busy=!1,this._queue=[],this.fd===null&&(this._open=t.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush())}}});var mfr=an((VIc,ffr)=>{"use strict";ffr.exports=uws;var lws=Object.getPrototypeOf||function(t){return t.__proto__};function uws(t){if(t===null||typeof t!="object")return t;if(t instanceof Object)var e={__proto__:lws(t)};else var e=Object.create(null);return Object.getOwnPropertyNames(t).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(t,n))}),e}});var MUt=an((zIc,NUt)=>{var xb=Or("fs"),pws=lfr(),dws=dfr(),fws=mfr(),AJe=Or("util"),pE,xJe;typeof Symbol=="function"&&typeof Symbol.for=="function"?(pE=Symbol.for("graceful-fs.queue"),xJe=Symbol.for("graceful-fs.previous")):(pE="___graceful-fs.queue",xJe="___graceful-fs.previous");function mws(){}function _fr(t,e){Object.defineProperty(t,pE,{get:function(){return e}})}var UX=mws;AJe.debuglog?UX=AJe.debuglog("gfs4"):/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&(UX=function(){var t=AJe.format.apply(AJe,arguments);t="GFS4: "+t.split(/\n/).join(`
1525
+ GFS4: `),console.error(t)});xb[pE]||(hfr=global[pE]||[],_fr(xb,hfr),xb.close=(function(t){function e(n,i){return t.call(xb,n,function(s){s||gfr(),typeof i=="function"&&i.apply(this,arguments)})}return Object.defineProperty(e,xJe,{value:t}),e})(xb.close),xb.closeSync=(function(t){function e(n){t.apply(xb,arguments),gfr()}return Object.defineProperty(e,xJe,{value:t}),e})(xb.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||"")&&process.on("exit",function(){UX(xb[pE]),Or("assert").equal(xb[pE].length,0)}));var hfr;global[pE]||_fr(global,xb[pE]);NUt.exports=DUt(fws(xb));process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!xb.__patched&&(NUt.exports=DUt(xb),xb.__patched=!0);function DUt(t){pws(t),t.gracefulify=DUt,t.createReadStream=Y,t.createWriteStream=V;var e=t.readFile;t.readFile=n;function n(ne,he,De){return typeof he=="function"&&(De=he,he=null),We(ne,he,De);function We(Me,ze,wt,yt){return e(Me,ze,function(Re){Re&&(Re.code==="EMFILE"||Re.code==="ENFILE")?dde([We,[Me,ze,wt],Re,yt||Date.now(),Date.now()]):typeof wt=="function"&&wt.apply(this,arguments)})}}var i=t.writeFile;t.writeFile=s;function s(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return i(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var a=t.appendFile;a&&(t.appendFile=u);function u(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return a(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var p=t.copyFile;p&&(t.copyFile=f);function f(ne,he,De,We){return typeof De=="function"&&(We=De,De=0),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return p(ze,wt,yt,function(ct){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}var _=t.readdir;t.readdir=b;var m=/^v[0-5]\./;function b(ne,he,De){typeof he=="function"&&(De=he,he=null);var We=m.test(process.version)?function(wt,yt,Re,je){return _(wt,Me(wt,yt,Re,je))}:function(wt,yt,Re,je){return _(wt,yt,Me(wt,yt,Re,je))};return We(ne,he,De);function Me(ze,wt,yt,Re){return function(je,ct){je&&(je.code==="EMFILE"||je.code==="ENFILE")?dde([We,[ze,wt,yt],je,Re||Date.now(),Date.now()]):(ct&&ct.sort&&ct.sort(),typeof yt=="function"&&yt.call(this,je,ct))}}}if(process.version.substr(0,4)==="v0.8"){var x=dws(t);R=x.ReadStream,L=x.WriteStream}var k=t.ReadStream;k&&(R.prototype=Object.create(k.prototype),R.prototype.open=F);var I=t.WriteStream;I&&(L.prototype=Object.create(I.prototype),L.prototype.open=U),Object.defineProperty(t,"ReadStream",{get:function(){return R},set:function(ne){R=ne},enumerable:!0,configurable:!0}),Object.defineProperty(t,"WriteStream",{get:function(){return L},set:function(ne){L=ne},enumerable:!0,configurable:!0});var C=R;Object.defineProperty(t,"FileReadStream",{get:function(){return C},set:function(ne){C=ne},enumerable:!0,configurable:!0});var D=L;Object.defineProperty(t,"FileWriteStream",{get:function(){return D},set:function(ne){D=ne},enumerable:!0,configurable:!0});function R(ne,he){return this instanceof R?(k.apply(this,arguments),this):R.apply(Object.create(R.prototype),arguments)}function F(){var ne=this;te(ne.path,ne.flags,ne.mode,function(he,De){he?(ne.autoClose&&ne.destroy(),ne.emit("error",he)):(ne.fd=De,ne.emit("open",De),ne.read())})}function L(ne,he){return this instanceof L?(I.apply(this,arguments),this):L.apply(Object.create(L.prototype),arguments)}function U(){var ne=this;te(ne.path,ne.flags,ne.mode,function(he,De){he?(ne.destroy(),ne.emit("error",he)):(ne.fd=De,ne.emit("open",De))})}function Y(ne,he){return new t.ReadStream(ne,he)}function V(ne,he){return new t.WriteStream(ne,he)}var z=t.open;t.open=te;function te(ne,he,De,We){return typeof De=="function"&&(We=De,De=null),Me(ne,he,De,We);function Me(ze,wt,yt,Re,je){return z(ze,wt,yt,function(ct,Qt){ct&&(ct.code==="EMFILE"||ct.code==="ENFILE")?dde([Me,[ze,wt,yt,Re],ct,je||Date.now(),Date.now()]):typeof Re=="function"&&Re.apply(this,arguments)})}}return t}function dde(t){UX("ENQUEUE",t[0].name,t[1]),xb[pE].push(t),RUt()}var vJe;function gfr(){for(var t=Date.now(),e=0;e<xb[pE].length;++e)xb[pE][e].length>2&&(xb[pE][e][3]=t,xb[pE][e][4]=t);RUt()}function RUt(){if(clearTimeout(vJe),vJe=void 0,xb[pE].length!==0){var t=xb[pE].shift(),e=t[0],n=t[1],i=t[2],s=t[3],a=t[4];if(s===void 0)UX("RETRY",e.name,n),e.apply(null,n);else if(Date.now()-s>=6e4){UX("TIMEOUT",e.name,n);var u=n.pop();typeof u=="function"&&u.call(null,i)}else{var p=Date.now()-a,f=Math.max(a-s,1),_=Math.min(f*1.2,100);p>=_?(UX("RETRY",e.name,n),e.apply(null,n.concat([s]))):xb[pE].push(t)}vJe===void 0&&(vJe=setTimeout(RUt,0))}}});var bfr=an((HIc,yfr)=>{function FN(t,e){typeof e=="boolean"&&(e={forever:e}),this._originalTimeouts=JSON.parse(JSON.stringify(t)),this._timeouts=t,this._options=e||{},this._maxRetryTime=e&&e.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}yfr.exports=FN;FN.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};FN.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timeouts=[],this._cachedTimeouts=null};FN.prototype.retry=function(t){if(this._timeout&&clearTimeout(this._timeout),!t)return!1;var e=new Date().getTime();if(t&&e-this._operationStart>=this._maxRetryTime)return this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(t);var n=this._timeouts.shift();if(n===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),n=this._timeouts.shift();else return!1;var i=this,s=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},n);return this._options.unref&&s.unref(),!0};FN.prototype.attempt=function(t,e){this._fn=t,e&&(e.timeout&&(this._operationTimeout=e.timeout),e.cb&&(this._operationTimeoutCb=e.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){n._operationTimeoutCb()},n._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)};FN.prototype.try=function(t){console.log("Using RetryOperation.try() is deprecated"),this.attempt(t)};FN.prototype.start=function(t){console.log("Using RetryOperation.start() is deprecated"),this.attempt(t)};FN.prototype.start=FN.prototype.try;FN.prototype.errors=function(){return this._errors};FN.prototype.attempts=function(){return this._attempts};FN.prototype.mainError=function(){if(this._errors.length===0)return null;for(var t={},e=null,n=0,i=0;i<this._errors.length;i++){var s=this._errors[i],a=s.message,u=(t[a]||0)+1;t[a]=u,u>=n&&(e=s,n=u)}return e}});var Afr=an(jX=>{var hws=bfr();jX.operation=function(t){var e=jX.timeouts(t);return new hws(e,{forever:t&&t.forever,unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})};jX.timeouts=function(t){if(t instanceof Array)return[].concat(t);var e={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var n in t)e[n]=t[n];if(e.minTimeout>e.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],s=0;s<e.retries;s++)i.push(this.createTimeout(s,e));return t&&t.forever&&!i.length&&i.push(this.createTimeout(s,e)),i.sort(function(a,u){return a-u}),i};jX.createTimeout=function(t,e){var n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*Math.pow(e.factor,t));return i=Math.min(i,e.maxTimeout),i};jX.wrap=function(t,e,n){if(e instanceof Array&&(n=e,e=null),!n){n=[];for(var i in t)typeof t[i]=="function"&&n.push(i)}for(var s=0;s<n.length;s++){var a=n[s],u=t[a];t[a]=function(f){var _=jX.operation(e),m=Array.prototype.slice.call(arguments,1),b=m.pop();m.push(function(x){_.retry(x)||(x&&(arguments[0]=_.mainError()),b.apply(this,arguments))}),_.attempt(function(){f.apply(t,m)})}.bind(t,u),t[a].options=e}}});var xfr=an((KIc,vfr)=>{vfr.exports=Afr()});var wfr=an((YIc,wJe)=>{wJe.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&wJe.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&wJe.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var kfr=an((XIc,hde)=>{var $0=global.process,WX=function(t){return t&&typeof t=="object"&&typeof t.removeListener=="function"&&typeof t.emit=="function"&&typeof t.reallyExit=="function"&&typeof t.listeners=="function"&&typeof t.kill=="function"&&typeof t.pid=="number"&&typeof t.on=="function"};WX($0)?(Sfr=Or("assert"),fde=wfr(),Efr=/^win/i.test($0.platform),JCe=Or("events"),typeof JCe!="function"&&(JCe=JCe.EventEmitter),$0.__signal_exit_emitter__?oS=$0.__signal_exit_emitter__:(oS=$0.__signal_exit_emitter__=new JCe,oS.count=0,oS.emitted={}),oS.infinite||(oS.setMaxListeners(1/0),oS.infinite=!0),hde.exports=function(t,e){if(!WX(global.process))return function(){};Sfr.equal(typeof t,"function","a callback must be provided for exit handler"),mde===!1&&OUt();var n="exit";e&&e.alwaysLast&&(n="afterexit");var i=function(){oS.removeListener(n,t),oS.listeners("exit").length===0&&oS.listeners("afterexit").length===0&&SJe()};return oS.on(n,t),i},SJe=function(){!mde||!WX(global.process)||(mde=!1,fde.forEach(function(e){try{$0.removeListener(e,EJe[e])}catch{}}),$0.emit=CJe,$0.reallyExit=FUt,oS.count-=1)},hde.exports.unload=SJe,QX=function(e,n,i){oS.emitted[e]||(oS.emitted[e]=!0,oS.emit(e,n,i))},EJe={},fde.forEach(function(t){EJe[t]=function(){if(WX(global.process)){var n=$0.listeners(t);n.length===oS.count&&(SJe(),QX("exit",null,t),QX("afterexit",null,t),Efr&&t==="SIGHUP"&&(t="SIGINT"),$0.kill($0.pid,t))}}}),hde.exports.signals=function(){return fde},mde=!1,OUt=function(){mde||!WX(global.process)||(mde=!0,oS.count+=1,fde=fde.filter(function(e){try{return $0.on(e,EJe[e]),!0}catch{return!1}}),$0.emit=Tfr,$0.reallyExit=Cfr)},hde.exports.load=OUt,FUt=$0.reallyExit,Cfr=function(e){WX(global.process)&&($0.exitCode=e||0,QX("exit",$0.exitCode,null),QX("afterexit",$0.exitCode,null),FUt.call($0,$0.exitCode))},CJe=$0.emit,Tfr=function(e,n){if(e==="exit"&&WX(global.process)){n!==void 0&&($0.exitCode=n);var i=CJe.apply(this,arguments);return QX("exit",$0.exitCode,null),QX("afterexit",$0.exitCode,null),i}else return CJe.apply(this,arguments)}):hde.exports=function(){return function(){}};var Sfr,fde,Efr,JCe,oS,SJe,QX,EJe,mde,OUt,FUt,Cfr,CJe,Tfr});var Pfr=an((ZIc,LUt)=>{"use strict";var Ifr=Symbol();function gws(t,e,n){let i=e[Ifr];if(i)return e.stat(t,(a,u)=>{if(a)return n(a);n(null,u.mtime,i)});let s=new Date(Math.ceil(Date.now()/1e3)*1e3+5);e.utimes(t,s,s,a=>{if(a)return n(a);e.stat(t,(u,p)=>{if(u)return n(u);let f=p.mtime.getTime()%1e3===0?"s":"ms";Object.defineProperty(e,Ifr,{value:f}),n(null,p.mtime,f)})})}function _ws(t){let e=Date.now();return t==="s"&&(e=Math.ceil(e/1e3)*1e3),new Date(e)}LUt.exports.probe=gws;LUt.exports.getMtime=_ws});var Ofr=an((ePc,YCe)=>{"use strict";var yws=Or("path"),UUt=MUt(),bws=xfr(),Aws=kfr(),Dfr=Pfr(),K8={};function KCe(t,e){return e.lockfilePath||`${t}.lock`}function jUt(t,e,n){if(!e.realpath)return n(null,yws.resolve(t));e.fs.realpath(t,n)}function $Ut(t,e,n){let i=KCe(t,e);e.fs.mkdir(i,s=>{if(!s)return Dfr.probe(i,e.fs,(a,u,p)=>{if(a)return e.fs.rmdir(i,()=>{}),n(a);n(null,u,p)});if(s.code!=="EEXIST")return n(s);if(e.stale<=0)return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:t}));e.fs.stat(i,(a,u)=>{if(a)return a.code==="ENOENT"?$Ut(t,{...e,stale:0},n):n(a);if(!Rfr(u,e))return n(Object.assign(new Error("Lock file is already being held"),{code:"ELOCKED",file:t}));Nfr(t,e,p=>{if(p)return n(p);$Ut(t,{...e,stale:0},n)})})})}function Rfr(t,e){return t.mtime.getTime()<Date.now()-e.stale}function Nfr(t,e,n){e.fs.rmdir(KCe(t,e),i=>{if(i&&i.code!=="ENOENT")return n(i);n()})}function TJe(t,e){let n=K8[t];n.updateTimeout||(n.updateDelay=n.updateDelay||e.update,n.updateTimeout=setTimeout(()=>{n.updateTimeout=null,e.fs.stat(n.lockfilePath,(i,s)=>{let a=n.lastUpdate+e.stale<Date.now();if(i)return i.code==="ENOENT"||a?BUt(t,n,Object.assign(i,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,TJe(t,e));if(!(n.mtime.getTime()===s.mtime.getTime()))return BUt(t,n,Object.assign(new Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let p=Dfr.getMtime(n.mtimePrecision);e.fs.utimes(n.lockfilePath,p,p,f=>{let _=n.lastUpdate+e.stale<Date.now();if(!n.released){if(f)return f.code==="ENOENT"||_?BUt(t,n,Object.assign(f,{code:"ECOMPROMISED"})):(n.updateDelay=1e3,TJe(t,e));n.mtime=p,n.lastUpdate=Date.now(),n.updateDelay=null,TJe(t,e)}})})},n.updateDelay),n.updateTimeout.unref&&n.updateTimeout.unref())}function BUt(t,e,n){e.released=!0,e.updateTimeout&&clearTimeout(e.updateTimeout),K8[t]===e&&delete K8[t],e.options.onCompromised(n)}function vws(t,e,n){e={stale:1e4,update:null,realpath:!0,retries:0,fs:UUt,onCompromised:i=>{throw i},...e},e.retries=e.retries||0,e.retries=typeof e.retries=="number"?{retries:e.retries}:e.retries,e.stale=Math.max(e.stale||0,2e3),e.update=e.update==null?e.stale/2:e.update||0,e.update=Math.max(Math.min(e.update,e.stale/2),1e3),jUt(t,e,(i,s)=>{if(i)return n(i);let a=bws.operation(e.retries);a.attempt(()=>{$Ut(s,e,(u,p,f)=>{if(a.retry(u))return;if(u)return n(a.mainError());let _=K8[s]={lockfilePath:KCe(s,e),mtime:p,mtimePrecision:f,options:e,lastUpdate:Date.now()};TJe(s,e),n(null,m=>{if(_.released)return m&&m(Object.assign(new Error("Lock is already released"),{code:"ERELEASED"}));Mfr(s,{...e,realpath:!1},m)})})})})}function Mfr(t,e,n){e={fs:UUt,realpath:!0,...e},jUt(t,e,(i,s)=>{if(i)return n(i);let a=K8[s];if(!a)return n(Object.assign(new Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));a.updateTimeout&&clearTimeout(a.updateTimeout),a.released=!0,delete K8[s],Nfr(s,e,n)})}function xws(t,e,n){e={stale:1e4,realpath:!0,fs:UUt,...e},e.stale=Math.max(e.stale||0,2e3),jUt(t,e,(i,s)=>{if(i)return n(i);e.fs.stat(KCe(s,e),(a,u)=>a?a.code==="ENOENT"?n(null,!1):n(a):n(null,!Rfr(u,e)))})}function wws(){return K8}Aws(()=>{for(let t in K8){let e=K8[t].options;try{e.fs.rmdirSync(KCe(t,e))}catch{}}});YCe.exports.lock=vws;YCe.exports.unlock=Mfr;YCe.exports.check=xws;YCe.exports.getLocks=wws});var Lfr=an((tPc,Ffr)=>{"use strict";var Sws=MUt();function Ews(t){let e=["mkdir","realpath","stat","rmdir","utimes"],n={...t};return e.forEach(i=>{n[i]=(...s)=>{let a=s.pop(),u;try{u=t[`${i}Sync`](...s)}catch(p){return a(p)}a(null,u)}}),n}function Cws(t){return(...e)=>new Promise((n,i)=>{e.push((s,a)=>{s?i(s):n(a)}),t(...e)})}function Tws(t){return(...e)=>{let n,i;if(e.push((s,a)=>{n=s,i=a}),t(...e),n)throw n;return i}}function kws(t){if(t={...t},t.fs=Ews(t.fs||Sws),typeof t.retries=="number"&&t.retries>0||t.retries&&typeof t.retries.retries=="number"&&t.retries.retries>0)throw Object.assign(new Error("Cannot use retries with the sync api"),{code:"ESYNC"});return t}Ffr.exports={toPromise:Cws,toSync:Tws,toSyncOptions:kws}});var $fr=an((nPc,Aq)=>{"use strict";var gde=Ofr(),{toPromise:kJe,toSync:IJe,toSyncOptions:WUt}=Lfr();async function Bfr(t,e){let n=await kJe(gde.lock)(t,e);return kJe(n)}function Iws(t,e){let n=IJe(gde.lock)(t,WUt(e));return IJe(n)}function Pws(t,e){return kJe(gde.unlock)(t,e)}function Dws(t,e){return IJe(gde.unlock)(t,WUt(e))}function Rws(t,e){return kJe(gde.check)(t,e)}function Nws(t,e){return IJe(gde.check)(t,WUt(e))}Aq.exports=Bfr;Aq.exports.lock=Bfr;Aq.exports.unlock=Pws;Aq.exports.lockSync=Iws;Aq.exports.unlockSync=Dws;Aq.exports.check=Rws;Aq.exports.checkSync=Nws});function nie(){return process.env.CRTR_PROFILE_ID}function Uj(){return process.env.CRTR_HOME}var _Ts=5*6e4;var yTs=300*1e3;var bTs=60*1e3;function Aun(){let t=process.env.CRTR_PIDFILE;return t!==void 0&&t!==""?t:void 0}function vun(){return process.env.CRTR_NO_DAEMON_AUTOSTART==="1"}var ATs=5*6e4;import{existsSync as Fjr,readFileSync as Ljr}from"node:fs";import{dirname as xun,join as Bjr,parse as $jr}from"node:path";import{fileURLToPath as Ujr}from"node:url";function jjr(t,e){let n=xun(t),i=$jr(n).root;for(;;){let s=Bjr(n,"package.json");if(Fjr(s))try{if(JSON.parse(Ljr(s,"utf8")).name===e)return n}catch{return null}if(n===i)return null;n=xun(n)}}function wun(){let t="@earendil-works/pi-coding-agent",e;try{e=Ujr(import.meta.resolve(t))}catch(i){throw new Error(`crouter install is missing bundled ${t}; reinstall @north-light/crouter. ${i.message}`)}let n=jjr(e,t);if(n===null)throw new Error(`could not locate bundled ${t} package root from ${e}`);return n}try{process.env.PI_PACKAGE_DIR=wun()}catch{}UP();var Qjr='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>';function GLe(t){return t.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function Sun(t){let e=GLe(t.title),n=GLe(t.heading),i=GLe(t.message),s=t.details?GLe(t.details):void 0;return`<!doctype html>
1526
1526
  <html lang="en">
1527
1527
  <head>
1528
1528
  <meta charset="utf-8" />
@@ -2047,7 +2047,7 @@ ${pys(e)}
2047
2047
 
2048
2048
  `)}registerCopyBlock(e,n,i){let s=this.condensedCopyBlocks.get(this.appendTarget);if(s){let u=s.findIndex(p=>p.block===e);u===-1?s.push({block:e,kind:n,text:i}):s[u].text=i;return}let a=this.copyIndex.get(e);a===void 0?(this.copyIndex.set(e,this.copyBlockRecords.length),this.copyBlockRecords.push({block:e,kind:n,text:i})):this.copyBlockRecords[a].text=i}unregisterCopyBlock(e){let n=this.condensedCopyBlocks.get(this.appendTarget);if(n){let s=n.findIndex(a=>a.block===e);s!==-1&&n.splice(s,1);return}let i=this.copyIndex.get(e);if(i!==void 0){this.copyBlockRecords.splice(i,1),this.copyIndex.delete(e);for(let s=i;s<this.copyBlockRecords.length;s++)this.copyIndex.set(this.copyBlockRecords[s].block,s)}}appendCondensedBlock({component:e,copyBlocks:n}){this.append(e),this.registerCopyBlock(e,"condensed",n.map(i=>i.text).filter(i=>i.trim()!=="").join(`
2049
2049
 
2050
- `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(i=>typeof i=="object"&&i!==null&&i.type==="text"&&typeof i.text=="string").map(i=>i.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let i=n5t([n],this.cwd);if(i.length===0)return;let s=[...i,...this.transcriptFilePaths.filter(a=>!i.includes(a))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...s)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(i=>typeof i=="object"&&i!==null&&i.type==="text").map(i=>i.text).join(""):""}};var d0s="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",kCe={first:-1,last:-1,lastFullyVisible:-1};function f0s(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function m0s(t,e,n){let i=0,s=t.blockCount();for(;i<s;){let a=Math.floor((i+s)/2);t.blockStart(a,n)+t.blockHeight(a,n)>e?s=a:i=a+1}return i}function eur(t,e){let n={follow:!0,anchor:void 0},i,s=0,a=kCe,u;function p(m,b,x){let k=Math.max(0,x-b);if(n.follow)return k;if(!n.anchor)return n.follow=!0,k;let I=t.anchorLine(n.anchor,m);return I===void 0?(n.follow=!0,n.anchor=void 0,k):Math.min(Math.max(0,I),k)}function f(m,b,x,k){let I=Math.min(x,k+b);if(k>=I)return{top:k,bottom:I,total:x,blocks:kCe};let C=t.blockCount(),D=m0s(t,k,m),R=-1,F=-1,L=-1;for(;D<C;){let U=t.blockStart(D,m);if(U>=I)break;let Y=t.blockHeight(D,m),V=U+Y;V>k&&(R===-1&&(R=D),F=D,U>=k&&V<=I&&(L=D)),D++}return{top:k,bottom:I,total:x,blocks:R===-1?kCe:{first:R,last:F,lastFullyVisible:L}}}function _(){if(i===void 0||s<=0)return;let m=t.totalHeight(i),b=p(i,s,m);return f(i,s,m,b)}return{renderSlice(m,b){let x=Math.max(0,b);if(i=m,s=x,x===0)return a=kCe,u=t.revision(),[];let k=t.totalHeight(m),I=p(m,x,k),C=f(m,x,k,I),D=[];for(let F=C.blocks.first;F!==-1&&F<=C.blocks.last;F++){let L=t.blockStart(F,m),U=t.blockLines(F,m),Y=t.blockHeight(F,m),V=L+Y,z=Math.max(0,C.top-L),te=Math.min(Y,C.bottom-L);if(z>=te)continue;if((L<C.top||V>C.bottom)&&f0s(U))D.push(...Array(te-z).fill(d0s));else if(e===void 0)D.push(...U.slice(z,te));else for(let he=z;he<te;he++)D.push(e(L+he,U[he],m))}let R=D.length>=x?D.slice(0,x):[...Array(x-D.length).fill(""),...D];return a=C.blocks,u=t.revision(),R},scrollBy(m){if(i===void 0||s<=0||m===0)return!1;let b=n.follow,x=n.anchor,k=t.totalHeight(i),I=p(i,s,k),C=Math.max(0,k-s),D=Math.min(Math.max(0,I+m),C);return D>=C?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(D,i),n.anchor||(n.follow=!0)),n.follow!==b||n.anchor!==x},pageRows(){return Math.max(0,s-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(m){if(i===void 0||s<=0)return;let b=t.totalHeight(i),x=Math.max(0,b-s),k=Math.min(Math.max(0,m-Math.floor(s/3)),x);if(k>=x){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(k,i),n.anchor||(n.follow=!0)},topLine(){if(!(i===void 0||s<=0))return p(i,s,t.totalHeight(i))},isLive(){return n.follow},visibleBlocks(){let m=t.revision();return u===m||(a=_()?.blocks??kCe,u=m),a},invalidate(){t.invalidate()}}}var h0s=new Intl.Segmenter(void 0,{granularity:"grapheme"}),g0s="\x1B[7m",_0s="\x1B[27m";function y0s(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let i=t.indexOf("\x07",e+2),s=t.indexOf("\x1B\\",e+2),a=i===-1?s:s===-1?i:Math.min(i,s);return a===-1?void 0:{text:t.slice(e,a+(a===i?1:2)),end:a+(a===i?1:2)}}if(n==="["){let i=e+2;for(;i<t.length&&(t.charCodeAt(i)<64||t.charCodeAt(i)>126);)i++;return i>=t.length?void 0:{text:t.slice(e,i+1),end:i+1}}return{text:t.slice(e,e+2),end:e+2}}}function THe(t,e){let n=0,i=0;for(;i<t.length;){if(t[i]==="\x1B"){let u=y0s(t,i);if(u===void 0)break;e.onEscape?.(u.text),i=u.end;continue}let s=t.indexOf("\x1B",i),a=t.slice(i,s===-1?void 0:s);for(let u of h0s.segment(a)){let p=Hv(u.segment);e.onGlyph?.({text:u.segment,cell:n,width:p}),n+=p}i=s===-1?t.length:s}return n}function tur(t,e,n){let i="";return THe(t,{onGlyph:s=>{s.cell>=e&&s.cell<n&&(i+=s.text)}}),i}var b0s={on:g0s,off:_0s};function g8t(t,e,n,i,s=b0s){let a=Math.min(n,i);if(a<=e||e<0)return t;let u="",p=!1,f=[],_=()=>{p||(u+=s.on,p=!0)},m=()=>{p&&(u+=s.restore===!0?`\x1B[0m${f.join("")}`:s.off,p=!1)},b=THe(t,{onEscape:x=>{u+=x,x.endsWith("m")&&(x==="\x1B[0m"||x==="\x1B[m"?f.length=0:f.push(x),p&&(u+=s.on))},onGlyph:x=>{x.cell>=e&&x.cell<a?_():m(),u+=x.text}});if(m(),b<a){let x=Math.max(0,e-b),k=a-Math.max(e,b);u+=" ".repeat(x)+s.on+" ".repeat(k)+(s.restore===!0?"\x1B[0m":s.off)}return u}function nur(t,e,n,i){return g8t(t,e,n,i)}var A0s={on:"\x1B[107m\x1B[30m",off:"",restore:!0},v0s={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function x0s(t){let e="",n=[],i=THe(t,{onGlyph:s=>{for(let a=0;a<s.text.length;a++)n.push(s.cell);e+=s.text}});return{text:e,cells:n,width:i}}function w0s(t){return t!==t.toLowerCase()}function S0s(t,e,n,i,s){let a=n?t.text:t.text.toLowerCase(),u=n?e:e.toLowerCase(),p=a.indexOf(u);for(;p!==-1;){let f=p+u.length,_=t.cells[p]??0,m=f<t.cells.length?t.cells[f]:t.width;m>_&&s.push({line:i,from:_,to:m}),p=a.indexOf(u,p+Math.max(1,u.length))}}function rur(t){let e="",n=0,i=[],s=new Map,a,u;function p(f){let _=`${f}:${t.revision()}:${e}`;if(a===_)return i;let m=[];if(e!==""){let x=w0s(e),k=t.blockCount();for(let I=0;I<k;I++){let C=t.blockStart(I,f),D=t.blockLines(I,f);for(let R=0;R<D.length;R++){let F=D[R];F.toLowerCase().includes(e.toLowerCase())&&S0s(x0s(F),e,x,C+R,m)}}}let b=new Map;for(let x of m){let k=b.get(x.line);k?k.push(x):b.set(x.line,[x])}if(i=m,s=b,a=_,u!==void 0){let x=u;u=void 0;let k=m.findIndex(I=>I.line>=x);n=k===-1?Math.max(0,m.length-1):k}else n>=m.length&&(n=Math.max(0,m.length-1));return i}return{setQuery(f,_){f!==e&&(e=f,u=_,a=void 0)},query(){return e},matches(f){return p(f)},current(f){return p(f)[n]},status(f){let _=p(f);return{index:_.length===0?0:n+1,total:_.length}},step(f,_){let m=p(f);if(m.length!==0)return n=(n+_+m.length)%m.length,m[n]},selectNear(f,_){let m=p(f);if(m.length===0)return;let b=m.findIndex(x=>x.line>=_);return n=b===-1?m.length-1:b,m[n]},decorate(f,_,m){if(e==="")return _;let b=p(m),x=s.get(f);if(x===void 0)return _;let k=b[n],I=_;for(let C of x)I=g8t(I,C.from,C.to,m,C===k?v0s:A0s);return I}}}import{existsSync as xur,readFileSync as wur}from"node:fs";import{join as Sur}from"node:path";import{existsSync as E0s,readFileSync as axc,writeFileSync as cxc,rmSync as lxc,mkdirSync as uxc,statSync as pxc}from"node:fs";import{join as C0s}from"node:path";function T0s(t){return C0s(PR(t),"busy")}function iur(t){return E0s(T0s(t))}function G8(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{existsSync as kxc,mkdirSync as L0s,readFileSync as pur,realpathSync as B0s,rmSync as lur,writeFileSync as $0s}from"node:fs";import{join as dur}from"node:path";var k0s="crtr:managed-provider-cooling";function sur(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===k0s)}function _8t(t){return typeof t=="string"?t:""}function $D(t,e,n={}){return{kind:t,matchedOn:e,...n}}function TF(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}var I0s=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]];function our(t){let e=I0s.flatMap(([i,s])=>{let a=t.match(s);return a?[{kind:i,match:a[0]}]:[]}),n=e[0];return n===void 0?$D("other","none"):{...$D(n.kind,"text",{match:n.match}),textMatches:e}}function aur(t){let e=t.retryAfterMs,n=our(t.message??""),i=_8t(t.code)||_8t(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(i))return TF($D("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(i))return TF($D("overloaded","errno",{retryAfterMs:e}),n);let s=typeof t.status=="number"?t.status:void 0;if(s!==void 0){if(s===401||s===403)return TF($D("auth","status",{status:s,retryAfterMs:e}),n);if(s===429)return TF($D("rate-limit","status",{status:s,retryAfterMs:e}),n);if(s===500||s===502||s===503||s===504)return TF($D("transient-http","status",{status:s,retryAfterMs:e}),n);if(s>=500&&s<=599)return TF($D("overloaded","status",{status:s,retryAfterMs:e}),n);if(s>=400&&s<=499)return TF($D("protocol","status",{status:s,retryAfterMs:e}),n)}let a=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(a===1008)return TF($D("protocol","websocket-close",{retryAfterMs:e}),n);if(a===1006)return TF($D("connection","websocket-close",{retryAfterMs:e}),n);if(a===1011){let u=_8t(t.wsCloseReason),p=our(u);return/no running broker/i.test(u)||p.kind==="connection"||p.kind==="connection-only"?TF($D("connection","websocket-close",{retryAfterMs:e}),n):TF($D("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}var P0s="crtr:provider-failure";function ON(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function IHe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function PHe(t){return typeof t=="string"||typeof t=="number"?t:void 0}function kHe(t){return G8(t)?t:void 0}function D0s(t){let e=ON(t.errorMessage)??ON(t.message)??ON(t.reason)??ON(t.statusText),n={...e===void 0?{}:{message:e},...IHe(t.status)===void 0?{}:{status:IHe(t.status)},...PHe(t.code)===void 0?{}:{code:PHe(t.code)},...ON(t.errno)===void 0?{}:{errno:ON(t.errno)},...ON(t.body)===void 0?{}:{body:ON(t.body)}};return Object.keys(n).length===0?void 0:n}function R0s(t){let e=kHe(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let i=kHe(n);if(i?.type!==P0s)continue;let s=kHe(i.details);if(s===void 0)continue;let a=Array.isArray(s.causes)?s.causes.flatMap(u=>{let p=kHe(u),f=p===void 0?void 0:D0s(p);return f===void 0?[]:[f]}):void 0;return{...IHe(s.status)===void 0?{}:{status:IHe(s.status)},...PHe(s.code)===void 0?{}:{code:PHe(s.code)},...ON(s.errno)===void 0?{}:{errno:ON(s.errno)},...ON(s.body)===void 0?{}:{body:ON(s.body)},...a===void 0||a.length===0?{}:{causes:a}}}}function cur(t){return R0s(t)}var N0s={"rate-limit":"rate_limit",overloaded:"overloaded",connection:"connection",auth:"auth",protocol:"protocol","context-overflow":"context_overflow",wedged:"wedged","model-not-found":"model_not_found",other:"unknown"};function y8t(t){return{class:N0s[t.kind],retry_disposition:t.retry.disposition}}function M0s(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function O0s(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function F0s(t){if(typeof t=="string")return t;if(!G8(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let i of e)if(typeof i=="string"&&i!=="")return i;let n=t.error;if(G8(n)){let i=n.message;if(typeof i=="string"&&i!=="")return i;let s=n.reason;if(typeof s=="string"&&s!=="")return s}return""}function DHe(t,e){if(t==="pi\u2192provider"&&sur(e))return{kind:"rate-limit",disposition:"auto"};let n=G8(e)?e:{},i=cur(e),s=i?.causes??[],a=aur({code:n.code??i?.code??s.find(p=>p.code!==void 0)?.code,errno:n.errno??i?.errno??s.find(p=>p.errno!==void 0)?.errno,status:n.status??i?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[F0s(e),i?.body,...s.flatMap(p=>[p.message,p.body])].filter(p=>typeof p=="string"&&p!=="").join(" ")}),u=M0s(a);return{kind:u,disposition:O0s(t,u)}}var U0s=5*6e4,j0s=500;function b8t(t){return dur(PR(t),"fault")}function fur(t){return dur(PR(t),"provider-retry")}function W0s(t){try{return B0s(t)}catch{return t}}function Q0s(t){return t.slice(0,j0s)}function uur(t){return t.link==="pi\u2192provider"&&t.retry.disposition==="auto"&&t.retry.by==="daemon"?3:t.retry.disposition==="fatal"?2:1}var q0s=["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","broker\u2194crtrd","daemon\u2192node","crtr\u2192pi"],G0s=["rate-limit","overloaded","connection","auth","protocol","context-overflow","other","wedged","model-not-found"];function V0s(t){if(!G8(t)||typeof t.provider!="string"||t.provider===""||typeof t.model!="string"||t.model==="")return;let e=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0,n=typeof t.code=="string"||typeof t.code=="number"?t.code:void 0,i=typeof t.errno=="string"?t.errno:void 0,s=typeof t.body=="string"?t.body:void 0,a=Array.isArray(t.causes)?t.causes.flatMap(u=>{if(!G8(u))return[];let p={...typeof u.message=="string"?{message:u.message}:{},...typeof u.status=="number"&&Number.isFinite(u.status)?{status:u.status}:{},...typeof u.code=="string"||typeof u.code=="number"?{code:u.code}:{},...typeof u.errno=="string"?{errno:u.errno}:{},...typeof u.body=="string"?{body:u.body}:{}};return Object.keys(p).length===0?[]:[p]}):void 0;return{provider:t.provider,model:t.model,...e===void 0?{}:{status:e},...n===void 0?{}:{code:n},...i===void 0?{}:{errno:i},...s===void 0?{}:{body:s},...a===void 0||a.length===0?{}:{causes:a}}}function mur(t){try{let e=JSON.parse(t);if(!q0s.includes(e.link)||typeof e.op!="string"||e.op===""||!G0s.includes(e.kind)||typeof e.message!="string"||typeof e.since!="string")return null;let n=mH(e.operation_id),i=e.retry;if(i===void 0||i.disposition!=="auto"&&i.disposition!=="manual"&&i.disposition!=="fatal"||i.by!==void 0&&i.by!=="sdk"&&i.by!=="daemon"&&i.by!=="client"||i.attempt!==void 0&&typeof i.attempt!="number"||i.max!==void 0&&typeof i.max!="number"||i.nextAt!==void 0&&typeof i.nextAt!="string"||e.anchorEntryId!==void 0&&(typeof e.anchorEntryId!="string"||e.anchorEntryId===""))return null;let s=e.providerError===void 0?void 0:V0s(e.providerError);return e.providerError!==void 0&&s===void 0?null:{link:e.link,op:e.op,kind:e.kind,retry:{disposition:i.disposition,...i.by===void 0?{}:{by:i.by},...i.attempt===void 0?{}:{attempt:i.attempt},...i.max===void 0?{}:{max:i.max},...i.nextAt===void 0?{}:{nextAt:i.nextAt}},message:e.message,since:e.since,operation_id:n,...e.anchorEntryId===void 0?{}:{anchorEntryId:e.anchorEntryId},...s===void 0?{}:{providerError:s}}}catch{return null}}function A8t(t){try{return mur(pur(b8t(t),"utf8"))}catch{return null}}function z0s(t){try{let e=JSON.parse(pur(fur(t),"utf8"));if(e.state!=="pending"&&e.state!=="admitted"&&e.state!=="invalidated"||typeof e.sessionFile!="string"||e.sessionFile===""||e.anchorEntryId!==null&&typeof e.anchorEntryId!="string")return null;let n=mur(JSON.stringify(e.fault));return n===null||n.link!=="pi\u2192provider"||n.retry.disposition!=="auto"||n.retry.by!=="daemon"||(n.anchorEntryId??null)!==e.anchorEntryId?null:{state:e.state,sessionFile:W0s(e.sessionFile),anchorEntryId:e.anchorEntryId,fault:n}}catch{return null}}function H0s(t,e){try{return L0s(PR(t),{recursive:!0}),$0s(b8t(t),JSON.stringify(e)),!0}catch{return!1}}function J0s(t,e){let n=A8t(t);if(n===null)return e;if(n.link===e.link&&n.kind===e.kind){let i={...n.retry,...e.retry};return e.retry.disposition==="fatal"&&!("nextAt"in e.retry)&&delete i.nextAt,{...e,since:n.since,anchorEntryId:n.anchorEntryId??e.anchorEntryId,retry:i}}return uur(n)>uur(e)?null:e}function K0s(t,e){let n=J0s(t,e);return n!==null&&H0s(t,n)?n:null}function hur(t){if(t!==void 0)return mH(t);let e=cbe.current();return e!==void 0?e:cbe.fresh(n=>n)}function Y0s(t){return{link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:Q0s(t.message),since:t.since??new Date().toISOString(),operation_id:hur(t.operation_id),...typeof t.anchorEntryId=="string"&&t.anchorEntryId!==""?{anchorEntryId:t.anchorEntryId}:{},...t.providerError===void 0?{}:{providerError:t.providerError}}}function X0s(t,e){DR({level:e.retry.disposition==="fatal"?"error":"warn",event:"fault.recorded",operation_id:e.operation_id,node_id:t,error_class:y8t(e),fields:{link:e.link,op:e.op,kind:e.kind,retry:e.retry,message:e.message,...e.anchorEntryId===void 0?{}:{anchor_entry_id:e.anchorEntryId},...e.providerError===void 0?{}:{provider_error:e.providerError}}})}function gur(t,e){let n=Y0s(e);X0s(t,n),K0s(t,n)}function RHe(t,e){try{let n=A8t(t);if(n===null||e?.link!==void 0&&n.link!==e.link)return!1;lur(b8t(t));let i=z0s(t);e?.preserveProviderRetryEpisode!==!0&&i?.fault.since===n.since&&i.state==="pending"&&lur(fur(t),{force:!0});let s=hur();return DR({level:"info",event:"fault.cleared",operation_id:s,node_id:t,error_class:y8t(n),fields:{cleared_fault_operation_id:n.operation_id,link:n.link,op:n.op,kind:n.kind,retry:n.retry,message:n.message,since:n.since,...n.anchorEntryId===void 0?{}:{anchor_entry_id:n.anchorEntryId}}}),!0}catch{return!1}}function ICe(t){return A8t(t)}function _ur(t,e,n=5e3){let i=/^[\x20-\x7e]+$/.test(e);return async function(a,u){if(!i)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let p={kind:"exec",bin:a,args:u},f=new AbortController,_=setTimeout(()=>f.abort(),n),m;try{m=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(p),signal:f.signal})}catch{return f.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(_)}return m.ok?await m.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${m.status} ${m.statusText}`}}}var v8t=1e3;function kF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z0s(t){if(!kF(t))return!1;let e=t.node;if(!kF(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!kF(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let i=t.paths;if(!kF(i)||typeof i.context_dir!="string"||typeof i.reports_dir!="string"||"session_file"in i&&i.session_file!==null&&typeof i.session_file!="string"||typeof t.follow_up!="string")return!1;let s=t.fault;if(s!=null){if(!kF(s)||typeof s.link!="string"||typeof s.kind!="string"||typeof s.since!="string")return!1;let a=s.retry;if(!kF(a)||typeof a.disposition!="string")return!1}return!0}function yur(t){return kF(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function ebs(t){return kF(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var V8=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=_ur(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<v8t)return n.value;let i=await this.execJson(["node","inspect","show",e]),s=Z0s(i)?{...i,fault:i.fault??null,reports:i.reports.filter(yur),managers:i.managers.filter(yur)}:null;return this.nodeCache.set(e,{value:s,at:Date.now()}),s}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,parent:n.parent??null,created:n.created,intent:n.intent??null,waiting_for:n.waiting_for??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null}:null}async listNodes(e){let n=JSON.stringify(e?.status??null),i=this.rosterCache.get(n);if(i&&Date.now()-i.at<v8t)return i.value;let s=["node","inspect","list"];e?.status&&s.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(","));let a=await this.execJson(s),p=(kF(a)&&Array.isArray(a.nodes)?a.nodes:[]).filter(ebs);return this.rosterCache.set(n,{value:p,at:Date.now()}),p}async subscriptionsOf(e){return((await this.fetchShow(e))?.reports??[]).map(i=>({node_id:i.node_id,active:i.active,created:""}))}async subscribersOf(e){return((await this.fetchShow(e))?.managers??[]).map(i=>({node_id:i.node_id,active:i.active,created:""}))}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<v8t)return n.value;let i=new Set([e]),s=[],a=(await this.subscriptionsOf(e)).map(u=>u.node_id);for(;a.length>0;){let u=a.shift();if(!i.has(u)){i.add(u),s.push(u);for(let p of await this.subscriptionsOf(u))i.has(p.node_id)||a.push(p.node_id)}}return this.viewCache.set(e,{value:s,at:Date.now()}),s}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return kF(n)&&kF(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(i=>i.active);for(let i of n){let s=await this.getRow(i.node_id);if(s&&(s.status==="active"||s.status==="idle"))return!0}return!1}};function x8t(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function w8t(t){let e=(t.description??"").trim(),i=[t.name&&t.name!==t.kind?t.name:"",e].filter(s=>s!=="").join(" ");return i!==""?i:t.name}function bur(t){return`${x8t(t.mode)} ${t.kind}`}var tbs=Cu(DX(),1);var Aur="38;5;243";var nbs={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},rbs={active:"32",idle:"33",done:"36",dead:"31",canceled:Aur},ibs="\u27F3",sbs="92",obs="\u25CC",abs="94",cbs="\u26A0",lbs="33";function vur(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function S8t(t){return t.frozen_at!=null&&t.pi_pid==null}function E8t(t,e){return e.hanging!=null?{glyph:cbs,color:lbs,word:vur(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:obs,color:abs,word:"frozen"}:e.streaming===!0?{glyph:ibs,color:sbs,word:"live",bold:!0}:{glyph:nbs[t]??"?",color:rbs[t]}}function ubs(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let i=n-e;return i<=0?"now":i>=6e4?`${Math.max(1,Math.round(i/6e4))}m`:`${Math.max(1,Math.ceil(i/1e3))}s`}function pbs(t){return t.retry.disposition!=="auto"}function dbs(t,e=Date.now()){let n=t.retry;if(!pbs(t)){if(n.by==="client")return"redialing";let i=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${i}, next ${ubs(n.nextAt,e)}`:i}return"needs you"}function C8t(t,e=Date.now()){return`${t.link} ${vur(t.kind)} \xB7 ${dbs(t,e)}`}function NHe(t,e){return e===null||e.link==="pi\u2192provider"&&e.retry.by==="daemon"&&e.retry.disposition==="auto"&&!EF(t.pi_pid)?null:e}var Eur=30,IF="\x1B[",rg=`${IF}0m`,PCe=`${IF}1m`,N1=`${IF}2m`,gq=`${IF}7m`,Cur=`${IF}48;5;22m`,MHe=`${IF}32m`,fwc=`${IF}31m`,DCe=`${IF}33m`,mwc=`${IF}36m`,hwc=`${IF}90m`;function fbs(t){return NHe(t,ICe(t.node_id))}function mbs(t){return t.status!=="active"&&t.status!=="idle"||!EF(t.pi_pid)?!1:iur(t.node_id)}function OHe(t,e=!1){if(t===null)return"?";let n=E8t(t.status,{streaming:e?!1:mbs(t),frozen:S8t(t),hanging:e?null:fbs(t)});return`${IF}${n.color}m${n.glyph}${rg}`}var Tur=/\x1b\[[0-9;]*m/g;function MX(t){return t.replace(Tur,"")}function _I(t){return t.replace(Tur,"").length}function H8(t,e=PF()){if(_I(t)<=e)return t;let n="",i=0,s=0;for(;s<t.length&&i<e-1;){if(t[s]==="\x1B"){let a=/^\x1b\[[0-9;]*m/.exec(t.slice(s));if(a){n+=a[0],s+=a[0].length;continue}}n+=t[s],i++,s++}return`${n}\u2026${rg}`}function PF(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function J8(t,e,n){let i=H8(t,e),s=i.replace(/\x1b\[0m/g,`${rg}${n}`),a=Math.max(0,e-_I(i));return`${n}${s}${" ".repeat(a)}${rg}`}var T8t=new Map;function RCe(){T8t.clear()}function kur(t){let e=T8t.get(t);if(e!==void 0)return e;let n;try{let i=Sur(PR(t),"telemetry.json");n=xur(i)?JSON.parse(wur(i,"utf8")):{}}catch{n={}}return T8t.set(t,n),n}function hbs(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function FHe(t,e=!1){return hbs(e?0:kur(t).context_tokens??0)}function LHe(t,e,n=!1){if(n||e?.status!=="active")return"";let i=(kur(t).last_activity??"").trim();return i===""?"":` ${N1}\xB7 ${i}${rg}`}function BHe(t){let e=t?.cycles??0;return e>0?` ${N1}\u27F3${e}${rg}`:""}function OX(t,e){if(t===null)return $He(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let i=(t.description??"").trim();return i!==""?i:t.name}function $He(t){return t.slice(0,8)}function gbs(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let i=Sur(PR(t),"attach.json");if(!xur(i))return!1;let s=JSON.parse(wur(i,"utf8"));return typeof s.viewers=="number"&&s.viewers>0}catch{return!1}}function Iur(t,e,n,i=!1){return i?!1:n.has(t)?!0:gbs(t,e,i)}function UHe(t,e){let n=e[t]??0;return n>0?` ${DCe}\u2691${n}${rg}`:""}var gwc=`${N1}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${rg}`;var _bs=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message"];function FX(t,e,n){return vH(t,e,AH(n),(i,s)=>za(i,s))}function k8t(t,e){e[t]()}function Pur(t,e,n){for(let{actionId:i}of qB)if(FX(t,i,e))return k8t(i,n),!0;return!1}function Dur(t,e,n){for(let i of _bs)if(FX(t,i,e))return n[i](),!0;return!1}function Rur(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return qS(t,e)}function Nur(t){return t.gestures("crtr.attach.detach").length>0?qS(t,"crtr.attach.detach"):void 0}function I8t(t,e,n,i){let s=t();if(e(s.bindings),n())try{i(s.bindings,s.tmuxPassthrough)}catch{}return s}function Mur(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function Our(t,e,n,i,s){let a="closed",u=0,p="",f=()=>t.terminal.columns,_=D=>{D!==void 0&&n.scrollToLine(D.line),t.requestRender()},m=()=>{i.setQuery(p,u),_(i.current(f()))},b=()=>{a="closed",p="",i.setQuery("",void 0),t.requestRender()},x=()=>{a==="closed"&&(u=n.topLine()??0),a="editing",p=i.query(),t.requestRender()},k=D=>{let R=i.step(f(),D);if(R===void 0){s.setNotice(`No matches for \u201C${i.query()}\u201D`);return}_(R)};return{component:{render(D){if(a==="closed")return[];let{index:R,total:F}=i.status(D),L=a==="editing"?`${e.accent("\u2315")} ${p}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${p}`,U=F===0?i.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${R}/${F}`),Y=a==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${qS(s.bindings(),"crtr.attach.search.next")} next`,`${qS(s.bindings(),"crtr.attach.search.previous")} prev`,`${qS(s.bindings(),"crtr.attach.search.edit")} edit`,`${qS(s.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),V=`${U} ${Y}`,z=D-_I(L)-_I(V)-2;return[z<1?Ha(` ${L}`,D,"",!0):` ${L}${" ".repeat(z)}${V} `]},invalidate(){}},open:x,close:b,handleKey:D=>{if(a==="closed")return!1;let R=s.bindings();if(FX(R,"crtr.attach.search.close",D))return b(),!0;if(a==="editing"){if(D==="")return b(),!0;if(D==="\r"||D===`
2050
+ `))}toolResultText(e){if(typeof e=="string")return e;if(typeof e=="object"&&e!==null&&"content"in e){let n=e.content;if(typeof n=="string")return n;if(Array.isArray(n))return n.filter(i=>typeof i=="object"&&i!==null&&i.type==="text"&&typeof i.text=="string").map(i=>i.text).join("")}try{let n=JSON.stringify(e);return typeof n=="string"?n:""}catch{return""}}pushTranscriptText(e){let n=e.trim();if(n==="")return;let i=n5t([n],this.cwd);if(i.length===0)return;let s=[...i,...this.transcriptFilePaths.filter(a=>!i.includes(a))].slice(0,50);this.transcriptFilePaths.splice(0,this.transcriptFilePaths.length,...s)}pushTranscriptValue(e){try{let n=typeof e=="string"?e:JSON.stringify(e);typeof n=="string"&&this.pushTranscriptText(n)}catch{}}userMessageText(e){let n=e.content;return typeof n=="string"?n:Array.isArray(n)?n.filter(i=>typeof i=="object"&&i!==null&&i.type==="text").map(i=>i.text).join(""):""}};var d0s="\x1B[2m\u2338 image \u2014 scroll to view\x1B[22m",kCe={first:-1,last:-1,lastFullyVisible:-1};function f0s(t){return t.some(e=>e.includes("\x1B_G")||e.includes("\x1B]1337;File="))}function m0s(t,e,n){let i=0,s=t.blockCount();for(;i<s;){let a=Math.floor((i+s)/2);t.blockStart(a,n)+t.blockHeight(a,n)>e?s=a:i=a+1}return i}function eur(t,e){let n={follow:!0,anchor:void 0},i,s=0,a=kCe,u;function p(m,b,x){let k=Math.max(0,x-b);if(n.follow)return k;if(!n.anchor)return n.follow=!0,k;let I=t.anchorLine(n.anchor,m);return I===void 0?(n.follow=!0,n.anchor=void 0,k):Math.min(Math.max(0,I),k)}function f(m,b,x,k){let I=Math.min(x,k+b);if(k>=I)return{top:k,bottom:I,total:x,blocks:kCe};let C=t.blockCount(),D=m0s(t,k,m),R=-1,F=-1,L=-1;for(;D<C;){let U=t.blockStart(D,m);if(U>=I)break;let Y=t.blockHeight(D,m),V=U+Y;V>k&&(R===-1&&(R=D),F=D,U>=k&&V<=I&&(L=D)),D++}return{top:k,bottom:I,total:x,blocks:R===-1?kCe:{first:R,last:F,lastFullyVisible:L}}}function _(){if(i===void 0||s<=0)return;let m=t.totalHeight(i),b=p(i,s,m);return f(i,s,m,b)}return{renderSlice(m,b){let x=Math.max(0,b);if(i=m,s=x,x===0)return a=kCe,u=t.revision(),[];let k=t.totalHeight(m),I=p(m,x,k),C=f(m,x,k,I),D=[];for(let F=C.blocks.first;F!==-1&&F<=C.blocks.last;F++){let L=t.blockStart(F,m),U=t.blockLines(F,m),Y=t.blockHeight(F,m),V=L+Y,z=Math.max(0,C.top-L),te=Math.min(Y,C.bottom-L);if(z>=te)continue;if((L<C.top||V>C.bottom)&&f0s(U))D.push(...Array(te-z).fill(d0s));else if(e===void 0)D.push(...U.slice(z,te));else for(let he=z;he<te;he++)D.push(e(L+he,U[he],m))}let R=D.length>=x?D.slice(0,x):[...Array(x-D.length).fill(""),...D];return a=C.blocks,u=t.revision(),R},scrollBy(m){if(i===void 0||s<=0||m===0)return!1;let b=n.follow,x=n.anchor,k=t.totalHeight(i),I=p(i,s,k),C=Math.max(0,k-s),D=Math.min(Math.max(0,I+m),C);return D>=C?(n.follow=!0,n.anchor=void 0):(n.follow=!1,n.anchor=t.anchorAt(D,i),n.anchor||(n.follow=!0)),n.follow!==b||n.anchor!==x},pageRows(){return Math.max(0,s-1)},goLive(){n.follow=!0,n.anchor=void 0},scrollToLine(m){if(i===void 0||s<=0)return;let b=t.totalHeight(i),x=Math.max(0,b-s),k=Math.min(Math.max(0,m-Math.floor(s/3)),x);if(k>=x){n.follow=!0,n.anchor=void 0;return}n.follow=!1,n.anchor=t.anchorAt(k,i),n.anchor||(n.follow=!0)},topLine(){if(!(i===void 0||s<=0))return p(i,s,t.totalHeight(i))},isLive(){return n.follow},visibleBlocks(){let m=t.revision();return u===m||(a=_()?.blocks??kCe,u=m),a},invalidate(){t.invalidate()}}}var h0s=new Intl.Segmenter(void 0,{granularity:"grapheme"}),g0s="\x1B[7m",_0s="\x1B[27m";function y0s(t,e){let n=t[e+1];if(n!==void 0){if(n==="]"||n==="_"||n==="P"||n==="^"){let i=t.indexOf("\x07",e+2),s=t.indexOf("\x1B\\",e+2),a=i===-1?s:s===-1?i:Math.min(i,s);return a===-1?void 0:{text:t.slice(e,a+(a===i?1:2)),end:a+(a===i?1:2)}}if(n==="["){let i=e+2;for(;i<t.length&&(t.charCodeAt(i)<64||t.charCodeAt(i)>126);)i++;return i>=t.length?void 0:{text:t.slice(e,i+1),end:i+1}}return{text:t.slice(e,e+2),end:e+2}}}function THe(t,e){let n=0,i=0;for(;i<t.length;){if(t[i]==="\x1B"){let u=y0s(t,i);if(u===void 0)break;e.onEscape?.(u.text),i=u.end;continue}let s=t.indexOf("\x1B",i),a=t.slice(i,s===-1?void 0:s);for(let u of h0s.segment(a)){let p=Hv(u.segment);e.onGlyph?.({text:u.segment,cell:n,width:p}),n+=p}i=s===-1?t.length:s}return n}function tur(t,e,n){let i="";return THe(t,{onGlyph:s=>{s.cell>=e&&s.cell<n&&(i+=s.text)}}),i}var b0s={on:g0s,off:_0s};function g8t(t,e,n,i,s=b0s){let a=Math.min(n,i);if(a<=e||e<0)return t;let u="",p=!1,f=[],_=()=>{p||(u+=s.on,p=!0)},m=()=>{p&&(u+=s.restore===!0?`\x1B[0m${f.join("")}`:s.off,p=!1)},b=THe(t,{onEscape:x=>{u+=x,x.endsWith("m")&&(x==="\x1B[0m"||x==="\x1B[m"?f.length=0:f.push(x),p&&(u+=s.on))},onGlyph:x=>{x.cell>=e&&x.cell<a?_():m(),u+=x.text}});if(m(),b<a){let x=Math.max(0,e-b),k=a-Math.max(e,b);u+=" ".repeat(x)+s.on+" ".repeat(k)+(s.restore===!0?"\x1B[0m":s.off)}return u}function nur(t,e,n,i){return g8t(t,e,n,i)}var A0s={on:"\x1B[107m\x1B[30m",off:"",restore:!0},v0s={on:"\x1B[48;5;214m\x1B[30m",off:"",restore:!0};function x0s(t){let e="",n=[],i=THe(t,{onGlyph:s=>{for(let a=0;a<s.text.length;a++)n.push(s.cell);e+=s.text}});return{text:e,cells:n,width:i}}function w0s(t){return t!==t.toLowerCase()}function S0s(t,e,n,i,s){let a=n?t.text:t.text.toLowerCase(),u=n?e:e.toLowerCase(),p=a.indexOf(u);for(;p!==-1;){let f=p+u.length,_=t.cells[p]??0,m=f<t.cells.length?t.cells[f]:t.width;m>_&&s.push({line:i,from:_,to:m}),p=a.indexOf(u,p+Math.max(1,u.length))}}function rur(t){let e="",n=0,i=[],s=new Map,a,u;function p(f){let _=`${f}:${t.revision()}:${e}`;if(a===_)return i;let m=[];if(e!==""){let x=w0s(e),k=t.blockCount();for(let I=0;I<k;I++){let C=t.blockStart(I,f),D=t.blockLines(I,f);for(let R=0;R<D.length;R++){let F=D[R];F.toLowerCase().includes(e.toLowerCase())&&S0s(x0s(F),e,x,C+R,m)}}}let b=new Map;for(let x of m){let k=b.get(x.line);k?k.push(x):b.set(x.line,[x])}if(i=m,s=b,a=_,u!==void 0){let x=u;u=void 0;let k=m.findIndex(I=>I.line>=x);n=k===-1?Math.max(0,m.length-1):k}else n>=m.length&&(n=Math.max(0,m.length-1));return i}return{setQuery(f,_){f!==e&&(e=f,u=_,a=void 0)},query(){return e},matches(f){return p(f)},current(f){return p(f)[n]},status(f){let _=p(f);return{index:_.length===0?0:n+1,total:_.length}},step(f,_){let m=p(f);if(m.length!==0)return n=(n+_+m.length)%m.length,m[n]},selectNear(f,_){let m=p(f);if(m.length===0)return;let b=m.findIndex(x=>x.line>=_);return n=b===-1?m.length-1:b,m[n]},decorate(f,_,m){if(e==="")return _;let b=p(m),x=s.get(f);if(x===void 0)return _;let k=b[n],I=_;for(let C of x)I=g8t(I,C.from,C.to,m,C===k?v0s:A0s);return I}}}import{existsSync as xur,readFileSync as wur}from"node:fs";import{join as Sur}from"node:path";import{existsSync as E0s,readFileSync as axc,writeFileSync as cxc,rmSync as lxc,mkdirSync as uxc,statSync as pxc}from"node:fs";import{join as C0s}from"node:path";function T0s(t){return C0s(PR(t),"busy")}function iur(t){return E0s(T0s(t))}function G8(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}import{existsSync as kxc,mkdirSync as L0s,readFileSync as pur,realpathSync as B0s,rmSync as lur,writeFileSync as $0s}from"node:fs";import{join as dur}from"node:path";var k0s="crtr:managed-provider-cooling";function sur(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===k0s)}function _8t(t){return typeof t=="string"?t:""}function $D(t,e,n={}){return{kind:t,matchedOn:e,...n}}function TF(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}var I0s=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]];function our(t){let e=I0s.flatMap(([i,s])=>{let a=t.match(s);return a?[{kind:i,match:a[0]}]:[]}),n=e[0];return n===void 0?$D("other","none"):{...$D(n.kind,"text",{match:n.match}),textMatches:e}}function aur(t){let e=t.retryAfterMs,n=our(t.message??""),i=_8t(t.code)||_8t(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(i))return TF($D("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(i))return TF($D("overloaded","errno",{retryAfterMs:e}),n);let s=typeof t.status=="number"?t.status:void 0;if(s!==void 0){if(s===401||s===403)return TF($D("auth","status",{status:s,retryAfterMs:e}),n);if(s===429)return TF($D("rate-limit","status",{status:s,retryAfterMs:e}),n);if(s===500||s===502||s===503||s===504)return TF($D("transient-http","status",{status:s,retryAfterMs:e}),n);if(s>=500&&s<=599)return TF($D("overloaded","status",{status:s,retryAfterMs:e}),n);if(s>=400&&s<=499)return TF($D("protocol","status",{status:s,retryAfterMs:e}),n)}let a=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(a===1008)return TF($D("protocol","websocket-close",{retryAfterMs:e}),n);if(a===1006)return TF($D("connection","websocket-close",{retryAfterMs:e}),n);if(a===1011){let u=_8t(t.wsCloseReason),p=our(u);return/no running broker/i.test(u)||p.kind==="connection"||p.kind==="connection-only"?TF($D("connection","websocket-close",{retryAfterMs:e}),n):TF($D("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}var P0s="crtr:provider-failure";function ON(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function IHe(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function PHe(t){return typeof t=="string"||typeof t=="number"?t:void 0}function kHe(t){return G8(t)?t:void 0}function D0s(t){let e=ON(t.errorMessage)??ON(t.message)??ON(t.reason)??ON(t.statusText),n={...e===void 0?{}:{message:e},...IHe(t.status)===void 0?{}:{status:IHe(t.status)},...PHe(t.code)===void 0?{}:{code:PHe(t.code)},...ON(t.errno)===void 0?{}:{errno:ON(t.errno)},...ON(t.body)===void 0?{}:{body:ON(t.body)}};return Object.keys(n).length===0?void 0:n}function R0s(t){let e=kHe(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let i=kHe(n);if(i?.type!==P0s)continue;let s=kHe(i.details);if(s===void 0)continue;let a=Array.isArray(s.causes)?s.causes.flatMap(u=>{let p=kHe(u),f=p===void 0?void 0:D0s(p);return f===void 0?[]:[f]}):void 0;return{...IHe(s.status)===void 0?{}:{status:IHe(s.status)},...PHe(s.code)===void 0?{}:{code:PHe(s.code)},...ON(s.errno)===void 0?{}:{errno:ON(s.errno)},...ON(s.body)===void 0?{}:{body:ON(s.body)},...a===void 0||a.length===0?{}:{causes:a}}}}function cur(t){return R0s(t)}var N0s={"rate-limit":"rate_limit",overloaded:"overloaded",connection:"connection",auth:"auth",protocol:"protocol","context-overflow":"context_overflow",wedged:"wedged","model-not-found":"model_not_found",other:"unknown"};function y8t(t){return{class:N0s[t.kind],retry_disposition:t.retry.disposition}}function M0s(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function O0s(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function F0s(t){if(typeof t=="string")return t;if(!G8(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let i of e)if(typeof i=="string"&&i!=="")return i;let n=t.error;if(G8(n)){let i=n.message;if(typeof i=="string"&&i!=="")return i;let s=n.reason;if(typeof s=="string"&&s!=="")return s}return""}function DHe(t,e){if(t==="pi\u2192provider"&&sur(e))return{kind:"rate-limit",disposition:"auto"};let n=G8(e)?e:{},i=cur(e),s=i?.causes??[],a=aur({code:n.code??i?.code??s.find(p=>p.code!==void 0)?.code,errno:n.errno??i?.errno??s.find(p=>p.errno!==void 0)?.errno,status:n.status??i?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[F0s(e),i?.body,...s.flatMap(p=>[p.message,p.body])].filter(p=>typeof p=="string"&&p!=="").join(" ")}),u=M0s(a);return{kind:u,disposition:O0s(t,u)}}var U0s=5*6e4,j0s=500;function b8t(t){return dur(PR(t),"fault")}function fur(t){return dur(PR(t),"provider-retry")}function W0s(t){try{return B0s(t)}catch{return t}}function Q0s(t){return t.slice(0,j0s)}function uur(t){return t.link==="pi\u2192provider"&&t.retry.disposition==="auto"&&t.retry.by==="daemon"?3:t.retry.disposition==="fatal"?2:1}var q0s=["pi\u2192provider","viewer\u2194broker","relay\u2194broker","viewer\u2194crtrd","broker\u2194crtrd","daemon\u2192node","crtr\u2192pi"],G0s=["rate-limit","overloaded","connection","auth","protocol","context-overflow","other","wedged","model-not-found"];function V0s(t){if(!G8(t)||typeof t.provider!="string"||t.provider===""||typeof t.model!="string"||t.model==="")return;let e=typeof t.status=="number"&&Number.isFinite(t.status)?t.status:void 0,n=typeof t.code=="string"||typeof t.code=="number"?t.code:void 0,i=typeof t.errno=="string"?t.errno:void 0,s=typeof t.body=="string"?t.body:void 0,a=Array.isArray(t.causes)?t.causes.flatMap(u=>{if(!G8(u))return[];let p={...typeof u.message=="string"?{message:u.message}:{},...typeof u.status=="number"&&Number.isFinite(u.status)?{status:u.status}:{},...typeof u.code=="string"||typeof u.code=="number"?{code:u.code}:{},...typeof u.errno=="string"?{errno:u.errno}:{},...typeof u.body=="string"?{body:u.body}:{}};return Object.keys(p).length===0?[]:[p]}):void 0;return{provider:t.provider,model:t.model,...e===void 0?{}:{status:e},...n===void 0?{}:{code:n},...i===void 0?{}:{errno:i},...s===void 0?{}:{body:s},...a===void 0||a.length===0?{}:{causes:a}}}function mur(t){try{let e=JSON.parse(t);if(!q0s.includes(e.link)||typeof e.op!="string"||e.op===""||!G0s.includes(e.kind)||typeof e.message!="string"||typeof e.since!="string")return null;let n=mH(e.operation_id),i=e.retry;if(i===void 0||i.disposition!=="auto"&&i.disposition!=="manual"&&i.disposition!=="fatal"||i.by!==void 0&&i.by!=="sdk"&&i.by!=="daemon"&&i.by!=="client"||i.attempt!==void 0&&typeof i.attempt!="number"||i.max!==void 0&&typeof i.max!="number"||i.nextAt!==void 0&&typeof i.nextAt!="string"||e.anchorEntryId!==void 0&&(typeof e.anchorEntryId!="string"||e.anchorEntryId===""))return null;let s=e.providerError===void 0?void 0:V0s(e.providerError);return e.providerError!==void 0&&s===void 0?null:{link:e.link,op:e.op,kind:e.kind,retry:{disposition:i.disposition,...i.by===void 0?{}:{by:i.by},...i.attempt===void 0?{}:{attempt:i.attempt},...i.max===void 0?{}:{max:i.max},...i.nextAt===void 0?{}:{nextAt:i.nextAt}},message:e.message,since:e.since,operation_id:n,...e.anchorEntryId===void 0?{}:{anchorEntryId:e.anchorEntryId},...s===void 0?{}:{providerError:s}}}catch{return null}}function A8t(t){try{return mur(pur(b8t(t),"utf8"))}catch{return null}}function z0s(t){try{let e=JSON.parse(pur(fur(t),"utf8"));if(e.state!=="pending"&&e.state!=="admitted"&&e.state!=="invalidated"||typeof e.sessionFile!="string"||e.sessionFile===""||e.anchorEntryId!==null&&typeof e.anchorEntryId!="string")return null;let n=mur(JSON.stringify(e.fault));return n===null||n.link!=="pi\u2192provider"||n.retry.disposition!=="auto"||n.retry.by!=="daemon"||(n.anchorEntryId??null)!==e.anchorEntryId?null:{state:e.state,sessionFile:W0s(e.sessionFile),anchorEntryId:e.anchorEntryId,fault:n}}catch{return null}}function H0s(t,e){try{return L0s(PR(t),{recursive:!0}),$0s(b8t(t),JSON.stringify(e)),!0}catch{return!1}}function J0s(t,e){let n=A8t(t);if(n===null)return e;if(n.link===e.link&&n.kind===e.kind){let i={...n.retry,...e.retry};return e.retry.disposition==="fatal"&&!("nextAt"in e.retry)&&delete i.nextAt,{...e,since:n.since,anchorEntryId:n.anchorEntryId??e.anchorEntryId,retry:i}}return uur(n)>uur(e)?null:e}function K0s(t,e){let n=J0s(t,e);return n!==null&&H0s(t,n)?n:null}function hur(t){if(t!==void 0)return mH(t);let e=cbe.current();return e!==void 0?e:cbe.fresh(n=>n)}function Y0s(t){return{link:t.link,op:t.op,kind:t.kind,retry:t.retry,message:Q0s(t.message),since:t.since??new Date().toISOString(),operation_id:hur(t.operation_id),...typeof t.anchorEntryId=="string"&&t.anchorEntryId!==""?{anchorEntryId:t.anchorEntryId}:{},...t.providerError===void 0?{}:{providerError:t.providerError}}}function X0s(t,e){DR({level:e.retry.disposition==="fatal"?"error":"warn",event:"fault.recorded",operation_id:e.operation_id,node_id:t,error_class:y8t(e),fields:{link:e.link,op:e.op,kind:e.kind,retry:e.retry,message:e.message,...e.anchorEntryId===void 0?{}:{anchor_entry_id:e.anchorEntryId},...e.providerError===void 0?{}:{provider_error:e.providerError}}})}function gur(t,e){let n=Y0s(e);X0s(t,n),K0s(t,n)}function RHe(t,e){try{let n=A8t(t);if(n===null||e?.link!==void 0&&n.link!==e.link)return!1;lur(b8t(t));let i=z0s(t);e?.preserveProviderRetryEpisode!==!0&&i?.fault.since===n.since&&i.state==="pending"&&lur(fur(t),{force:!0});let s=hur();return DR({level:"info",event:"fault.cleared",operation_id:s,node_id:t,error_class:y8t(n),fields:{cleared_fault_operation_id:n.operation_id,link:n.link,op:n.op,kind:n.kind,retry:n.retry,message:n.message,since:n.since,...n.anchorEntryId===void 0?{}:{anchor_entry_id:n.anchorEntryId}}}),!0}catch{return!1}}function ICe(t){return A8t(t)}function _ur(t,e,n=5e3){let i=/^[\x20-\x7e]+$/.test(e);return async function(a,u){if(!i)return{ok:!1,stdout:"",stderr:"remote source: invalid stored relay token"};let p={kind:"exec",bin:a,args:u},f=new AbortController,_=setTimeout(()=>f.abort(),n),m;try{m=await fetch(new URL("/__crtr/source",t),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e}`},body:JSON.stringify(p),signal:f.signal})}catch{return f.signal.aborted?{ok:!1,stdout:"",stderr:`remote source: timeout after ${n}ms`}:{ok:!1,stdout:"",stderr:"remote source: network error"}}finally{clearTimeout(_)}return m.ok?await m.json():{ok:!1,stdout:"",stderr:`remote source: HTTP ${m.status} ${m.statusText}`}}}var v8t=1e3;function kF(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Z0s(t){if(!kF(t))return!1;let e=t.node;if(!kF(e)||typeof e.node_id!="string"||!Array.isArray(t.reports)||!Array.isArray(t.managers))return!1;let n=t.artifacts;if(!kF(n)||typeof n.report!="number"||typeof n.doc!="number"||typeof n.roadmap!="number"||typeof t.pending_crons!="number")return!1;let i=t.paths;if(!kF(i)||typeof i.context_dir!="string"||typeof i.reports_dir!="string"||"session_file"in i&&i.session_file!==null&&typeof i.session_file!="string"||typeof t.follow_up!="string")return!1;let s=t.fault;if(s!=null){if(!kF(s)||typeof s.link!="string"||typeof s.kind!="string"||typeof s.since!="string")return!1;let a=s.retry;if(!kF(a)||typeof a.disposition!="string")return!1}return!0}function yur(t){return kF(t)&&typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.status=="string"&&typeof t.active=="boolean"}function ebs(t){return kF(t)?typeof t.node_id=="string"&&typeof t.name=="string"&&typeof t.kind=="string"&&typeof t.mode=="string"&&typeof t.lifecycle=="string"&&typeof t.status=="string"&&typeof t.cwd=="string"&&typeof t.created=="string":!1}var V8=class{constructor(e,n){this.previewEndpoint=e;this.relayToken=n;this.exec=_ur(e,n)}previewEndpoint;relayToken;exec;nodeCache=new Map;rosterCache=new Map;viewCache=new Map;async execJson(e){let n;try{n=await this.exec("crtr",["--json",...e])}catch{return null}if(!n.ok||n.exitCode!==void 0&&n.exitCode!==0)return null;try{return JSON.parse(n.stdout.trim())}catch{return null}}async fetchShow(e){let n=this.nodeCache.get(e);if(n&&Date.now()-n.at<v8t)return n.value;let i=await this.execJson(["node","inspect","show",e]),s=Z0s(i)?{...i,fault:i.fault??null,reports:i.reports.filter(yur),managers:i.managers.filter(yur)}:null;return this.nodeCache.set(e,{value:s,at:Date.now()}),s}async rawShow(e){return this.fetchShow(e)}async getNode(e){return(await this.fetchShow(e))?.node??null}async getRow(e){let n=(await this.fetchShow(e))?.node;return n?{node_id:n.node_id,name:n.name,kind:n.kind,mode:n.mode,lifecycle:n.lifecycle,status:n.status,cwd:n.cwd,host_kind:n.host_kind??null,profile_id:n.profile_id??null,parent:n.parent??null,created:n.created,intent:n.intent??null,waiting_for:n.waiting_for??null,frozen_at:n.frozen_at??null,terminal_reason:n.terminal_reason??null,pi_pid:n.pi_pid??null,pi_pid_identity:n.pi_pid_identity??null,window:n.window??null,tmux_session:n.tmux_session??null,pane:n.pane??null}:null}async listNodes(e){let n=JSON.stringify(e?.status??null),i=this.rosterCache.get(n);if(i&&Date.now()-i.at<v8t)return i.value;let s=["node","inspect","list"];e?.status&&s.push("--status",(Array.isArray(e.status)?e.status:[e.status]).join(","));let a=await this.execJson(s),p=(kF(a)&&Array.isArray(a.nodes)?a.nodes:[]).filter(ebs);return this.rosterCache.set(n,{value:p,at:Date.now()}),p}async subscriptionsOf(e){return((await this.fetchShow(e))?.reports??[]).map(i=>({node_id:i.node_id,active:i.active,created:""}))}async subscribersOf(e){return((await this.fetchShow(e))?.managers??[]).map(i=>({node_id:i.node_id,active:i.active,created:""}))}async view(e){let n=this.viewCache.get(e);if(n&&Date.now()-n.at<v8t)return n.value;let i=new Set([e]),s=[],a=(await this.subscriptionsOf(e)).map(u=>u.node_id);for(;a.length>0;){let u=a.shift();if(!i.has(u)){i.add(u),s.push(u);for(let p of await this.subscriptionsOf(u))i.has(p.node_id)||a.push(p.node_id)}}return this.viewCache.set(e,{value:s,at:Date.now()}),s}async ticketCountsForView(e){let n=await this.execJson(["canvas","attention","map","--view",e]);return kF(n)&&kF(n.counts)?n.counts:{}}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(i=>i.active);for(let i of n){let s=await this.getRow(i.node_id);if(s&&(s.status==="active"||s.status==="idle"))return!0}return!1}};function x8t(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function w8t(t){let e=(t.description??"").trim(),i=[t.name&&t.name!==t.kind?t.name:"",e].filter(s=>s!=="").join(" ");return i!==""?i:t.name}function bur(t){return`${x8t(t.mode)} ${t.kind}`}var tbs=Cu(DX(),1);var Aur="38;5;243";var nbs={active:"\u25CF",idle:"\u25CB",done:"\u2713",dead:"\u2717",canceled:"\u2298"},rbs={active:"32",idle:"33",done:"36",dead:"31",canceled:Aur},ibs="\u27F3",sbs="92",obs="\u25CC",abs="94",cbs="\u26A0",lbs="33";function vur(t){switch(t){case"rate-limit":return"rate-limited";case"overloaded":return"overloaded";case"connection":return"down";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"wedged":return"wedged";case"model-not-found":return"model-not-found";default:return"other"}}function S8t(t){return t.frozen_at!=null&&t.pi_pid==null}function E8t(t,e){return e.hanging!=null?{glyph:cbs,color:lbs,word:vur(e.hanging.kind),bold:!0}:e.frozen===!0?{glyph:obs,color:abs,word:"frozen"}:e.streaming===!0?{glyph:ibs,color:sbs,word:"live",bold:!0}:{glyph:nbs[t]??"?",color:rbs[t]}}function ubs(t,e){let n=Date.parse(t);if(Number.isNaN(n))return"now";let i=n-e;return i<=0?"now":i>=6e4?`${Math.max(1,Math.round(i/6e4))}m`:`${Math.max(1,Math.ceil(i/1e3))}s`}function pbs(t){return t.retry.disposition!=="auto"}function dbs(t,e=Date.now()){let n=t.retry;if(!pbs(t)){if(n.by==="client")return"redialing";let i=typeof n.attempt=="number"&&typeof n.max=="number"?`auto-retry ${n.attempt}/${n.max}`:"auto-retrying";return n.nextAt?`${i}, next ${ubs(n.nextAt,e)}`:i}return"needs you"}function C8t(t,e=Date.now()){return`${t.link} ${vur(t.kind)} \xB7 ${dbs(t,e)}`}function NHe(t,e){return e===null||e.link==="pi\u2192provider"&&e.retry.by==="daemon"&&e.retry.disposition==="auto"&&!EF(t.pi_pid)?null:e}var iwc=1<<20,swc=1<<20,owc=4<<20;var Eur=30,IF="\x1B[",rg=`${IF}0m`,PCe=`${IF}1m`,N1=`${IF}2m`,gq=`${IF}7m`,Cur=`${IF}48;5;22m`,MHe=`${IF}32m`,gwc=`${IF}31m`,DCe=`${IF}33m`,_wc=`${IF}36m`,ywc=`${IF}90m`;function fbs(t){return NHe(t,ICe(t.node_id))}function mbs(t){return t.status!=="active"&&t.status!=="idle"||!EF(t.pi_pid)?!1:iur(t.node_id)}function OHe(t,e=!1){if(t===null)return"?";let n=E8t(t.status,{streaming:e?!1:mbs(t),frozen:S8t(t),hanging:e?null:fbs(t)});return`${IF}${n.color}m${n.glyph}${rg}`}var Tur=/\x1b\[[0-9;]*m/g;function MX(t){return t.replace(Tur,"")}function _I(t){return t.replace(Tur,"").length}function H8(t,e=PF()){if(_I(t)<=e)return t;let n="",i=0,s=0;for(;s<t.length&&i<e-1;){if(t[s]==="\x1B"){let a=/^\x1b\[[0-9;]*m/.exec(t.slice(s));if(a){n+=a[0],s+=a[0].length;continue}}n+=t[s],i++,s++}return`${n}\u2026${rg}`}function PF(){return Math.max(20,Math.min((process.stdout.columns??80)-2,180))}function J8(t,e,n){let i=H8(t,e),s=i.replace(/\x1b\[0m/g,`${rg}${n}`),a=Math.max(0,e-_I(i));return`${n}${s}${" ".repeat(a)}${rg}`}var T8t=new Map;function RCe(){T8t.clear()}function kur(t){let e=T8t.get(t);if(e!==void 0)return e;let n;try{let i=Sur(PR(t),"telemetry.json");n=xur(i)?JSON.parse(wur(i,"utf8")):{}}catch{n={}}return T8t.set(t,n),n}function hbs(t){return t<1e3?`${t}`:`${Math.round(t/1e3)}k`}function FHe(t,e=!1){return hbs(e?0:kur(t).context_tokens??0)}function LHe(t,e,n=!1){if(n||e?.status!=="active")return"";let i=(kur(t).last_activity??"").trim();return i===""?"":` ${N1}\xB7 ${i}${rg}`}function BHe(t){let e=t?.cycles??0;return e>0?` ${N1}\u27F3${e}${rg}`:""}function OX(t,e){if(t===null)return $He(e);let n=t.name&&t.name!==t.kind?t.name:"";if(n!=="")return n;let i=(t.description??"").trim();return i!==""?i:t.name}function $He(t){return t.slice(0,8)}function gbs(t,e,n=!1){if(n||e?.status!=="active")return!1;try{let i=Sur(PR(t),"attach.json");if(!xur(i))return!1;let s=JSON.parse(wur(i,"utf8"));return typeof s.viewers=="number"&&s.viewers>0}catch{return!1}}function Iur(t,e,n,i=!1){return i?!1:n.has(t)?!0:gbs(t,e,i)}function UHe(t,e){let n=e[t]??0;return n>0?` ${DCe}\u2691${n}${rg}`:""}var bwc=`${N1}jk move \xB7 hl fold \xB7 \u21B5 focus \xB7 e expand \xB7 x kill \xB7 m mgr \xB7 esc${rg}`;var _bs=["crtr.attach.scroll.up","crtr.attach.scroll.down","crtr.attach.scroll.page-up","crtr.attach.scroll.page-down","crtr.attach.scroll.live","crtr.attach.mouse.toggle","crtr.attach.copy.message"];function FX(t,e,n){return vH(t,e,AH(n),(i,s)=>za(i,s))}function k8t(t,e){e[t]()}function Pur(t,e,n){for(let{actionId:i}of qB)if(FX(t,i,e))return k8t(i,n),!0;return!1}function Dur(t,e,n){for(let i of _bs)if(FX(t,i,e))return n[i](),!0;return!1}function Rur(t){for(let e of["crtr.attach.clear-or-detach","crtr.attach.detach"])if(t.gestures(e).length>0)return qS(t,e)}function Nur(t){return t.gestures("crtr.attach.detach").length>0?qS(t,"crtr.attach.detach"):void 0}function I8t(t,e,n,i){let s=t();if(e(s.bindings),n())try{i(s.bindings,s.tmuxPassthrough)}catch{}return s}function Mur(t){if(t!==""){for(let e of t){let n=e.codePointAt(0);if(n<32||n===127)return}return t}}function Our(t,e,n,i,s){let a="closed",u=0,p="",f=()=>t.terminal.columns,_=D=>{D!==void 0&&n.scrollToLine(D.line),t.requestRender()},m=()=>{i.setQuery(p,u),_(i.current(f()))},b=()=>{a="closed",p="",i.setQuery("",void 0),t.requestRender()},x=()=>{a==="closed"&&(u=n.topLine()??0),a="editing",p=i.query(),t.requestRender()},k=D=>{let R=i.step(f(),D);if(R===void 0){s.setNotice(`No matches for \u201C${i.query()}\u201D`);return}_(R)};return{component:{render(D){if(a==="closed")return[];let{index:R,total:F}=i.status(D),L=a==="editing"?`${e.accent("\u2315")} ${p}${e.accent("\u258C")}`:`${e.accent("\u2315")} ${p}`,U=F===0?i.query()===""?e.faint("type to search what is on screen"):e.error("no matches"):e.info(`${R}/${F}`),Y=a==="editing"?e.faint("enter browse \xB7 esc cancel"):e.faint([`${qS(s.bindings(),"crtr.attach.search.next")} next`,`${qS(s.bindings(),"crtr.attach.search.previous")} prev`,`${qS(s.bindings(),"crtr.attach.search.edit")} edit`,`${qS(s.bindings(),"crtr.attach.search.close")} close`].join(" \xB7 ")),V=`${U} ${Y}`,z=D-_I(L)-_I(V)-2;return[z<1?Ha(` ${L}`,D,"",!0):` ${L}${" ".repeat(z)}${V} `]},invalidate(){}},open:x,close:b,handleKey:D=>{if(a==="closed")return!1;let R=s.bindings();if(FX(R,"crtr.attach.search.close",D))return b(),!0;if(a==="editing"){if(D==="")return b(),!0;if(D==="\r"||D===`
2051
2051
  `)return i.status(f()).total===0?(s.setNotice(p===""?"Type something to search for":`No matches for \u201C${p}\u201D`),!0):(a="browsing",t.requestRender(),!0);if(D==="\x7F"||D==="\b")return p=[...p].slice(0,-1).join(""),m(),!0;let F=Mur(D);return F===void 0?!1:(p+=F,m(),!0)}return FX(R,"crtr.attach.search.next",D)||D==="\r"||D===`
2052
2052
  `?(k(1),!0):FX(R,"crtr.attach.search.previous",D)?(k(-1),!0):FX(R,"crtr.attach.search.edit",D)?(x(),!0):(Mur(D)!==void 0&&b(),!1)}}}import{performance as Fur}from"node:perf_hooks";var P8t=100,ybs=25,bbs=.5,Abs=.15;function vbs(t){return 1-(1-t)*(1-t)}function Lur(t,e){let n,i=0,s=0,a=0,u=()=>{n!==void 0&&clearTimeout(n),n=void 0,s=0,a=0},p=_=>{let m=Math.max(0,i+P8t-_);n=setTimeout(()=>{n=void 0,f(Fur.now(),!0)},Math.min(ybs,m))},f=(_,m)=>{let b=Math.min(1,(_-i)/P8t),x=Math.round(s*vbs(b)),k=x-a;if(k!==0){if(!t.scrollBy(k))return u();a=x,e()}if(b===1)return u();m&&p(_)};return{page(_){let m=Fur.now();n!==void 0&&(clearTimeout(n),n=void 0,f(m,!1));let b=s-a,x=Math.max(1,Math.round(t.pageRows()*bbs)),k=(_==="up"?-1:1)*x;if(s=b+k,a=0,s===0)return u();i=m-P8t*Abs,f(m,!0)},cancel:u}}import{spawnSync as Bur}from"node:child_process";var $ur=3e3;function xbs(){if(process.platform==="darwin")return[["pbcopy",[]]];let t=!!process.env.WAYLAND_DISPLAY||process.env.XDG_SESSION_TYPE==="wayland",e=["xclip",["-selection","clipboard"]],n=["wl-copy",[]];return t?[n,e]:[e,n]}function D8t(t){for(let[e,n]of xbs()){let i=Bur(e,n,{input:t,timeout:$ur,encoding:"utf-8"});if(i.error){if(i.error.code==="ENOENT")continue;continue}if(i.status===0)return!0}return!1}function jHe(t){let e=D8t(t),n=!1;if(process.env.TMUX!==void 0){let i=Bur("tmux",["load-buffer","-w","-"],{input:t,timeout:$ur,encoding:"utf-8"});n=!i.error&&i.status===0}return{system:e,tmux:n}}function ode(t){return t!==void 0&&t.trim()!==""}function wbs(t){return t.split(`
2053
2053
  `).length}function Sbs(t,e){if(t&&e)return"clipboard + tmux buffer";if(t)return"clipboard";if(e)return"tmux buffer"}function Ebs(t,e,n){let{first:i,last:s,lastFullyVisible:a}=e.visibleBlocks(),u=p=>{let f=n.blockAt(p);return f?t.blockText(f):void 0};for(let p=Math.min(s,a);p>=i;p--){let f=u(p);if(ode(f))return f}for(let p=s;p>=i;p--){let f=u(p);if(ode(f))return f}}function Uur(t,e,n){return{copy(i){let s,a;switch(i){case"message":{let _=Ebs(t,e,n);ode(_)&&(s={text:_,label:"message"}),a="Nothing to copy \u2014 no visible message";break}case"last-assistant":{let _=t.getLastAssistantText();ode(_)&&(s={text:_,label:"last assistant message"}),a="Nothing to copy \u2014 no assistant message yet";break}case"tool":{let _=t.getLastToolOutputText();ode(_)&&(s={text:_,label:"tool output"}),a="Nothing to copy \u2014 no tool output yet";break}case"transcript":{let _=t.getTranscriptPlainText();ode(_)&&(s={text:_,label:"transcript"}),a="Nothing to copy \u2014 transcript is empty";break}}if(!s)return a;let{system:u,tmux:p}=jHe(s.text),f=Sbs(u,p);return f?`Copied ${s.label} (${wbs(s.text)} lines) \u2014 ${f}`:"Copy failed \u2014 no clipboard tool found"}}}var WHe=class extends oc{render(e){let n=super.render(e);return n[0]===""?n.slice(1):n}};import{spawn as Yxs}from"node:child_process";import{readFileSync as Xxs,unlinkSync as Zxs,writeFileSync as ews}from"node:fs";import{tmpdir as tws}from"node:os";import{join as nws}from"node:path";import{StringDecoder as Cbs}from"node:string_decoder";function QHe(t){return JSON.stringify(t)+`
@@ -2072,13 +2072,13 @@ ${pys(e)}
2072
2072
  end try
2073
2073
  return "OK"
2074
2074
  end run`;function tAs(){let t=W8t(opr(),`crtr-clip-${process.pid}-${Date.now()}.png`);try{let e=spr("osascript",["-e",eAs,t],{timeout:cpr,maxBuffer:apr,encoding:"utf-8"});if(e.error||e.status!==0)return{note:"Could not read the clipboard (osascript failed)"};let n=(e.stdout??"").trim();if(n==="NO_IMAGE")return{};if(n!=="OK")return{note:"Could not read the clipboard image"};let i;try{i=Hbs(t)}catch{return{note:"Could not read the clipboard image"}}return i.length>0?{image:{bytes:i,mimeType:"image/png"}}:{}}finally{try{Jbs(t)}catch{}}}function nAs(){return!!process.env.WAYLAND_DISPLAY||process.env.XDG_SESSION_TYPE==="wayland"}function ipr(t,e){let n=spr(t,e,{timeout:cpr,maxBuffer:apr});if(n.error)return{missing:n.error.code==="ENOENT"};if(n.status!==0)return{};let i=n.stdout;return!i||i.length===0?{}:{bytes:Buffer.isBuffer(i)?i:Buffer.from(i)}}function q8t(t){return t.method==="select"||t.method==="confirm"||t.method==="input"||t.method==="editor"}var ppr={dismiss:()=>{}},rAs={anchor:"center",width:"70%",maxHeight:"80%"};function dpr(t,e,n,i){if(!q8t(e))return ppr;let s=!1,a,u,p=()=>{a?.hide();let m=u;try{m?.dispose?.()}catch{}},f=m=>{s||(s=!0,p(),n(m))},_=()=>f({type:"extension_ui_response",id:e.id,cancelled:!0});switch(e.method){case"select":u=new P8(e.title,e.options,m=>f({type:"extension_ui_response",id:e.id,value:m}),_,{tui:t,timeout:e.timeout});break;case"confirm":u=new P8(`${e.title}
2075
- ${e.message}`,["Yes","No"],m=>f({type:"extension_ui_response",id:e.id,confirmed:m==="Yes"}),_,{tui:t,timeout:e.timeout});break;case"input":u=new QQ(e.title,e.placeholder,m=>f({type:"extension_ui_response",id:e.id,value:m}),_,{tui:t,timeout:e.timeout});break;case"editor":u=new XY(t,i??new BB(TR),e.title,e.prefill,m=>f({type:"extension_ui_response",id:e.id,value:m}),_);break;default:return ppr}return a=t.showOverlay(u,rAs),{dismiss:()=>{s||(s=!0,p())}}}function iAs(t,e){return{getAvailableSnapshot(){return e},getModel(i,s){return t.find(a=>a.provider===i&&a.id===s)},getError(){},async refresh(){return{aborted:!1,errors:new Map}}}}function fpr(t,e,n,i){let s=e.models,a=new Set(e.availableIds),u=s.filter(_=>a.has(`${_.provider}/${_.id}`)),p=e.current?s.find(_=>_.provider===e.current.provider&&_.id===e.current.id):void 0,f=new eX(t,p,iAs(s,u),e.scopedModels,_=>{n({type:"set_model",model:`${_.provider}/${_.id}`}),i()},()=>i());return{component:f,focus:f}}function mpr(t,e,n,i,s,a){let u=_=>_.sessions.map(m=>({...m,created:new Date(m.created),modified:new Date(m.modified)})),p=_=>async()=>u(await n({type:"list_sessions",scope:_})),f=new qQ(p("cwd"),p("all"),_=>{s({type:"switch_session",path:_}),a()},()=>a(),()=>a(),()=>t.requestRender(),{showRenameHint:!1,keybindings:i},e);return{component:f,focus:f}}function hpr(t,e,n,i){let s=process.stdout.rows??24,a=new rX(e.tree,e.currentLeafId,s,u=>{n({type:"navigate_tree",targetId:u}),i()},()=>i());return{component:a,focus:a}}function gpr(t,e,n){let i=new iX(t.forkPoints,s=>{e({type:"fork",entryId:s}),n()},()=>n());return{component:i,focus:i.getMessageList()}}function _pr(t,e,n){let i=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:t.settings.autoCompact?"true":"false",values:["true","false"]},{id:"thinking",label:"Thinking level",description:"Reasoning depth for thinking-capable models",currentValue:t.settings.thinkingLevel,values:t.settings.availableThinkingLevels}],s=new Die(i,i.length,kUe(),(u,p)=>{u==="autocompact"&&e({type:"set_auto_compaction",enabled:p==="true"}),u==="thinking"&&e({type:"set_thinking_level",level:p})},n,{enableSearch:!1}),a=new oc;return a.addChild(new gp),a.addChild(s),a.addChild(new gp),{component:a,focus:s}}function ypr(t,e,n){let i=t.enabledModelIds,s=f=>{if(i===null)return!0;let _=`${f.provider}/${f.id}`;return i.includes(_)||i.includes(f.id)||i.includes("*")},a=t.allModels.map(f=>({value:`${f.provider}/${f.id}`,label:`${s(f)?"\u2713":" "} ${f.provider}/${f.id}`,description:f.name})),u=nE(),p=new WS(a,12,u);return p.onSelect=()=>n("Enabling/disabling scoped models isn't supported over view.sock yet"),p.onCancel=()=>e(),{component:p,focus:p}}import{createHash as aAs}from"node:crypto";import{existsSync as cAs}from"node:fs";import{homedir as G8t}from"node:os";import{join as DF,resolve as V8t}from"node:path";import{homedir as sAs}from"node:os";import{join as oAs,resolve as lSc}from"node:path";function bpr(t=sAs()){let e=process.env.PI_CODING_AGENT_DIR;return e!==void 0&&e!==""?Agt(e,t):oAs(t,".pi","agent")}var lAs=10080*60*1e3;function uAs(t,e){switch(t){case"cursor":return[DF(e,".cursor","mcp.json")];case"claude-code":return[DF(e,".claude","mcp.json"),DF(e,".claude.json"),DF(e,".claude","claude_desktop_config.json")];case"claude-desktop":return[DF(e,"Library","Application Support","Claude","claude_desktop_config.json")];case"codex":return[DF(e,".codex","config.json")];case"windsurf":return[DF(e,".windsurf","mcp.json")];case"vscode":return[".vscode/mcp.json"];default:return[]}}function pAs(t){let e=t.mcpServers??t["mcp-servers"]??{};return typeof e!="object"||e===null||Array.isArray(e)?{servers:{},imports:[]}:{servers:e,imports:Array.isArray(t.imports)?t.imports:[]}}function dAs(t,e){if(!t||typeof t!="object")return{};let n=t,i;switch(e){case"claude-desktop":case"claude-code":case"codex":i=n.mcpServers;break;case"cursor":case"windsurf":case"vscode":i=n.mcpServers??n["mcp-servers"];break;default:return{}}return!i||typeof i!="object"||Array.isArray(i)?{}:i}function vpr(t,e){let n={...t};for(let[i,s]of Object.entries(e))n[i]={...n[i]??{},...s};return n}function fAs(t,e,n){let i=RR(t);if(i===null)return{};let{servers:s,imports:a}=pAs(i),u={};for(let p of a){let f=uAs(p,n).map(m=>m.startsWith(".")?V8t(e,m):m).find(m=>cAs(m));if(f===void 0)continue;let _=RR(f);if(_!==null)for(let[m,b]of Object.entries(dAs(_,p)))m in u||(u[m]=b)}return vpr(u,s)}function H8t(t){return t.replace(/\$\{(\w+)\}/g,(e,n)=>process.env[n]??"").replace(/\$env:(\w+)/g,(e,n)=>process.env[n]??"")}function Apr(t){if(!t)return;let e={};for(let[n,i]of Object.entries(t))e[n]=H8t(i);return e}function mAs(t){if(t===void 0)return;let e=H8t(t);return e==="~"?G8t():e.startsWith("~/")||e.startsWith("~\\")?DF(G8t(),e.slice(2)):e}function hAs(t){return t.bearerToken!==void 0?H8t(t.bearerToken):t.bearerTokenEnv?process.env[t.bearerTokenEnv]:void 0}function z8t(t){if(t==null||typeof t!="object"){let i=JSON.stringify(t);return i===void 0?"undefined":i}if(Array.isArray(t))return`[${t.map(i=>z8t(i)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(i=>`${JSON.stringify(i)}:${z8t(e[i])}`).join(",")}}`}function gAs(t){let e={command:t.command,args:t.args,env:Apr(t.env),cwd:mAs(t.cwd),url:t.url,headers:Apr(t.headers),auth:t.auth,bearerToken:hAs(t),bearerTokenEnv:t.bearerTokenEnv,exposeResources:t.exposeResources,excludeTools:t.excludeTools};return aAs("sha256").update(z8t(e)).digest("hex")}function xpr(t=G8t(),e=process.cwd()){let n=bpr(t),i=[...new Set([DF(t,".config","mcp","mcp.json"),DF(n,"mcp.json"),V8t(e,".mcp.json"),V8t(e,".pi","mcp.json")])],s={};for(let u of i)s=vpr(s,fAs(u,e,t));let a=RR(DF(n,"mcp-cache.json"));return Object.entries(s).map(([u,p])=>{let f=p.type??(p.url!==void 0?"http":"stdio"),_=p.url??[p.command,...p.args??[]].filter(Boolean).join(" "),m=a?.servers?.[u],b=m?.tools,x=Array.isArray(b)?b.length:null,k=x!==null&&m!==void 0&&!_As(m,p);return{name:u,transport:f,target:_,toolCount:x,stale:k}})}function _As(t,e){return!(t.configHash!==gAs(e)||!t.cachedAt||typeof t.cachedAt!="number"||Date.now()-t.cachedAt>lAs)}var wpr="No MCP servers configured \u2014 add one to ~/.config/mcp/mcp.json, ~/.pi/agent/mcp.json, <cwd>/.mcp.json, or <cwd>/.pi/mcp.json";function J8t(t,e,n){let i=JSON.stringify(t.name);t.toolCount===null?(e({type:"prompt",text:`Run mcp({ action: "auth-start", server: ${i} }) and show me the returned OAuth URL verbatim (with any instructions). If the server does not need OAuth, run mcp({ connect: ${i} }) instead and report the result.`}),n(`Asking the engine to start OAuth for ${t.name}\u2026`)):(e({type:"prompt",text:`Run mcp({ connect: ${i} }) to reconnect that MCP server and report the result. If it fails with an authentication or authorization error, run mcp({ action: "auth-start", server: ${i} }) and show me the returned OAuth URL verbatim (with any instructions).`}),n(`Asking the engine to reconnect ${t.name}\u2026`))}function Spr(t,e,n,i){let s=t.map(p=>({value:p.name,label:p.toolCount===null?`\u25CB ${p.name} \u2014 ${p.transport} \xB7 never connected (Enter to connect/OAuth)`:p.stale?`\u25B3 ${p.name} \u2014 ${p.transport} \xB7 config changed \u2014 ${p.toolCount} tool${p.toolCount===1?"":"s"} cached, stale (Enter to reconnect)`:`\u2713 ${p.name} \u2014 ${p.transport} \xB7 ${p.toolCount} tool${p.toolCount===1?"":"s"} cached (Enter to reconnect)`,description:p.target})),a=Math.max(0,...s.map(p=>Vs(p.label)))+2,u=new WS(s,12,nE(),{minPrimaryColumnWidth:a,maxPrimaryColumnWidth:a});return u.onSelect=p=>{let f=t.find(_=>_.name===p.value);f!==void 0&&(n(),J8t(f,e,i))},u.onCancel=()=>n(),{component:u,focus:u}}import{homedir as kUt}from"node:os";import{isAbsolute as Vxs,join as zxs,relative as Hxs,resolve as Jxs}from"node:path";import{basename as Qxs}from"node:path";import{relative as yxs,resolve as Ydr}from"node:path";import{extname as Epr}from"node:path";var yAs={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".hpp":"cpp",".cs":"csharp",".swift":"swift",".kt":"kotlin",".php":"php",".lua":"lua",".pl":"perl",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"fish",".sql":"sql",".json":"json",".jsonc":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".less":"less",".vim":"vim",".el":"lisp",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".scala":"scala",".dart":"dart",".r":"r",".jl":"julia",".zig":"zig",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".csv":"text",".txt":"text",".log":"text",".env":"bash",".mk":"makefile"},bAs=new Set([".md",".markdown",".mdown",".mkd"]);function Cpr(t){return bAs.has(Epr(t).toLowerCase())}function Tpr(t){let e=Epr(t).toLowerCase();if(e===""){let n=t.slice(t.lastIndexOf("/")+1).toLowerCase();return n==="dockerfile"?"dockerfile":n==="makefile"?"makefile":"text"}return yAs[e]??"text"}function AAs(t,e){let n=0;for(let a of t.matchAll(/`+/g))n=Math.max(n,a[0].length);let i="`".repeat(Math.max(3,n+1)),s=t.endsWith(`
2075
+ ${e.message}`,["Yes","No"],m=>f({type:"extension_ui_response",id:e.id,confirmed:m==="Yes"}),_,{tui:t,timeout:e.timeout});break;case"input":u=new QQ(e.title,e.placeholder,m=>f({type:"extension_ui_response",id:e.id,value:m}),_,{tui:t,timeout:e.timeout});break;case"editor":u=new XY(t,i??new BB(TR),e.title,e.prefill,m=>f({type:"extension_ui_response",id:e.id,value:m}),_);break;default:return ppr}return a=t.showOverlay(u,rAs),{dismiss:()=>{s||(s=!0,p())}}}function iAs(t,e){return{getAvailableSnapshot(){return e},getModel(i,s){return t.find(a=>a.provider===i&&a.id===s)},getError(){},async refresh(){return{aborted:!1,errors:new Map}}}}function fpr(t,e,n,i){let s=e.models,a=new Set(e.availableIds),u=s.filter(_=>a.has(`${_.provider}/${_.id}`)),p=e.current?s.find(_=>_.provider===e.current.provider&&_.id===e.current.id):void 0,f=new eX(t,p,iAs(s,u),e.scopedModels,_=>{n({type:"set_model",model:`${_.provider}/${_.id}`}),i()},()=>i());return{component:f,focus:f}}function mpr(t,e,n,i,s,a){let u=_=>_.sessions.map(m=>({...m,created:new Date(m.created),modified:new Date(m.modified)})),p=_=>async()=>u(await n({type:"list_sessions",scope:_})),f=new qQ(p("cwd"),p("all"),_=>{s({type:"switch_session",path:_}),a()},()=>a(),()=>a(),()=>t.requestRender(),{showRenameHint:!1,keybindings:i},e);return{component:f,focus:f}}function hpr(t,e,n,i){let s=process.stdout.rows??24,a=new rX(e.tree,e.currentLeafId,s,u=>{n({type:"navigate_tree",targetId:u}),i()},()=>i());return{component:a,focus:a}}function gpr(t,e,n){let i=new iX(t.forkPoints,s=>{e({type:"fork",entryId:s}),n()},()=>n());return{component:i,focus:i.getMessageList()}}function _pr(t,e,n){let i=[{id:"autocompact",label:"Auto-compact",description:"Automatically compact context when it gets too large",currentValue:t.settings.autoCompact?"true":"false",values:["true","false"]},{id:"thinking",label:"Thinking level",description:"Reasoning depth for thinking-capable models",currentValue:t.settings.thinkingLevel,values:t.settings.availableThinkingLevels}],s=new Die(i,i.length,kUe(),(u,p)=>{u==="autocompact"&&e({type:"set_auto_compaction",enabled:p==="true"}),u==="thinking"&&e({type:"set_thinking_level",level:p})},n,{enableSearch:!1}),a=new oc;return a.addChild(new gp),a.addChild(s),a.addChild(new gp),{component:a,focus:s}}function ypr(t,e,n){let i=t.enabledModelIds,s=f=>{if(i===null)return!0;let _=`${f.provider}/${f.id}`;return i.includes(_)||i.includes(f.id)||i.includes("*")},a=t.allModels.map(f=>({value:`${f.provider}/${f.id}`,label:`${s(f)?"\u2713":" "} ${f.provider}/${f.id}`,description:f.name})),u=nE(),p=new WS(a,12,u);return p.onSelect=()=>n("Enabling/disabling scoped models isn't supported over view.sock yet"),p.onCancel=()=>e(),{component:p,focus:p}}import{createHash as aAs}from"node:crypto";import{existsSync as cAs}from"node:fs";import{homedir as G8t}from"node:os";import{join as DF,resolve as V8t}from"node:path";import{homedir as sAs}from"node:os";import{join as oAs,resolve as dSc}from"node:path";function bpr(t=sAs()){let e=process.env.PI_CODING_AGENT_DIR;return e!==void 0&&e!==""?Agt(e,t):oAs(t,".pi","agent")}var lAs=10080*60*1e3;function uAs(t,e){switch(t){case"cursor":return[DF(e,".cursor","mcp.json")];case"claude-code":return[DF(e,".claude","mcp.json"),DF(e,".claude.json"),DF(e,".claude","claude_desktop_config.json")];case"claude-desktop":return[DF(e,"Library","Application Support","Claude","claude_desktop_config.json")];case"codex":return[DF(e,".codex","config.json")];case"windsurf":return[DF(e,".windsurf","mcp.json")];case"vscode":return[".vscode/mcp.json"];default:return[]}}function pAs(t){let e=t.mcpServers??t["mcp-servers"]??{};return typeof e!="object"||e===null||Array.isArray(e)?{servers:{},imports:[]}:{servers:e,imports:Array.isArray(t.imports)?t.imports:[]}}function dAs(t,e){if(!t||typeof t!="object")return{};let n=t,i;switch(e){case"claude-desktop":case"claude-code":case"codex":i=n.mcpServers;break;case"cursor":case"windsurf":case"vscode":i=n.mcpServers??n["mcp-servers"];break;default:return{}}return!i||typeof i!="object"||Array.isArray(i)?{}:i}function vpr(t,e){let n={...t};for(let[i,s]of Object.entries(e))n[i]={...n[i]??{},...s};return n}function fAs(t,e,n){let i=RR(t);if(i===null)return{};let{servers:s,imports:a}=pAs(i),u={};for(let p of a){let f=uAs(p,n).map(m=>m.startsWith(".")?V8t(e,m):m).find(m=>cAs(m));if(f===void 0)continue;let _=RR(f);if(_!==null)for(let[m,b]of Object.entries(dAs(_,p)))m in u||(u[m]=b)}return vpr(u,s)}function H8t(t){return t.replace(/\$\{(\w+)\}/g,(e,n)=>process.env[n]??"").replace(/\$env:(\w+)/g,(e,n)=>process.env[n]??"")}function Apr(t){if(!t)return;let e={};for(let[n,i]of Object.entries(t))e[n]=H8t(i);return e}function mAs(t){if(t===void 0)return;let e=H8t(t);return e==="~"?G8t():e.startsWith("~/")||e.startsWith("~\\")?DF(G8t(),e.slice(2)):e}function hAs(t){return t.bearerToken!==void 0?H8t(t.bearerToken):t.bearerTokenEnv?process.env[t.bearerTokenEnv]:void 0}function z8t(t){if(t==null||typeof t!="object"){let i=JSON.stringify(t);return i===void 0?"undefined":i}if(Array.isArray(t))return`[${t.map(i=>z8t(i)).join(",")}]`;let e=t;return`{${Object.keys(e).sort().map(i=>`${JSON.stringify(i)}:${z8t(e[i])}`).join(",")}}`}function gAs(t){let e={command:t.command,args:t.args,env:Apr(t.env),cwd:mAs(t.cwd),url:t.url,headers:Apr(t.headers),auth:t.auth,bearerToken:hAs(t),bearerTokenEnv:t.bearerTokenEnv,exposeResources:t.exposeResources,excludeTools:t.excludeTools};return aAs("sha256").update(z8t(e)).digest("hex")}function xpr(t=G8t(),e=process.cwd()){let n=bpr(t),i=[...new Set([DF(t,".config","mcp","mcp.json"),DF(n,"mcp.json"),V8t(e,".mcp.json"),V8t(e,".pi","mcp.json")])],s={};for(let u of i)s=vpr(s,fAs(u,e,t));let a=RR(DF(n,"mcp-cache.json"));return Object.entries(s).map(([u,p])=>{let f=p.type??(p.url!==void 0?"http":"stdio"),_=p.url??[p.command,...p.args??[]].filter(Boolean).join(" "),m=a?.servers?.[u],b=m?.tools,x=Array.isArray(b)?b.length:null,k=x!==null&&m!==void 0&&!_As(m,p);return{name:u,transport:f,target:_,toolCount:x,stale:k}})}function _As(t,e){return!(t.configHash!==gAs(e)||!t.cachedAt||typeof t.cachedAt!="number"||Date.now()-t.cachedAt>lAs)}var wpr="No MCP servers configured \u2014 add one to ~/.config/mcp/mcp.json, ~/.pi/agent/mcp.json, <cwd>/.mcp.json, or <cwd>/.pi/mcp.json";function J8t(t,e,n){let i=JSON.stringify(t.name);t.toolCount===null?(e({type:"prompt",text:`Run mcp({ action: "auth-start", server: ${i} }) and show me the returned OAuth URL verbatim (with any instructions). If the server does not need OAuth, run mcp({ connect: ${i} }) instead and report the result.`}),n(`Asking the engine to start OAuth for ${t.name}\u2026`)):(e({type:"prompt",text:`Run mcp({ connect: ${i} }) to reconnect that MCP server and report the result. If it fails with an authentication or authorization error, run mcp({ action: "auth-start", server: ${i} }) and show me the returned OAuth URL verbatim (with any instructions).`}),n(`Asking the engine to reconnect ${t.name}\u2026`))}function Spr(t,e,n,i){let s=t.map(p=>({value:p.name,label:p.toolCount===null?`\u25CB ${p.name} \u2014 ${p.transport} \xB7 never connected (Enter to connect/OAuth)`:p.stale?`\u25B3 ${p.name} \u2014 ${p.transport} \xB7 config changed \u2014 ${p.toolCount} tool${p.toolCount===1?"":"s"} cached, stale (Enter to reconnect)`:`\u2713 ${p.name} \u2014 ${p.transport} \xB7 ${p.toolCount} tool${p.toolCount===1?"":"s"} cached (Enter to reconnect)`,description:p.target})),a=Math.max(0,...s.map(p=>Vs(p.label)))+2,u=new WS(s,12,nE(),{minPrimaryColumnWidth:a,maxPrimaryColumnWidth:a});return u.onSelect=p=>{let f=t.find(_=>_.name===p.value);f!==void 0&&(n(),J8t(f,e,i))},u.onCancel=()=>n(),{component:u,focus:u}}import{homedir as kUt}from"node:os";import{isAbsolute as Vxs,join as zxs,relative as Hxs,resolve as Jxs}from"node:path";import{basename as Qxs}from"node:path";import{relative as yxs,resolve as Ydr}from"node:path";import{extname as Epr}from"node:path";var yAs={".ts":"typescript",".mts":"typescript",".cts":"typescript",".tsx":"tsx",".js":"javascript",".mjs":"javascript",".cjs":"javascript",".jsx":"jsx",".py":"python",".rb":"ruby",".go":"go",".rs":"rust",".java":"java",".c":"c",".h":"c",".cc":"cpp",".cpp":"cpp",".hpp":"cpp",".cs":"csharp",".swift":"swift",".kt":"kotlin",".php":"php",".lua":"lua",".pl":"perl",".sh":"bash",".bash":"bash",".zsh":"bash",".fish":"fish",".sql":"sql",".json":"json",".jsonc":"json",".yaml":"yaml",".yml":"yaml",".toml":"toml",".ini":"ini",".xml":"xml",".html":"html",".htm":"html",".css":"css",".scss":"scss",".less":"less",".vim":"vim",".el":"lisp",".ex":"elixir",".exs":"elixir",".erl":"erlang",".hs":"haskell",".scala":"scala",".dart":"dart",".r":"r",".jl":"julia",".zig":"zig",".tf":"terraform",".proto":"protobuf",".graphql":"graphql",".gql":"graphql",".dockerfile":"dockerfile",".diff":"diff",".patch":"diff",".csv":"text",".txt":"text",".log":"text",".env":"bash",".mk":"makefile"},bAs=new Set([".md",".markdown",".mdown",".mkd"]);function Cpr(t){return bAs.has(Epr(t).toLowerCase())}function Tpr(t){let e=Epr(t).toLowerCase();if(e===""){let n=t.slice(t.lastIndexOf("/")+1).toLowerCase();return n==="dockerfile"?"dockerfile":n==="makefile"?"makefile":"text"}return yAs[e]??"text"}function AAs(t,e){let n=0;for(let a of t.matchAll(/`+/g))n=Math.max(n,a[0].length);let i="`".repeat(Math.max(3,n+1)),s=t.endsWith(`
2076
2076
  `)?t.slice(0,-1):t;return`${i}${e}
2077
2077
  ${s}
2078
2078
  ${i}
2079
- `}function vAs(t,e){let n=e+2,i=a=>Math.max(1,Math.min(a-1,e)),s=t.spans.map(a=>a!==null&&(a[0]<=1||a[1]>=n));return{lines:t.lines,rows:t.rows.map((a,u)=>s[u]===!0?null:a),spans:t.spans.map((a,u)=>a===null||s[u]===!0?null:[i(a[0]),i(a[1])]),blocks:t.blocks.map(a=>({type:a.type,start:i(a.start),end:i(a.end)}))}}function kpr(t,e,n){let i=L8(t).length;return vAs(ZVe(AAs(t,e),n),i)}function zHe(t){let e=[],n=new Array(t.lines.length).fill(null);for(let i=0;i<t.lines.length;i++){let s=t.spans[i]??null;if(s===null){let u=t.rows[i]??null,p=u!==null?t.blocks[u]:void 0;if(p===void 0)continue;s=[p.start,p.end]}let a=e[e.length-1];a!==void 0&&a.lastRow===i-1&&a.start===s[0]&&a.end===s[1]?a.lastRow=i:e.push({start:s[0],end:s[1],firstRow:i,lastRow:i}),n[i]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let i=0;i<n.length;i++)n[i]=0}return{units:e,rowUnits:n}}function LX(t,e){let n=-1;for(let i=0;i<t.length;i++){let s=t[i];s.start<=e&&s.end>=e&&(n===-1||s.end-s.start<t[n].end-t[n].start)&&(n=i)}if(n!==-1)return n;for(let i=0;i<t.length;i++)if(t[i].start>e)return i;return Math.max(0,t.length-1)}function K8t(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return LX(t,e.start)}function LCe(t,e,n){let i=-1,s=-1;if(t.forEach((a,u)=>{a.start<=n&&a.end>=e&&(i===-1&&(i=u),s=u)}),i===-1){let a=LX(t,e);return{lo:a,hi:a}}return{lo:i,hi:s}}import{closeSync as qvs,fstatSync as Gvs,openSync as Vvs,readSync as zvs}from"node:fs";import{join as Hvs}from"node:path";import{spawn as gvs,execFileSync as gTc}from"node:child_process";import{createRequire as _vs}from"node:module";import{dirname as iUt,join as cde}from"node:path";import{fileURLToPath as yvs,pathToFileURL as sUt}from"node:url";import{existsSync as bvs,lstatSync as Avs,mkdirSync as vvs,openSync as xvs,closeSync as wvs}from"node:fs";import{copyFileSync as xAs,mkdirSync as JHe,existsSync as HHe,readFileSync as wAs,writeFileSync as Npr,chmodSync as SAs,readdirSync as EAs,renameSync as BX,realpathSync as Ipr,unlinkSync as CAs,rmSync as TAs,linkSync as Ppr}from"node:fs";import{homedir as Mpr}from"node:os";import{dirname as kAs,join as bA}from"node:path";import{spawnSync as Y8t}from"node:child_process";var KHe="crouter";function $Ce(){return bA(Mpr(),IR,"host")}function IAs(){return bA($Ce(),KHe)}function X8t(){return bA($Ce(),".source.json")}function PAs(t){let e=kAs(t);for(let n of[e,bA(e,"..","lib")]){if(!HHe(n))continue;let i=EAs(n).find(s=>s.startsWith("libnode.")&&s.endsWith(".dylib"));if(i!==void 0)return bA(n,i)}return null}function Dpr(t,e,n){let i=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;xAs(t,i),n!==void 0&&SAs(i,n),BX(i,e)}function Rpr(t=X8t()){try{return JSON.parse(wAs(t,"utf8"))}catch{return null}}var DAs=3e4;function RAs(t){let e=bA(Mpr(),IR),n=bA(e,"host.lock");return JHe(e,{recursive:!0}),kk(n,t,{timeoutMs:DAs,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function NAs(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function MAs(){if(process.platform!=="darwin")return null;let t=Y8t("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
2080
- `).map(i=>i.match(/\)\s+[A-Fa-f0-9]{40}\s+"([^"]+)"/)?.[1]??null).filter(i=>i!==null);return n.find(i=>i.startsWith("Apple Development:"))??n.find(i=>i.startsWith("Developer ID Application:"))??n[0]??null}function OAs(t,e){let n=Y8t("codesign",["-s",e,"--deep","--force",t],{stdio:["pipe","pipe","pipe"]});return{ok:n.status===0,stderr:(n.stderr??"").toString().trim()}}function FAs(t){if(process.platform!=="darwin")return;let e=NAs({configured:process.env.CRTR_CODESIGN_IDENTITY,discovered:MAs()}),n="";for(let i of e){let s=OAs(t,i);if(s.ok)return;n=s.stderr}throw n&&!n.includes("valid on disk")&&DR({event:"host.codesign.failed",level:"debug",error:n}),new Error(`codesign failed for ${t}: ${n||"codesign did not exit successfully"}`)}function LAs(t,e,n=FAs){e!==null&&n(e),n(t)}function BCe(t,e=5e3){try{return Y8t(t,["-e",""],{stdio:"ignore",timeout:e}).status===0}catch{return!1}}function BAs(){return RAs(()=>{let t=$Ce(),e=IAs(),n=Ipr(process.execPath);if(HHe(e)&&Ipr(e)===n)return e;let i=Rpr(),s=PAs(n),a=s!==null?s.split("/").pop():null,u=x=>HHe(e)&&x!==null&&x.version===2&&(x.libnode===null||HHe(bA(t,x.libnode))),p=x=>u(x)&&x.source===n&&x.libnode===a;if(p(i)&&BCe(e))return e;JHe(t,{recursive:!0});let f=bA(t,`.reconcile.${process.pid}.${Math.random().toString(36).slice(2)}`),_=bA(f,"previous");JHe(f);let m=!1,b=u(i)&&BCe(e);try{let x=bA(f,KHe),k=a!==null?bA(f,a):null;if(s!==null&&k!==null&&Dpr(s,k),Dpr(n,x,493),LAs(x,k),!BCe(x))throw new Error(`rebuilt branded host failed its startup check: ${x}`);if(b&&UAs(_,e,i),m=!0,k!==null&&BX(k,bA(t,a)),BX(x,e),$As({version:2,source:n,libnode:a}),!p(Rpr())||!BCe(e))throw new Error(`published branded host tuple failed validation: ${e}`);if(i?.libnode!=null&&i.libnode!==a)try{CAs(bA(t,i.libnode))}catch{}return e}catch(x){throw m&&b&&jAs(_,e,i),x}finally{TAs(f,{recursive:!0,force:!0})}})}function $As(t){let e=X8t(),n=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;Npr(n,JSON.stringify(t)),BX(n,e)}function UAs(t,e,n){JHe(t),Ppr(e,bA(t,KHe)),n.libnode!==null&&Ppr(bA($Ce(),n.libnode),bA(t,n.libnode)),Npr(bA(t,".source.json"),JSON.stringify(n))}function jAs(t,e,n){if(n.libnode!==null&&BX(bA(t,n.libnode),bA($Ce(),n.libnode)),BX(bA(t,KHe),e),BX(bA(t,".source.json"),X8t()),!BCe(e))throw new Error(`failed to restore previous branded host tuple: ${e}`)}function Opr(){return process.env.CRTR_BRANDED_HOST==="0"||process.platform!=="darwin"||import.meta.url.endsWith(".ts")?process.execPath:BAs()}import{existsSync as WAs,readFileSync as QAs}from"node:fs";import{join as qAs}from"node:path";function GAs(){return Aun()??qAs(Hw(),"crtrd.pid")}function UCe(){let t=GAs();if(!WAs(t))return null;let e=QAs(t,"utf8").trim(),n=Number(e);return Number.isFinite(n)&&n>0?n:null}function Fpr(){let t=UCe();return t!==null&&EF(t)}import{rmSync as uvs}from"node:fs";import{statSync as pvs}from"node:fs";import{join as dvs}from"node:path";var KAs=Cu(DX(),1);var jCe=Cu(DX(),1);var jpr=Cu(DX(),1);var nUt="__CROUTER_SYNTHETIC_NAMESPACE__",avs="__CROUTER_SYNTHETIC_NAMESPACE_SCALAR__",b1c=["---","kind: knowledge",`namespace: ${avs}`,`when-and-why-to-read: When working in \`${nUt}\`, this knowledge should be read because it names the namespace every document in this project answers under.`,"surfaces:"," - on: workspace-open"," at: content"," - on: read",' match: "./**"'," at: content","---",`# ${nUt}`,"",`This project's memory store. Every document here answers at \`${nUt}/<local name>\`.`,""].join(`
2081
- `);var rUt=Cu(DX(),1);function Qpr(){return dvs(Hw(),"daemon-startup-blocked.json")}function fvs(t){try{let e=pvs(t);return{path:t,sizeBytes:e.size,mtimeMs:e.mtimeMs}}catch{return{path:t,sizeBytes:null,mtimeMs:null}}}function mvs(t,e){return t.sizeBytes===e.sizeBytes&&t.mtimeMs===e.mtimeMs}function XHe(){try{uvs(Qpr(),{force:!0})}catch{}}function ZHe(){let t=RR(Qpr());return t===null||typeof t.message!="string"||!Array.isArray(t.blockers)?null:t.blockers.length===0||t.blockers.some(n=>!mvs(n,fvs(n.path)))?(XHe(),null):t.message}var Svs=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function Evs(){let t={...process.env};for(let e of Svs)delete t[e];return t}function Cvs(){for(let t=iUt(yvs(import.meta.url));;t=iUt(t)){if(bvs(cde(t,"bin","runtime-generation-manifest.mjs")))return t;if(iUt(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}async function Tvs(){let t=Cvs(),e=sUt(cde(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:n}=await import(e);try{Avs(cde(n(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",sUt(_vs(import.meta.url).resolve("tsx/esm")).href,cde(t,"src","daemon","crtrd-cli.ts")]}let i=sUt(cde(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:s}=await import(i),a=s("daemon");if(!a.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${a.error}`);return[a.runtime.entryPath]}var Gpr=2e4,aUt=10,qpr=1e3;async function Vpr(t=qpr){let e=Math.min(t,qpr);if(!(await Xj.forLocalSocket({autostart:!1,timeoutMs:e}).probeHealthz(e)).ok)throw new Error("crtrd health check reported not ready")}function cUt(t){return new Promise(e=>{setTimeout(e,t)})}var rJe=class extends Error{constructor(e){super(`daemon ${e} exited: startup is blocked by a standing condition that retrying cannot clear. See crtrd.err, then run \`crtr sys migrate\`.`),this.name="DaemonStartupBlockedError"}};async function kvs(t,e=3e5,n={}){let i=n.readPidfile??UCe,s=n.isPidAlive??EF,a=n.childExited,u=n.isDaemonServing,p=n.probeDaemonServing??(async x=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await Vpr(x)}),f=n.sleepMs??cUt,_=n.now??Date.now,m=null,b=null;return await i4e({windowMs:e,pollIntervalMs:aUt,now:_,sleep:f,retry:x=>x!==b,probe:async x=>{let k=i();if(k===null||!s(k)){let I=a?.();throw I!=null&&(I.signal!==null?b=new Error(`daemon ${t} exited before becoming ready (by ${I.signal})`):I.code===78?b=new rJe(t):I.code!==0&&(b=new Error(`daemon ${t} exited before becoming ready (with exit code ${I.code??"?"})`)),b!==null)?b:new Error(`daemon ${t} has no live pidfile owner`)}await p(x),m=k}}),m===t?null:m}async function Ivs(t,e=Gpr,n={}){let i=n.readPidfile??UCe,s=n.isPidAlive??EF,a=n.sleepMs??cUt,u=n.now??Date.now,p=u()+e;for(;u()<=p;){if(!s(t)&&i()!==t)return;await a(aUt)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var Pvs=2e3,Dvs=5e3;async function Rvs(t,e=Gpr,n={}){let i=n.isPidAlive??EF,s=n.sleepMs??cUt,a=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ivs(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let u=a()+Pvs;for(;a()<=u;){if(!i(t))return"killed";await s(aUt)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}async function Nvs(){let t=UCe();if(t!==null&&EF(t))try{return await Vpr(),{started:!1,existing_pid:t}}catch(f){return{started:!1,existing_pid:t,running:!0,serving:!1,probe_error:f.message}}vvs(Hw(),{recursive:!0});let e=await Tvs(),n=cde(Hw(),"crtrd.err"),i=xvs(n,"a");KBe()===void 0&&qfn();let s=gvs(Opr(),[...e,"--canvas-home",Hw()],{detached:!0,stdio:["ignore",i,i],env:Evs()});wvs(i);let a=s.pid;if(a===void 0)throw new Error("daemon spawn did not return a pid");let u=null;s.once("exit",(f,_)=>{u={code:f,signal:_}}),s.unref();let p;try{p=await kvs(a,3e5,{childExited:()=>u})}catch(f){let _=XBe(ygt())===a;if(u===null&&!_)try{await Rvs(a,Dvs)}catch{}throw f}return p!==null?{started:!1,existing_pid:p}:{started:!0,pid:a}}function lUt(){return vun()||process.argv.includes("--no-autostart")}var Mvs=5e3,Ovs=6e4,oUt=!1,eJe=0,tJe=0,nJe=null;function Fvs(t){return Math.min(Mvs*2**(t-1),Ovs)}function Lvs(){eJe=0,tJe=0,nJe=null,XHe()}function zpr(t={}){let e=t.isDaemonRunning??Fpr,n=t.spawnDaemon??Nvs,i=t.now??Date.now;if(lUt()||nJe!==null||oUt||i()<tJe)return;if(e()){Lvs();return}let s=ZHe();if(s!==null){nJe=s;return}oUt=!0,n().then(()=>{eJe=0,tJe=0},a=>{eJe+=1,tJe=i()+Fvs(eJe),a instanceof rJe&&(nJe=a.message)}).finally(()=>{oUt=!1})}import{existsSync as Bvs,readFileSync as $vs,writeFileSync as NTc,chmodSync as MTc}from"node:fs";import{join as Uvs}from"node:path";var jvs="secrets.json";function Wvs(t){return Uvs(t,jvs)}function Qvs(t){let e=QB(t);if(!e)return{relayTokens:{}};let n=Wvs(e);if(!Bvs(n))return{relayTokens:{}};try{return{relayTokens:JSON.parse($vs(n,"utf8")).relayTokens??{}}}catch{return{relayTokens:{}}}}function Hpr(t,e){return Qvs(e).relayTokens[t]}function iJe(t,e="user"){let n=Ik(e),i=n.remoteCanvas.targets[t];if(i===void 0){let a=Object.keys(n.remoteCanvas.targets);throw FC(`no remote canvas target named '${t}'`+(a.length>0?` \u2014 configured: ${a.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let s=Hpr(i.relayTokenRef,e);if(s===void 0||s==="")throw FC(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:i.previewEndpoint,relayToken:s}}function sJe(t,e){throw t instanceof bh?_mn(t,e):t}var Jvs=4096,Kvs=20;function Yvs(){let t;try{t=Vvs(Hvs(Hw(),"crtrd.log"),"r");let{size:e}=Gvs(t),n=Math.max(0,e-Jvs),i=e-n;if(i<=0)return;let s=Buffer.alloc(i);zvs(t,s,0,i,n);let u=s.toString("utf8").split(`
2079
+ `}function vAs(t,e){let n=e+2,i=a=>Math.max(1,Math.min(a-1,e)),s=t.spans.map(a=>a!==null&&(a[0]<=1||a[1]>=n));return{lines:t.lines,rows:t.rows.map((a,u)=>s[u]===!0?null:a),spans:t.spans.map((a,u)=>a===null||s[u]===!0?null:[i(a[0]),i(a[1])]),blocks:t.blocks.map(a=>({type:a.type,start:i(a.start),end:i(a.end)}))}}function kpr(t,e,n){let i=L8(t).length;return vAs(ZVe(AAs(t,e),n),i)}function zHe(t){let e=[],n=new Array(t.lines.length).fill(null);for(let i=0;i<t.lines.length;i++){let s=t.spans[i]??null;if(s===null){let u=t.rows[i]??null,p=u!==null?t.blocks[u]:void 0;if(p===void 0)continue;s=[p.start,p.end]}let a=e[e.length-1];a!==void 0&&a.lastRow===i-1&&a.start===s[0]&&a.end===s[1]?a.lastRow=i:e.push({start:s[0],end:s[1],firstRow:i,lastRow:i}),n[i]=e.length-1}if(e.length===0){e.push({start:t.blocks[0]?.start??1,end:t.blocks[t.blocks.length-1]?.end??1,firstRow:0,lastRow:Math.max(0,t.lines.length-1)});for(let i=0;i<n.length;i++)n[i]=0}return{units:e,rowUnits:n}}function LX(t,e){let n=-1;for(let i=0;i<t.length;i++){let s=t[i];s.start<=e&&s.end>=e&&(n===-1||s.end-s.start<t[n].end-t[n].start)&&(n=i)}if(n!==-1)return n;for(let i=0;i<t.length;i++)if(t[i].start>e)return i;return Math.max(0,t.length-1)}function K8t(t,e){for(let n=0;n<t.length;n++)if(t[n].start===e.start&&t[n].end===e.end)return n;return LX(t,e.start)}function LCe(t,e,n){let i=-1,s=-1;if(t.forEach((a,u)=>{a.start<=n&&a.end>=e&&(i===-1&&(i=u),s=u)}),i===-1){let a=LX(t,e);return{lo:a,hi:a}}return{lo:i,hi:s}}import{closeSync as qvs,fstatSync as Gvs,openSync as Vvs,readSync as zvs}from"node:fs";import{join as Hvs}from"node:path";import{spawn as gvs,execFileSync as bTc}from"node:child_process";import{createRequire as _vs}from"node:module";import{dirname as iUt,join as cde}from"node:path";import{fileURLToPath as yvs,pathToFileURL as sUt}from"node:url";import{existsSync as bvs,lstatSync as Avs,mkdirSync as vvs,openSync as xvs,closeSync as wvs}from"node:fs";import{copyFileSync as xAs,mkdirSync as JHe,existsSync as HHe,readFileSync as wAs,writeFileSync as Npr,chmodSync as SAs,readdirSync as EAs,renameSync as BX,realpathSync as Ipr,unlinkSync as CAs,rmSync as TAs,linkSync as Ppr}from"node:fs";import{homedir as Mpr}from"node:os";import{dirname as kAs,join as bA}from"node:path";import{spawnSync as Y8t}from"node:child_process";var KHe="crouter";function $Ce(){return bA(Mpr(),IR,"host")}function IAs(){return bA($Ce(),KHe)}function X8t(){return bA($Ce(),".source.json")}function PAs(t){let e=kAs(t);for(let n of[e,bA(e,"..","lib")]){if(!HHe(n))continue;let i=EAs(n).find(s=>s.startsWith("libnode.")&&s.endsWith(".dylib"));if(i!==void 0)return bA(n,i)}return null}function Dpr(t,e,n){let i=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;xAs(t,i),n!==void 0&&SAs(i,n),BX(i,e)}function Rpr(t=X8t()){try{return JSON.parse(wAs(t,"utf8"))}catch{return null}}var DAs=3e4;function RAs(t){let e=bA(Mpr(),IR),n=bA(e,"host.lock");return JHe(e,{recursive:!0}),kk(n,t,{timeoutMs:DAs,timeoutError:()=>new Error(`timed out waiting for branded host lock: ${n}`)})}function NAs(t={}){let e=t.configured?.trim();return e?[e]:[t.discovered?.trim()||"-"]}function MAs(){if(process.platform!=="darwin")return null;let t=Y8t("security",["find-identity","-v","-p","codesigning"],{stdio:["pipe","pipe","pipe"]});if(t.status!==0)return null;let n=(t.stdout??"").toString().split(`
2080
+ `).map(i=>i.match(/\)\s+[A-Fa-f0-9]{40}\s+"([^"]+)"/)?.[1]??null).filter(i=>i!==null);return n.find(i=>i.startsWith("Apple Development:"))??n.find(i=>i.startsWith("Developer ID Application:"))??n[0]??null}function OAs(t,e){let n=Y8t("codesign",["-s",e,"--deep","--force",t],{stdio:["pipe","pipe","pipe"]});return{ok:n.status===0,stderr:(n.stderr??"").toString().trim()}}function FAs(t){if(process.platform!=="darwin")return;let e=NAs({configured:process.env.CRTR_CODESIGN_IDENTITY,discovered:MAs()}),n="";for(let i of e){let s=OAs(t,i);if(s.ok)return;n=s.stderr}throw n&&!n.includes("valid on disk")&&DR({event:"host.codesign.failed",level:"debug",error:n}),new Error(`codesign failed for ${t}: ${n||"codesign did not exit successfully"}`)}function LAs(t,e,n=FAs){e!==null&&n(e),n(t)}function BCe(t,e=5e3){try{return Y8t(t,["-e",""],{stdio:"ignore",timeout:e}).status===0}catch{return!1}}function BAs(){return RAs(()=>{let t=$Ce(),e=IAs(),n=Ipr(process.execPath);if(HHe(e)&&Ipr(e)===n)return e;let i=Rpr(),s=PAs(n),a=s!==null?s.split("/").pop():null,u=x=>HHe(e)&&x!==null&&x.version===2&&(x.libnode===null||HHe(bA(t,x.libnode))),p=x=>u(x)&&x.source===n&&x.libnode===a;if(p(i)&&BCe(e))return e;JHe(t,{recursive:!0});let f=bA(t,`.reconcile.${process.pid}.${Math.random().toString(36).slice(2)}`),_=bA(f,"previous");JHe(f);let m=!1,b=u(i)&&BCe(e);try{let x=bA(f,KHe),k=a!==null?bA(f,a):null;if(s!==null&&k!==null&&Dpr(s,k),Dpr(n,x,493),LAs(x,k),!BCe(x))throw new Error(`rebuilt branded host failed its startup check: ${x}`);if(b&&UAs(_,e,i),m=!0,k!==null&&BX(k,bA(t,a)),BX(x,e),$As({version:2,source:n,libnode:a}),!p(Rpr())||!BCe(e))throw new Error(`published branded host tuple failed validation: ${e}`);if(i?.libnode!=null&&i.libnode!==a)try{CAs(bA(t,i.libnode))}catch{}return e}catch(x){throw m&&b&&jAs(_,e,i),x}finally{TAs(f,{recursive:!0,force:!0})}})}function $As(t){let e=X8t(),n=`${e}.tmp.${process.pid}.${Math.random().toString(36).slice(2)}`;Npr(n,JSON.stringify(t)),BX(n,e)}function UAs(t,e,n){JHe(t),Ppr(e,bA(t,KHe)),n.libnode!==null&&Ppr(bA($Ce(),n.libnode),bA(t,n.libnode)),Npr(bA(t,".source.json"),JSON.stringify(n))}function jAs(t,e,n){if(n.libnode!==null&&BX(bA(t,n.libnode),bA($Ce(),n.libnode)),BX(bA(t,KHe),e),BX(bA(t,".source.json"),X8t()),!BCe(e))throw new Error(`failed to restore previous branded host tuple: ${e}`)}function Opr(){return process.env.CRTR_BRANDED_HOST==="0"||process.platform!=="darwin"||import.meta.url.endsWith(".ts")?process.execPath:BAs()}import{existsSync as WAs,readFileSync as QAs}from"node:fs";import{join as qAs}from"node:path";function GAs(){return Aun()??qAs(Hw(),"crtrd.pid")}function UCe(){let t=GAs();if(!WAs(t))return null;let e=QAs(t,"utf8").trim(),n=Number(e);return Number.isFinite(n)&&n>0?n:null}function Fpr(){let t=UCe();return t!==null&&EF(t)}import{rmSync as uvs}from"node:fs";import{statSync as pvs}from"node:fs";import{join as dvs}from"node:path";var KAs=Cu(DX(),1);var jCe=Cu(DX(),1);var jpr=Cu(DX(),1);var nUt="__CROUTER_SYNTHETIC_NAMESPACE__",avs="__CROUTER_SYNTHETIC_NAMESPACE_SCALAR__",x1c=["---","kind: knowledge",`namespace: ${avs}`,`when-and-why-to-read: When working in \`${nUt}\`, this knowledge should be read because it names the namespace every document in this project answers under.`,"surfaces:"," - on: workspace-open"," at: content"," - on: read",' match: "./**"'," at: content","---",`# ${nUt}`,"",`This project's memory store. Every document here answers at \`${nUt}/<local name>\`.`,""].join(`
2081
+ `);var rUt=Cu(DX(),1);function Qpr(){return dvs(Hw(),"daemon-startup-blocked.json")}function fvs(t){try{let e=pvs(t);return{path:t,sizeBytes:e.size,mtimeMs:e.mtimeMs}}catch{return{path:t,sizeBytes:null,mtimeMs:null}}}function mvs(t,e){return t.sizeBytes===e.sizeBytes&&t.mtimeMs===e.mtimeMs}function XHe(){try{uvs(Qpr(),{force:!0})}catch{}}function ZHe(){let t=RR(Qpr());return t===null||typeof t.message!="string"||!Array.isArray(t.blockers)?null:t.blockers.length===0||t.blockers.some(n=>!mvs(n,fvs(n.path)))?(XHe(),null):t.message}var Svs=["CRTR_NODE_ID","CRTR_KIND","CRTR_MODE","CRTR_LIFECYCLE","CRTR_NODE_CWD","CRTR_CONTEXT_DIR","CRTR_CYCLES","CRTR_PROFILE_ID","CRTR_PARENT_NODE_ID","CRTR_FRONT_DOOR","TMUX","TMUX_PANE","CRTR_BROKER_ENGINE","CRTR_PI_BINARY","NODE_OPTIONS"];function Evs(){let t={...process.env};for(let e of Svs)delete t[e];return t}function Cvs(){for(let t=iUt(yvs(import.meta.url));;t=iUt(t)){if(bvs(cde(t,"bin","runtime-generation-manifest.mjs")))return t;if(iUt(t)===t)throw new Error(`cannot locate the crouter generation root from ${import.meta.url}`)}}async function Tvs(){let t=Cvs(),e=sUt(cde(t,"bin","runtime-generation-manifest.mjs")).href,{runtimeHome:n}=await import(e);try{Avs(cde(n(),"selected"))}catch(u){if(u.code!=="ENOENT")throw u;return["--conditions","crtr-src","--import",sUt(_vs(import.meta.url).resolve("tsx/esm")).href,cde(t,"src","daemon","crtrd-cli.ts")]}let i=sUt(cde(t,"bin","runtime-selector.mjs")).href,{tryResolveRuntime:s}=await import(i),a=s("daemon");if(!a.ok)throw new Error(`cannot resolve the selected runtime generation's daemon entry: ${a.error}`);return[a.runtime.entryPath]}var Gpr=2e4,aUt=10,qpr=1e3;async function Vpr(t=qpr){let e=Math.min(t,qpr);if(!(await Xj.forLocalSocket({autostart:!1,timeoutMs:e}).probeHealthz(e)).ok)throw new Error("crtrd health check reported not ready")}function cUt(t){return new Promise(e=>{setTimeout(e,t)})}var rJe=class extends Error{constructor(e){super(`daemon ${e} exited: startup is blocked by a standing condition that retrying cannot clear. See crtrd.err, then run \`crtr sys migrate\`.`),this.name="DaemonStartupBlockedError"}};async function kvs(t,e=3e5,n={}){let i=n.readPidfile??UCe,s=n.isPidAlive??EF,a=n.childExited,u=n.isDaemonServing,p=n.probeDaemonServing??(async x=>{if(u!==void 0){if(await u())return;throw new Error("crtrd health check reported not ready")}await Vpr(x)}),f=n.sleepMs??cUt,_=n.now??Date.now,m=null,b=null;return await i4e({windowMs:e,pollIntervalMs:aUt,now:_,sleep:f,retry:x=>x!==b,probe:async x=>{let k=i();if(k===null||!s(k)){let I=a?.();throw I!=null&&(I.signal!==null?b=new Error(`daemon ${t} exited before becoming ready (by ${I.signal})`):I.code===78?b=new rJe(t):I.code!==0&&(b=new Error(`daemon ${t} exited before becoming ready (with exit code ${I.code??"?"})`)),b!==null)?b:new Error(`daemon ${t} has no live pidfile owner`)}await p(x),m=k}}),m===t?null:m}async function Ivs(t,e=Gpr,n={}){let i=n.readPidfile??UCe,s=n.isPidAlive??EF,a=n.sleepMs??cUt,u=n.now??Date.now,p=u()+e;for(;u()<=p;){if(!s(t)&&i()!==t)return;await a(aUt)}throw new Error(`daemon ${t} did not exit and release its pidfile within ${e}ms`)}var Pvs=2e3,Dvs=5e3;async function Rvs(t,e=Gpr,n={}){let i=n.isPidAlive??EF,s=n.sleepMs??cUt,a=n.now??Date.now;try{process.kill(t,"SIGTERM")}catch{}try{return await Ivs(t,e,n),"terminated"}catch{}try{process.kill(t,"SIGKILL")}catch{}let u=a()+Pvs;for(;a()<=u;){if(!i(t))return"killed";await s(aUt)}throw new Error(`daemon ${t} survived both SIGTERM and SIGKILL`)}async function Nvs(){let t=UCe();if(t!==null&&EF(t))try{return await Vpr(),{started:!1,existing_pid:t}}catch(f){return{started:!1,existing_pid:t,running:!0,serving:!1,probe_error:f.message}}vvs(Hw(),{recursive:!0});let e=await Tvs(),n=cde(Hw(),"crtrd.err"),i=xvs(n,"a");KBe()===void 0&&qfn();let s=gvs(Opr(),[...e,"--canvas-home",Hw()],{detached:!0,stdio:["ignore",i,i],env:Evs()});wvs(i);let a=s.pid;if(a===void 0)throw new Error("daemon spawn did not return a pid");let u=null;s.once("exit",(f,_)=>{u={code:f,signal:_}}),s.unref();let p;try{p=await kvs(a,3e5,{childExited:()=>u})}catch(f){let _=XBe(ygt())===a;if(u===null&&!_)try{await Rvs(a,Dvs)}catch{}throw f}return p!==null?{started:!1,existing_pid:p}:{started:!0,pid:a}}function lUt(){return vun()||process.argv.includes("--no-autostart")}var Mvs=5e3,Ovs=6e4,oUt=!1,eJe=0,tJe=0,nJe=null;function Fvs(t){return Math.min(Mvs*2**(t-1),Ovs)}function Lvs(){eJe=0,tJe=0,nJe=null,XHe()}function zpr(t={}){let e=t.isDaemonRunning??Fpr,n=t.spawnDaemon??Nvs,i=t.now??Date.now;if(lUt()||nJe!==null||oUt||i()<tJe)return;if(e()){Lvs();return}let s=ZHe();if(s!==null){nJe=s;return}oUt=!0,n().then(()=>{eJe=0,tJe=0},a=>{eJe+=1,tJe=i()+Fvs(eJe),a instanceof rJe&&(nJe=a.message)}).finally(()=>{oUt=!1})}import{existsSync as Bvs,readFileSync as $vs,writeFileSync as FTc,chmodSync as LTc}from"node:fs";import{join as Uvs}from"node:path";var jvs="secrets.json";function Wvs(t){return Uvs(t,jvs)}function Qvs(t){let e=QB(t);if(!e)return{relayTokens:{}};let n=Wvs(e);if(!Bvs(n))return{relayTokens:{}};try{return{relayTokens:JSON.parse($vs(n,"utf8")).relayTokens??{}}}catch{return{relayTokens:{}}}}function Hpr(t,e){return Qvs(e).relayTokens[t]}function iJe(t,e="user"){let n=Ik(e),i=n.remoteCanvas.targets[t];if(i===void 0){let a=Object.keys(n.remoteCanvas.targets);throw FC(`no remote canvas target named '${t}'`+(a.length>0?` \u2014 configured: ${a.join(", ")}`:" \u2014 none configured yet")+`. Add one with \`crtr canvas config add ${t} --preview <url> --relay-token -\`.`)}let s=Hpr(i.relayTokenRef,e);if(s===void 0||s==="")throw FC(`target '${t}' has no stored relay token \u2014 add it with \`crtr canvas config add ${t} --relay-token -\`.`);return{previewEndpoint:i.previewEndpoint,relayToken:s}}function sJe(t,e){throw t instanceof bh?_mn(t,e):t}var Jvs=4096,Kvs=20;function Yvs(){let t;try{t=Vvs(Hvs(Hw(),"crtrd.log"),"r");let{size:e}=Gvs(t),n=Math.max(0,e-Jvs),i=e-n;if(i<=0)return;let s=Buffer.alloc(i);zvs(t,s,0,i,n);let u=s.toString("utf8").split(`
2082
2082
  `).filter(p=>p.trim()!=="").slice(-Kvs).join(`
2083
2083
  `).trim();return u===""?void 0:`crtrd.log (tail):
2084
2084
  ${u}`}catch{return}finally{if(t!==void 0)try{qvs(t)}catch{}}}function Hm(t){return lUt()?Xj.forLocalSocket({autostart:!1,...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{}}):Xj.forLocalSocket({...t?.timeoutMs!==void 0?{timeoutMs:t.timeoutMs}:{},onColdSocket:async()=>{zpr()},coldStartDiagnostic:Yvs,coldStartAbort:ZHe,coldStartPollWindowMs:3e5})}var Xvs=2e3,QCe=class{client;rosterCache=null;rosterInFlight=null;constructor(e=Hm()){this.client=e}async roster(){let e=Date.now();return this.rosterCache!==null&&e-this.rosterCache.at<Xvs?this.rosterCache.index:this.rosterInFlight!==null?this.rosterInFlight:(this.rosterInFlight=this.client.canvasRoster().then(n=>{let i={subscriptions:new Map,subscribers:new Map};for(let s of n.edges){let a={node_id:s.to_id,active:s.active,created:s.created},u={node_id:s.from_id,active:s.active,created:s.created},p=i.subscriptions.get(s.from_id);p===void 0?i.subscriptions.set(s.from_id,[a]):p.push(a);let f=i.subscribers.get(s.to_id);f===void 0?i.subscribers.set(s.to_id,[u]):f.push(u)}return this.rosterCache={at:Date.now(),index:i},i}).finally(()=>{this.rosterInFlight=null}),this.rosterInFlight)}async orNull(e){try{return await e()}catch(n){if(n instanceof bh&&n.status===404)return null;throw n}}async getNode(e){return this.orNull(()=>this.client.getNode(e))}async getRow(e){return this.orNull(()=>this.client.getNode(e))}async listNodes(e){let n=e?.status,i;if(Array.isArray(n)){let s=new Set(n);i=(await this.client.listNodes()).filter(u=>s.has(u.status))}else n!==void 0?i=await this.client.listNodes({status:n}):i=await this.client.listNodes();return i}async subscriptionsOf(e){return this.roster().then(n=>n.subscriptions.get(e)??[])}async subscribersOf(e){return this.roster().then(n=>n.subscribers.get(e)??[])}async view(e){let n=new Set([e]),i=[],s=(await this.subscriptionsOf(e)).map(a=>a.node_id);for(;s.length>0;){let a=s.shift();if(!n.has(a)){n.add(a),i.push(a);for(let u of await this.subscriptionsOf(a))n.has(u.node_id)||s.push(u.node_id)}}return i}async ticketCountsForView(e){let n=[e,...await this.view(e)];return(await this.client.attentionCounts(n)).counts}async hasActiveLiveSubscription(e){let n=(await this.subscriptionsOf(e)).filter(i=>i.active);for(let i of n){let s=await this.getRow(i.node_id);if(s&&(s.status==="active"||s.status==="idle"))return!0}return!1}};function Jpr(t){let e=t?.scope??"user",n=t?.canvasName??Fmn(e).activeCanvas??null;if(!n)return new QCe;let{previewEndpoint:i,relayToken:s}=iJe(n,e);return new V8(i,s)}function Kpr(t){return GVe("review-activity",t)}var qCe=class extends Error{code;details;constructor(e,n,i){super(n),this.name="ReviewDocumentError",this.code=e,this.details=i}};function Ypr(t,e){return{async anchorBase(){let n=await e(()=>Hm().getReviewDocumentBase(t));return{file:n.file,text:n.anchor_base_text,docHash:n.anchor_base_sha256}},async list(){return(await e(()=>Hm().listReviewComments(t,{status:"all"}))).comments.map(Zvs)},async create(n){await lde(()=>e(()=>Hm().createReviewComment(t,{text:n.text,anchor:{line:n.line,end_line:n.endLine},doc_hash:n.docHash,actor_node_id:null})))},async edit(n){await lde(()=>e(()=>Hm().editReviewComment(n.id,{text:n.text,if_revision:n.ifRevision,actor_node_id:null})))},async resolve(n){await lde(()=>e(()=>Hm().resolveReviewComment(n,{actor_node_id:null})))},async reopen(n){await lde(()=>e(()=>Hm().reopenReviewComment(n,{actor_node_id:null})))},async remove(n){await lde(()=>e(()=>Hm().deleteReviewComment(n,{actor_node_id:null})))},async remapRanges(n){await lde(()=>e(()=>Hm().updateReviewCommentRanges(t,{from_doc_hash:n.fromDocHash,to_doc_hash:n.toDocHash,entries:n.entries.map(i=>"detached"in i?{comment_id:i.id,detached:!0}:{comment_id:i.id,anchor:{line:i.anchor.line,end_line:i.anchor.endLine}})})))},onChanged(n){return Kpr(n)}}}function Zvs(t){let e={line:t.anchor.line,endLine:t.anchor.end_line};return{id:t.comment_id,revision:t.revision,...e,lineText:t.anchor_line_text,comment:t.text,status:t.status,authorKind:t.author.kind,createdAt:t.created_at,anchorStatus:t.anchor_state==="detached"?"detached":"live",...t.anchor_state==="detached"?{originalRange:e}:{}}}async function lde(t){try{return await t()}catch(e){throw e instanceof bh&&exs(e.code)?new qCe(e.code,e.message,e.details):e}}function exs(t){return t==="stale_document"||t==="stale_comment"||t==="range_batch_incomplete"||t==="range_batch_stale"}function dUt(){let t=Uj();return t!==void 0?{CRTR_HOME:t}:{}}function pUt(){return{...dUt(),CRTR_ATTACH_WAKE_PARKED:"0"}}function uUt(t){let e=Xgt();if(e!==null){for(let n of e)if(VB(n,"@crtr_node")===t)return n}}function Xpr(t,e,n,i,s){let a=Bie(t,{cwd:n,env:pUt(),command:`crtr surface attach to ${e}`});if(a===null)return{focused:!1,session:null,inPlace:!1,revived:s};let u=n9(a);return u!==null&&p4e(u.window,"even-horizontal"),d4e(a),{focused:!0,session:u?.session??i,inPlace:!1,revived:s}}async function Zpr(t,e){let n=e.pane??process.env.TMUX_PANE??p$()?.pane;if(n===void 0||n==="")return{focused:!1,session:null,inPlace:!1,revived:!1};let s=(await Hm().ensureAttach(t,{resume:!0,revive:!0,wakeParked:!1}).catch(sJe)).revived,a=n9(n)?.session??null;if(e.inPlace===!0){let p=VB(n,"@crtr_node"),f=uUt(t);f!==void 0&&f!==n&&xH(f)&&t9(f);try{GB(n,"@crtr_node","")}catch{}let _=Ygt(n),m=p!==void 0&&p!==""?{...pUt(),CRTR_ATTACH_ROSTER:p}:pUt(),b=n_t({pane:n,cwd:e.cwd,env:m,command:`crtr surface attach to ${t}`});return b&&_!==null&&Kgt(_,e.name),{focused:b,session:a,inPlace:!0,revived:s}}if(e.newPane===!0){let p=uUt(t);return p!==void 0&&xH(p)&&t9(p),Xpr(n,t,e.cwd,a,s)}let u=uUt(t);if(u!==void 0){let p=n9(u);if(p!==null)return i_t(p.session),Pbe(p.session,p.window),d4e(u),{focused:!0,session:p.session,inPlace:!0,revived:s}}return Xpr(n,t,e.cwd,a,s)}var txs=99,nxs=40,rxs=12,ixs=.42,sxs=.4;function edr(t){let{companionNodeId:e,cwd:n,callerPane:i}=t;if(!jx())return{ok:!1,reason:"no_tmux"};let a=t_t().filter(m=>m.nodeId===e&&u4e(m.pane)).sort((m,b)=>b.stampMs-m.stampMs);if(a.length>0)return{ok:!0,paneId:a[0].pane,origin:"adopted"};if(i===void 0||i==="")return{ok:!1,reason:"no_caller_pane"};let u=Zgt(i);if(u===null)return{ok:!1,reason:"split_refused"};let p,f;u.cols>=txs?(p=!1,f=Math.max(nxs,Math.round(u.cols*ixs))):(p=!0,f=Math.max(rxs,Math.round(u.rows*sxs)));let _=Bie(i,{cwd:n,env:dUt(),command:`crtr surface attach to ${e}`,vertical:p,size:f});return _===null?{ok:!1,reason:"split_refused"}:{ok:!0,paneId:_,origin:"opened"}}function tdr(t){return xH(t)&&u4e(t)}function ndr(t,e){!xH(t)||VB(t,"@crtr_node")!==e||t9(t)}var oxs=8,oJe=(t,e,n)=>rze(t,e,n);function idr(t){return e5t(t.manifest,Object.fromEntries(t.responses),{completedAt:""})}function axs(t,e){return e.id===void 0?void 0:t.slots.find(n=>n.id===e.id)}function sdr(t){if(t===void 0||t.state==="unanswered")return"unanswered";if(t.raw!==void 0)return"custom response";let e=t.text!==void 0?[t.text.edited?"edited":"accepted"]:t.groups.map(n=>n.picked.length===0?"none":n.picked.map(i=>i.label).join(", "));return t.freetext!==void 0&&e.push(t.freetext),t.comments.length>0&&e.push(`${t.comments.length} comment${t.comments.length===1?"":"s"}`),e.join("; ")||"answered"}function rdr(t,e){return Z6t(t,e)}function odr(t,e,n){let i=Math.min(Math.max(20,e-4),120),s=Math.max(20,e-4),a=["",` ${Jv}${nv}${vm(t.manifest.title)}${Ps}`];if(t.manifest.subtitle)for(let x of xF(vm(t.manifest.subtitle),i))a.push(` ${ua}${x}${Ps}`);if(t.displayMarkdown!==""){a.push("");for(let x of oJe(t.displayMarkdown,i,s))a.push(` ${x}`)}else t.manifest.dialect==="html"&&a.push("",` ${ua}HTML page \u2014 open in Northlight to read this${Ps}`);let u=t.slots.length>0;u&&a.push(` ${ua}${j8(i)}${Ps}`,"");let p=idr(t),f=-1,_;for(let x=0;x<t.slots.length;x++){let k=t.slots[x];t.manifest.steps>1&&k.step!==f&&(f!==-1&&a.push(""),a.push(` ${Jv}Step ${k.step+1}/${t.manifest.steps}${Ps}`),f=k.step);let I=k.id===void 0?void 0:t.responses.get(k.id),C=tv(k)?$8(t,k)?`${SX}\u2713${Ps}`:`${ua}\u25CB${Ps}`:`${ua}\xB7${Ps}`,D=x===t.currentIndex?`${nv}\u25B8${Ps} `:" ";x===t.currentIndex&&(_=a.length),a.push(` ${D}${C} ${mI(U8(jpe(k)),Math.max(10,e-16))}`),I!==void 0&&a.push(` ${ua}${mI(U8(sdr(axs(p,k))),Math.max(10,e-10))}${Ps}`)}if(t.manifest.slots.some(x=>tv(x)&&!BD(x))){a.push("");for(let x of xF("This page must be answered in Northlight. Leaving it here keeps it in your inbox; x on the list cancels it.",i-2))a.push(` ${Kv}${x}${Ps}`)}u&&a.push(""),a.push(` ${ua}${j8(i)}${Ps}`);let b=!t.manifest.slots.some(tv)?` ${ua}u/d${Ps} scroll ${ua}q${Ps} dismiss`:` ${ua}enter${Ps} review ${ua}j/k${Ps} navigate ${ua}u/d${Ps} scroll ${ua}q${Ps} close`;return hdr(a,b,t,e,n,i+2,t.followSelection?_:void 0)}function ude(t,e,n){let i=[...t],s=Math.max(0,Math.min(e,i.length)),a=adr(t,n),u=0;for(let _=0;_<a.length;_++)a[_].start<=s&&(u=_);let p=a.map((_,m)=>{if(m!==u)return i.slice(_.start,_.end).join("");let b=i.slice(_.start,s).join(""),x=s<_.end?i[s]:" ",k=s<_.end?i.slice(s+1,_.end).join(""):"";return`${b}${W1e}${x}${Ps}${k}`}),f=a[u];return s===f.end&&Hv(i.slice(f.start,f.end).join(""))>=n&&(p[u]=i.slice(f.start,f.end).join(""),p.splice(u+1,0,`${W1e} ${Ps}`)),p}function GCe(t,e){let n=[...t],i=Math.max(0,Math.min(e,n.length));for(;i>0&&/\s/.test(n[i-1]);)i--;for(;i>0&&!/\s/.test(n[i-1]);)i--;return i}function aJe(t,e){let n=[...t],i=Math.max(0,Math.min(e,n.length));for(;i<n.length&&/\s/.test(n[i]);)i++;for(;i<n.length&&!/\s/.test(n[i]);)i++;return i}function adr(t,e){let n=[...t],i=Math.max(1,e),s=[],a=0,u=0;for(let p=0;p<n.length;p++){let f=n[p];if(f===`
@@ -2123,7 +2123,7 @@ Follow the instructions below exactly as written \u2014 every part, including th
2123
2123
  ${i}`}function Jmr(t){try{let e=JSON.parse(t);return Array.isArray(e)?e.flatMap(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return[];let i=n;return typeof i.name!="string"||typeof i.description!="string"||typeof i.source!="string"?[]:i.source!=="builtin"&&i.source!=="command"&&i.source!=="template"?[]:i.template!==void 0&&typeof i.template!="string"?[]:i.expansion!==void 0&&!qJe(i.expansion)?[]:[{name:i.name,description:i.description,source:i.source,...typeof i.template=="string"?{template:i.template}:{},...qJe(i.expansion)?{expansion:i.expansion}:{}}]}):[]}catch{return[]}}function yEs(t){let e=[],n="",i=null;for(let s of t)i!==null?s===i?i=null:n+=s:s==='"'||s==="'"?i=s:/\s/.test(s)?n!==""&&(e.push(n),n=""):n+=s;return n!==""&&e.push(n),e}function bEs(t,e){let n=e.join(" ");return t.replace(/\$\{(\d+):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(i,s,a,u,p,f)=>{if(s!==void 0)return e[Number.parseInt(s,10)-1]||a||"";if(u!==void 0){let _=Math.max(0,Number.parseInt(u,10)-1);return p!==void 0?e.slice(_,_+Number.parseInt(p,10)).join(" "):e.slice(_).join(" ")}return f==="ARGUMENTS"||f==="@"?n:e[Number.parseInt(f||"0",10)-1]??""})}function Kmr(t,e){let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(n===null)return;let i=n[1];if(e.some(f=>f.source==="builtin"&&f.name===i))return;let s=t.indexOf(" "),a=s===-1?t.slice(1):t.slice(1,s),u=e.find(f=>f.source==="command"&&f.name===a);if(u!==void 0){if(u.expansion===void 0||!qJe(u.expansion))return;let f=s===-1?"":t.slice(s+1);return{name:u.name,invocation:t,content:Hmr(u.expansion,f)}}let p=e.find(f=>f.source==="template"&&f.name===i);if(typeof p?.template=="string")return{name:p.name,invocation:t,content:bEs(p.template,yEs(n[2]??""))}}var AEs="CRTR_TIMING",Ymr="CRTR_TIMING_T0";function vEs(){return performance.timeOrigin+performance.now()}var Xmr=(()=>{let t=process.env[AEs];return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"})(),xEs=(()=>{if(!Xmr)return 0;let t=Number(process.env[Ymr]);if(Number.isFinite(t)&&t>0)return t;let e=performance.timeOrigin;return process.env[Ymr]=String(e),e})(),wEs=(()=>{let t=process.env.CRTR_TIMING_PROC;return t!==void 0&&t!==""?t:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})(),s7t=0;function zX(t,e){if(!Xmr)return;let n=vEs(),i=n-xEs,s=s7t===0?i:n-s7t;s7t=n;let a=performance.now(),u=e===void 0?"":" "+Object.entries(e).map(([_,m])=>`${_}=${String(m)}`).join(" "),p=process.env.CRTR_TIMING_PROC??wEs,f=_=>_.toFixed(1).padStart(8);process.stderr.write(`[timing] +${f(i)}ms \u0394${f(s)}ms up=${f(a)}ms t=${n.toFixed(1)} ${p}/${process.pid} ${t}${u}
2124
2124
  `)}function Zmr(t,e){let{socket:n}=t,i=()=>{n.send({type:"get_commands"}),e.resetMemoryRefs()},s=p=>{if(p.for==="get_commands"&&p.ok&&p.detail){try{e.setCommands(Jmr(p.detail))}catch{}return}if(p.for==="navigate_tree"&&p.ok){p.detail&&e.setEditorText(p.detail);return}if(p.for==="share"){p.ok&&p.detail?(e.setNotice(`Shared: ${p.detail}`),D8t(p.detail)):p.ok||e.setNotice(`share failed: ${p.detail??"unknown error"}`);return}if(p.for==="clone"&&!p.ok){e.setNotice(`clone failed: ${p.detail??"unknown error"}`);return}if(!p.ok){e.setNotice(`command failed: ${p.for}${p.detail?` \u2014 ${p.detail}`:""}`);return}p.for==="reload"&&(e.reloadBindings(),e.setCommands(),i(),e.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},a=p=>{e.chat.handleEvent(p),p.type==="session_info_changed"?e.refreshNodeIdentity():p.type==="thinking_level_changed"?e.setNotice(e.modelThinkingLabel()??`Thinking level: ${p.level}`):(p.type==="tool_execution_start"||p.type==="tool_execution_end")&&e.renderFooter()},u=!1;return p=>{switch(e.foldState(p),p.type){case"welcome":{u||(u=!0,zX("viewer.welcome")),e.chat.applySnapshot(p.snapshot),e.refreshNodeIdentity(),i(),p.pending_dialog!=null&&e.attachDialog(p.pending_dialog);break}case"tool_group_summary":e.chat.applyToolGroupSummary(p.key,p.summary);break;case"working_activity":e.chat.setWorkingActivity(p.activity);break;case"model_changed":{let f=e.modelThinkingLabel();f&&e.setNotice(f);break}case"error":e.setNotice(p.code==="read_only"?"read-only":`error: ${p.message}`);break;case"node_named":break;case"ack":s(p);break;case"extension_ui_request":p.method!=="setStatus"&&p.method!=="setWidget"&&p.method!=="setTitle"&&e.attachDialog(p);break;case"extension_ui_dismiss":e.dismissDialog(p.id);break;case"bash_start":e.chat.bashStart(p.command,p.excludeFromContext);break;case"bash_output":e.chat.bashOutput(p.chunk);break;case"bash_end":e.chat.bashEnd(p);break;default:a(p);break}}}var SEs=1e3;function ehr(t,e){let{tui:n,editor:i}=t,s=0,a={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":()=>{let u=Date.now();if(u-s<SEs){s=0,e.cancelTurn();return}s=u,i.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),n.requestRender()},"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.previous":()=>e.cycleModelLadder("backward"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip};return n.addInputListener(u=>{if(u.includes("\x1B[I")||u.includes("\x1B[O")){e.setPaneFocused(u.lastIndexOf("\x1B[I")>u.lastIndexOf("\x1B[O")),n.requestRender();let f=u.replaceAll("\x1B[I","").replaceAll("\x1B[O","");return f.length>0?{data:f}:{consume:!0}}let p=zgt(u);if(p!==void 0)return k8t(p.actionId,a),p.remaining.length>0?{data:p.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(u)?{consume:!0}:e.searchHandleKey(u)?{consume:!0}:i.focused&&Dur(e.bindings(),u,e.viewportActions())?{consume:!0}:e.stripHandleKey(u)?{consume:!0}:e.rosterHandleKey(u)?{consume:!0}:Pur(e.bindings(),u,a)?{consume:!0}:void 0})}import{spawnSync as EEs}from"node:child_process";var CEs="\x1B[?1002h\x1B[?1006h",thr="\x1B[?1002l\x1B[?1006l",nhr=3;function TEs(){if(!jx())return!1;let t=EEs("tmux",["show-options","-gv","mouse"],{encoding:"utf8"});return t.status===0&&t.stdout?.trim()==="on"}function rhr(t,e){let n=e==="on"||e==="tmux"&&TEs(),i=()=>{t(n?CEs:thr)},s=()=>{n=!1;try{t(thr)}catch{}};return process.once("exit",s),{enabled:()=>n,toggle:()=>(n=!n,i(),n),reassert:i,disable:s,install:(a,u)=>a.addInputListener(p=>{let f=!1,m=p.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,(b,x,k,I,C)=>{f=!0;let D=Number(x),R=D&-29;return R===64?u.onWheel("up",nhr,Number(k)):R===65?u.onWheel("down",nhr,Number(k)):R===32&&C==="M"?u.onPrimaryDrag(Number(k),Number(I)):R===0&&C==="m"?u.onPrimaryRelease(Number(k),Number(I)):D===0&&C==="M"&&u.onPrimaryPress(Number(k),Number(I)),""}).replace(/\x1b\[M[\s\S]{3}/g,()=>(f=!0,""));if(f)return m.length>0?{data:m}:{consume:!0}})}}function kEs(t,e){return t.row<e.row||t.row===e.row&&t.column<=e.column}function ihr(t,e,n){let[i,s]=kEs(t,e)?[t,e]:[e,t],a=[];for(let u=i.row;u<=s.row;u++){let p=u===i.row?i.column-1:0,f=u===s.row?s.column:n;f>p&&a.push({row:u,from:p,to:f})}return a}function shr(t){let e,n,i=()=>e!==void 0&&n!==void 0?{anchor:e,head:n}:void 0,s=()=>{let a=i();if(!a)return"";let u=t.frame(),p=ihr(a.anchor,a.head,t.width()).map(f=>tur(u[f.row-1]??"",f.from,f.to).trimEnd());for(;p.length>0&&p[p.length-1]==="";)p.pop();return p.join(`
2125
2125
  `)};return{begin(a,u){e={row:u,column:a},n=void 0},extend(a,u){return e===void 0||n!==void 0&&n.row===u&&n.column===a?!1:(n={row:u,column:a},!0)},release(){let a=e;if(a===void 0)return;if(n===void 0)return e=void 0,{kind:"click",column:a.column,row:a.row};let u=s();if(u==="")return e=void 0,n=void 0,{kind:"selection",notice:"Nothing to copy \u2014 selection is empty"};let{system:p,tmux:f}=jHe(u),_=p&&f?"clipboard + tmux buffer":p?"clipboard":f?"tmux buffer":void 0,m=u.split(`
2126
- `).length;return{kind:"selection",notice:_===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${m} ${m===1?"line":"lines"}) \u2014 ${_}`}},clear(){let a=n!==void 0;return e=void 0,n=void 0,a},active(){return n!==void 0},apply(a){let u=i();if(!u)return a.slice();let p=t.width(),f=a.slice();for(let _ of ihr(u.anchor,u.head,p)){let m=_.row-1;m<0||m>=f.length||(f[m]=nur(f[m],_.from,_.to,p))}return f}}}import{existsSync as IEs}from"node:fs";var ohr="\x1B_crtr-file-open;",ahr="\x1B\\";function chr(t){let e=t.indexOf(ohr);if(e===-1)return;let n=e+ohr.length,i=t.indexOf(ahr,n);return i===-1?void 0:{file:PEs(t.slice(n,i)),remaining:t.slice(0,e)+t.slice(i+ahr.length)}}function PEs(t){let e=t.startsWith("'")?DEs(t):REs(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function DEs(t){let e="",n=1;for(;;){let i=t.indexOf("'",n);if(i===-1)return;if(e+=t.slice(n,i),n=i+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function REs(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let i=t[++n];if(i===void 0)return;e+=i}return e}function lhr(t){if(!IEs(t.file))return"missing";let e=`crtr surface attach to ${_d(t.nodeId)}${t.observer?" --observer":""}`,n=`nvim ${_d(t.file)} || :; exec ${e}`;return t.beforeRespawn(),r_t({pane:t.pane,cwd:t.cwd,env:Nbe(),command:n})?"opened":"failed"}import{execFile as NEs}from"node:child_process";function c7t(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}var MEs=.72,OEs={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},FEs=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],LEs=[["crtr.graph.dismiss","dismiss"]],BEs=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],GJe=class{constructor(e,n,i,s,a,u,p="controller",f=()=>{},_=()=>{}){this.tui=e;this.self=n;this.getAsks=i;this.palette=s;this.bindings=a;this.source=u;this.role=p;this.onRefreshFailure=f;this.onNotice=_;this.remote=u instanceof V8}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;async fetchFocused(){if(this.remote)return new Set;try{return new Set((await Hm().listFocuses()).map(e=>e.node_id))}catch{return new Set}}setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return vH(this.bindings,e,n,(i,s)=>za(i,s))}hint(e){return e.flatMap(([n,i])=>this.bindings.gestures(n).length===0?[]:[`${qS(this.bindings,n)} ${i}`])}fitHints(e,n){let s=[],a=0;for(let u of this.hint(e)){let p=(s.length===0?0:3)+_I(u);if(a+p>n)break;s.push(u),a+=p}return s.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,OEs),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async buildSnapshot(){RCe();let[e,n]=await Promise.all([this.source.listNodes().catch(()=>[]),this.fetchFocused()]),i=new Map(e.map(R=>[R.node_id,R])),s=new Map,a=new Map,u=new Map,p=new Map,f=async R=>{let F=s.get(R);if(F!==void 0)return F;let L;try{L=await this.source.subscriptionsOf(R)}catch{L=[]}let U=L.map(Y=>Y.node_id).filter(Y=>i.get(Y)?.kind!=="human");return s.set(R,U),U},_=async R=>{if(u.has(R))return u.get(R);let F;try{F=(await this.source.subscribersOf(R))[0]?.node_id}catch{F=void 0}return u.set(R,F),F},m=async()=>{let R=this.self,F=new Set([R]);for(;;){let L=await _(R);if(L===void 0||F.has(L))break;F.add(L),R=L}return R},b=async R=>{let F=a.get(R);if(F!==void 0)return F;let L=[...await f(R)];return L.sort((U,Y)=>c7t(i.get(U)?.status)-c7t(i.get(Y)?.status)),a.set(R,L),L},x=new Set,k=new Set,I=async R=>{let F=i.get(R)?.status==="active";if(k.has(R))return{active:F?1:0,reveal:F||R===this.self};k.add(R);let L=0,U=!1;for(let Y of await f(R)){let V=await I(Y);L+=V.active,V.reveal&&(U=!0)}return p.set(R,L),U&&x.add(R),{active:L+(F?1:0),reveal:U||F||R===this.self}},C=await m();await I(C),await Promise.all([...s.keys()].map(R=>b(R)));let D={root:C,rows:[],autoExpanded:x,activeBelow:p,nodes:i,childIds:s,sortedChildIds:a,managerOf:u,focused:n};return D.rows=this.projectRows(D),D}projectRows(e){let n=[],i=new Set,s=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;s.length>0;){let{id:a,prefix:u,isRoot:p,isLast:f}=s.pop(),_=p?"":f?"\u2514\u2500 ":"\u251C\u2500 ";if(i.has(a)){n.push({id:a,hasKids:!1,isSelf:a===this.self,branch:u+_,cycle:!0,collapsed:!1});continue}i.add(a);let m=e.sortedChildIds.get(a)??[],b=this.folds.userExpanded.has(a)?!1:this.folds.userCollapsed.has(a)?!0:!e.autoExpanded.has(a);if(n.push({id:a,hasKids:m.length>0,isSelf:a===this.self,branch:u+_,cycle:!1,collapsed:b}),b)continue;let x=p?"":u+(f?" ":"\u2502 ");for(let k=m.length-1;k>=0;k--)s.push({id:m[k],prefix:x,isRoot:!1,isLast:k===m.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,i,s){let a=(Y,V)=>i?J8(Y,PF(),gq):V?J8(Y,PF(),Cur):H8(Y);if(n.cycle){let Y=`${n.branch} ${N1}\u21BA ${$He(n.id)}${rg}`;return a(Y,!1)}let u=e.nodes.get(n.id)??null,p=OHe(u,this.remote),f=OX(u,n.id),_=n.isSelf?`${PCe}${f}${rg}`:f,m=`${N1}${u?.kind??""}${rg}`,b=`${N1}${FHe(n.id,this.remote)}${rg}`,x=n.hasKids&&n.collapsed,k=!i&&x?`${N1}\u25B8${rg} `:" ",I=BHe(u),C=e.childIds.get(n.id)?.length??0,D=u!==null&&C>0?` ${N1}\u2933${C}${rg}`:"",R=u!==null&&u.status!=="active"&&(e.activeBelow.get(u.node_id)??0)>0?` ${MHe}\u21E3${e.activeBelow.get(u.node_id)??0}${rg}`:"",F=u!==null&&!this.remote?NHe(u,ICe(n.id)):null,L=F!==null?` \xB7 ${C8t(F)}`:"",U=`${n.branch}${k}${p} ${_} ${m} ${b}${I}${D}${R}${UHe(n.id,s)}${LHe(n.id,u,this.remote)}${L}`;return a(U,Iur(n.id,u,e.focused,this.remote))}render(e){RCe();let n=this.getAsks(),i=this.snapshot?.rows??[],s=i.findIndex(R=>R.id===this.cursorId);s<0&&(s=i.findIndex(R=>R.id===this.self),s<0&&(s=0)),this.cursorId=i[s]?.id??this.self;let a=process.stdout.rows??Eur,u=Math.max(3,Math.min(Math.floor(a*MEs),a-2)),p=Math.max(2,Math.min(i.length,u-2)),f=p;for(let R=0;R<4;R++){s<this.scrollTop&&(this.scrollTop=s),s>=this.scrollTop+f&&(this.scrollTop=s-f+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-f)));let F=p-(this.scrollTop>0?1:0)-(this.scrollTop+f<i.length?1:0);if(F===f)break;f=Math.max(1,F)}let _=Math.min(i.length,this.scrollTop+f),m=[];this.scrollTop>0&&m.push(`${N1} \u2191 ${this.scrollTop} more${rg}`);for(let R=this.scrollTop;R<_;R++){let F=this.snapshot;m.push(F!==void 0?this.renderSnapshotRow(F,i[R],R===s,n):"")}for(_<i.length&&m.push(`${N1} \u2193 ${i.length-_} more${rg}`);m.length<p;)m.push("");let b=i.length>0?`${PCe}\u2317 canvas graph${rg} ${N1}(${s+1}/${i.length})${rg}`:`${PCe}\u2317 canvas graph${rg} ${N1}(loading)${rg}`,x=this.pendingConfirm!==void 0?`${DCe}${this.pendingConfirm.label} ${PCe}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${rg}`:`${N1}${this.fitHints([...this.remote||this.role!=="controller"?LEs:FEs,...BEs],Math.max(1,e-5))}${rg}`,k=this.palette.border,I=Math.max(1,e-4),C=m.map(R=>`${k("\u2502")} ${Ha(R,I,"",!0)} ${k("\u2502")}`),D=this.palette.surface;return[this.borderRow("\u256D","\u256E",b,e),...C,this.borderRow("\u2570","\u256F",x,e)].map(D)}borderRow(e,n,i,s){let a=this.palette.border,u=Math.max(1,s-5),p=Ha(i,u,"\u2026"),f=Math.max(0,s-5-_I(p));return`${a(`${e}\u2500`)} ${p} ${a("\u2500".repeat(f)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let _=this.pendingConfirm.action;this.pendingConfirm=void 0,_()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,i=n?.rows??[],s=i.findIndex(_=>_.id===this.cursorId);s<0&&(s=Math.max(0,i.findIndex(_=>_.id===this.self)));let a=i[s],u=_=>_!==void 0&&!_.cycle,p=(_,m)=>{for(let b=_+m;b>=0&&b<i.length;b+=m)if(u(i[b]))return b;return _},f=_=>{let m=_===1?0:i.length-1;for(let b=m;b>=0&&b<i.length;b+=_)if(u(i[b]))return b;return s};if(this.matches("crtr.graph.down",e)){s=p(s,1),this.cursorId=i[s]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){s=p(s,-1),this.cursorId=i[s]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=i[f(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=i[f(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(a!==void 0&&a.hasKids&&!a.collapsed)this.userCollapsed.add(a.id),this.userExpanded.delete(a.id),this.repaintFolds();else{let _=n?.managerOf.get(this.cursorId??this.self);_!==void 0&&i.some(m=>m.id===_)&&(this.cursorId=_),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(a!==void 0&&a.collapsed&&a.hasKids)this.userExpanded.add(a.id),this.userCollapsed.delete(a.id),this.repaintFolds();else if(a!==void 0&&a.hasKids){let _=n?.sortedChildIds.get(a.id)?.[0];_!==void 0&&(this.cursorId=_),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let _=this.cursorId,m=_===void 0?null:n?.nodes.get(_)??null;_!==void 0&&m!==null&&m.status!=="active"&&m.status!=="idle"&&(this.reviveTarget(_),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let _=n?.managerOf.get(this.self);_!==void 0&&(this.focusTarget(_),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let _=this.cursorId??this.self,m=n?.nodes.get(_)??null,b=m!==null?w8t(m):$He(_);this.pendingConfirm={label:`kill ${b}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",_])},this.tui.requestRender();return}}focusTarget(e){let n=["surface","node","focus",e],i=process.env.TMUX_PANE;i!==void 0&&i!==""&&n.push("--pane",i),this.shellCrtr(n)}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{NEs("crtr",e,s=>{s==null&&n?.()}).stdin?.end()}catch{}}};var $Es=.72,UEs={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},VJe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let i=n-4,s=this.body(i),a=Math.max(1,this.tui.terminal.rows),u=Math.max(3,Math.min(Math.floor(a*$Es),Math.max(3,a-2))),p=Math.max(1,u-2),f=s.length>p,_=f&&p>=3?p-2:1;this.lastContentRows=_,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,s.length-_)));let m=Math.min(s.length,this.scrollTop+_),b=[];for(f&&p>=3&&b.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),b.push(...s.slice(this.scrollTop,m)),f&&p>=3?b.push(m<s.length?this.pal.muted(`\u2193 ${s.length-m} more`):""):f&&p===2&&b.push(m<s.length?this.pal.muted(`\u2193 ${s.length-m} more`):"");b.length<p;)b.push("");let x=this.pal.bold(this.pal.accent("\u2328 attach help")),k=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",x,n),...b.map(I=>this.boxRow(I,n)),this.borderRow("\u2570","\u256F",k,n)].map(this.pal.surface)}handleInput(e){return za(e,"escape")||za(e,"q")?(this.close(),!0):za(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):za(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):za(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):za(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,UEs)}matchesBinding(e,n){return this.bindings!==void 0&&vH(this.bindings,e,n,(i,s)=>za(i,s))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,i=Math.max(0,n-this.lastContentRows),s=Math.max(0,Math.min(i,this.scrollTop+e));return s!==this.scrollTop&&(this.scrollTop=s,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(i=>this.style(i,n.style)))}lines(){let e=(u,p)=>({text:`${this.binding(u)} ${p}`,style:"plain"}),n=u=>({text:u,style:"heading"}),i=u=>({text:u,style:"muted"}),s={text:"",style:"plain"},a=qB.map(({actionId:u})=>{let p=GP.find(f=>f.id===u)?.name??u;return e(u,p)});return[n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),i("mouse wheel (when reporting is on)"),s,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},s,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},s,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},s,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},s,n("Other attach keys"),...a]}binding(e){return this.bindings===void 0?"Loading\u2026":qS(this.bindings,e)}wrap(e,n){if(e==="")return[""];let i=Math.max(1,n),s=e.split(/\s+/),a=[],u="";for(let p of s){let f=u===""?p:`${u} ${p}`;u!==""&&Vs(f)>i?(a.push(Ha(u,i,"",!0)),u=` ${p}`):u=f}return u!==""&&a.push(Ha(u,i,"",!0)),a}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let i=n-4,s=Ha(e,i,"",!0),a=" ".repeat(Math.max(0,i-Vs(s)));return`${this.pal.border("\u2502")} ${s}${a} ${this.pal.border("\u2502")}`}borderRow(e,n,i,s){if(s<6)return Ha(`${this.pal.border(e)}${i}${this.pal.border(n)}`,s,"",!0);let a=s-5,u=Ha(i,a,"\u2026"),p=Math.max(0,s-5-Vs(u));return`${this.pal.border(`${e}\u2500`)} ${u} ${this.pal.border("\u2500".repeat(p)+n)}`}renderNarrow(e){let n=Ha(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};import{join as jEs}from"node:path";function Ade(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");GBe(jEs(Hw(),"attach-invariants.log"),n)}var zJe=class{constructor(e,n,i){this.surface=e;this.focusTarget=n;this.getRows=i}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,X0e(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),i=Math.max(0,Math.floor(e));this.surface.setRows(n);let s=this.surface.render(i);s.length!==n&&l7t(`surface rendered ${s.length} rows; expected ${n}`);let a=s.slice(0,n).map(p=>Vs(p)>i?(l7t(`surface row is ${Vs(p)} cells wide; expected at most ${i}`),uhr(ry(p,0,i,!0),i)):uhr(p,i));for(;a.length<n;)a.push(" ".repeat(i));let u=WEs(a);return u>1?(l7t(`surface frame contains ${u} CURSOR_MARKER sequences; expected at most one`),a.map(QEs)):a}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function uhr(t,e){return Ha(t,e,"",!0)}function WEs(t){return t.reduce((e,n)=>e+n.split(Xh).length-1,0)}function QEs(t){return t.split(Xh).join("")}function l7t(t){Ade("surface-frame",t)}var qEs={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},GEs={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},JJe=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let i=new zJe(e,n?.focus??e,this.getRows),s=this.tui.showOverlay(i,qEs),a={component:e,frame:i,overlay:s,cleanup:[],closed:!1,closing:!1},u=this.stack[this.stack.length-1];return u&&u.overlay.setHidden(!0),this.stack.push(a),{close:()=>this.closeEntry(a,!0),invalidate:()=>{!a.closed&&this.stack[this.stack.length-1]===a&&this.tui.requestRender()},onClose:p=>{if(a.closed||a.closing){HJe("onClose registered after surface close");return}a.cleanup.push(p)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let i=new p7t(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(i,GEs),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=await Hm().getNode(e),i=await Zpr(e,{pane:this.selfPane,cwd:n.cwd,name:n.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(E3(n)),!1}}pickReviewFile(e){return new Promise(n=>{let i,s=!1,a=p=>{s||(s=!0,n(p),i.close())},u=gJe(e.candidates,e.cwd,p=>a(p),()=>a(null),p=>this.notice(p));i=this.mount(VEs(u.component,e.title),{focus:u.focus}),i.onClose(()=>a(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let a=this.stack.indexOf(e),u=this.stack[a+1];if(!u)break;this.closeEntry(u,!1)}try{e.overlay.hide()}catch(a){HJe(`surface overlay hide failed: ${u7t(a)}`)}for(let a of e.cleanup)try{let u=a();u&&typeof u.then=="function"&&u.catch(p=>HJe(`surface cleanup failed: ${u7t(p)}`))}catch(u){HJe(`surface cleanup failed: ${u7t(u)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let s=this.stack.indexOf(e);if(s!==-1&&this.stack.splice(s,1),n){this.disposeNotice();let a=this.stack[this.stack.length-1];a&&a.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},p7t=class{constructor(e){this.text=e}text;render(e){return[Ha(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function VEs(t,e){let n=0;return{setRows:i=>{n=Math.max(0,Math.floor(i))},render:i=>{let s=t.render(i),u=(e===void 0?s:[Ha(e,Math.max(0,i),"",!0),...s.slice(1)]).slice(0,n);for(;u.length<n;)u.push("");return u},invalidate:()=>t.invalidate()}}function HJe(t){Ade("surface-host",t)}function u7t(t){return t instanceof Error?t.message:String(t)}import{existsSync as dhr,statSync as n1s,watch as r1s}from"node:fs";import{basename as i1s}from"node:path";function zEs(t,e){switch(e){case"gray":return`${oze}${t}${Ps}`;case"cyan":return`${nv}${t}${Ps}`;case"red":return`${Bsr}${t}${Ps}`;case"yellow":return`${Kv}${t}${Ps}`;default:return t}}var HEs={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},JEs={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function KEs(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function phr(t,e,n,i=Number.MAX_SAFE_INTEGER){if(t.length===0)return[` ${ua}${Lsr}No pending interactions${Ps}`];let s=e-4,a=t.map((f,_)=>YEs(f,_,n,s)),u=XEs(a,n,Math.max(1,i-2)),p=[` ${Jv}${t.length} pending${Ps}`,""];u.start>0&&p.push(` ${ua}\u2191 ${u.start} above${Ps}`);for(let f=u.start;f<u.end;f++)p.push(...a[f]);return u.end<t.length&&p.push(` ${ua}\u2193 ${t.length-u.end} below${Ps}`),p}function YEs(t,e,n,i){let s=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,a=HEs[s]??"\xB7",u=KEs(t.kind==="page"?t.emittedAt:t.blockedSince),p=e===n?`${nv}\u25B8${Ps} `:" ",f=Math.max(1,i-u.length-6),_=`${p}${zEs(a,JEs[s]??"cyan")} ${Jv}${aze(t.title||`(${t.id.slice(0,8)})`,f)}${Ps} ${ua}${u}${Ps}`,m=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,b=[_,` ${ua}${aze(m,i-6)}${Ps}`],x=d7t(t);return x!==void 0&&b.push(` ${ua}Recommended: ${aze(x,Math.max(1,i-19))}${Ps}`),b}function d7t(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function XEs(t,e,n){let i=Math.max(0,Math.min(e,t.length-1)),s=i+1,a=!0;for(;;){let u=s<t.length?{start:i,end:s+1}:void 0,p=i>0?{start:i-1,end:s}:void 0,_=(a?[u,p]:[p,u]).find(m=>m!==void 0&&ZEs(t,m.start,m.end)<=n);if(_===void 0)break;i=_.start,s=_.end,a=!a}return{start:i,end:s}}function ZEs(t,e,n){let i=e>0?1:0;for(let s=e;s<n;s++)i+=t[s].length;return n<t.length&&i++,i}function f7t(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let i=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:i,detailWidth:t-i-1,height:e}}import{basename as e1s}from"node:path";var KJe=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote){this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host.");return}let e=e1s(this.opts.dir),n;try{n=await $X().byBridge(e)}catch(i){this.opts.host.notice(t1s(i));return}this.stopped||hJe(this.opts.host,n)}};function t1s(t){return t instanceof w3?pde(t):t instanceof Error?t.message:String(t)}var XJe=class{options;host;scan;items=[];selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??(()=>xq()),this.cols=e.cols??80,this.rows=e.rows??24,this.selectedDir=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}rescan(){let e=this.selectedDir,n=this.selectedIndex;this.items=this.scan();let i=e===void 0?-1:this.items.findIndex(s=>s.dir===e);if(i>=0){this.selectedIndex=i,this.selectedDir=e;return}if(this.adapter!==void 0&&e!==void 0){let s=o1s(e)?.kind==="canceled";s&&Y6t(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}if(this.items.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(n,this.items.length-1),this.selectedDir=this.items[this.selectedIndex].dir}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&JVe(this.claim.dir,this.claim.token)},1e4))}invalidate(){this.rescan(),this.markDirty()}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=f7t(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Kv}Resize terminal to at least 60\xD718 to use inbox.${Ps}`];let n=phr(this.items,e.listWidth,this.selectedIndex,e.height),i=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(i);let s=[],a=`${oze}\u2502${Ps}`;for(let u=0;u<e.height;u++){let p=rw(n[u]??"",e.listWidth),f=rw(i[u]??"",e.detailWidth),_=" ".repeat(Math.max(0,e.listWidth-Vs(p)));s.push(`${p}${_}${a}${f}`)}return this.withStatus(s)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let i=this.cancelConfirmation.dir;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(i)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="x"||e==="X"){let i=this.items[this.selectedIndex];i!==void 0&&(this.cancelConfirmation={dir:i.dir,title:i.title},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}async sendFastAction(){let e=this.items[this.selectedIndex];if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=$1e(e.dir);if(n===null){let s=B1e(e.dir);this.status=s?YJe(e.dir):"ticket is being edited by another inbox",s&&this.rescan();return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${d7t(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await iTe(e.dir,e.fastAction.responses),this.status=i}catch(s){this.status=sTe(s)==="already_resolved"?YJe(e.dir):E3(s)}finally{yX(e.dir,n.token),this.submittingDir=void 0,this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e;try{await Mmr(e,{reason:"Canceled from the inbox.",actor:"human",disposition:"dismissed"}),this.status="canceled"}catch(n){this.status=E3(n)}finally{this.submittingDir=void 0,this.rescan(),this.markDirty()}}activate(){let e=this.items[this.selectedIndex];if(e===void 0)return;if(e.kind==="review"){this.activateReview(e);return}if(e.kind!=="page")return;let n=$1e(e.dir);if(n===null){let a=B1e(e.dir);this.status=a?YJe(e.dir):"ticket is being edited by another inbox",a&&this.rescan();return}this.claim={dir:e.dir,token:n.token};let i;try{i=bX(e.dir)}catch{yX(e.dir,n.token),this.claim=void 0,this.status="page could not be read",this.invalidate();return}let s=c4e();this.screen="detail",this.adapter=new _de({dir:e.dir,ticket:i,productKinds:s,cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:a=>{this.complete(a)}}),this.watchSelected(e.dir)}async activateReview(e){this.reviewAdapter=new KJe({dir:e.dir,host:this.host});try{await this.reviewAdapter.start()}catch(n){this.status=E3(n)}finally{this.reviewAdapter=void 0,this.rescan(),this.markDirty()}}selectDir(e){let n=this.items.findIndex(i=>i.dir===e);n>=0&&(this.select(n),this.markDirty())}reloadSelectedPage(){if(this.adapter===void 0||this.claim===void 0){this.markDirty();return}try{this.adapter.reload(bX(this.claim.dir))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await iTe(n.dir,e)}catch(s){this.submittingDir=void 0,this.status=E3(s);let a=sTe(s);if(a==="unreachable"||a==="other"){this.markDirty();return}a==="already_resolved"&&(this.status=YJe(n.dir)),this.leaveDetail(!1),this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),this.rescan();let i=this.items.some(s=>s.dir===n.dir);DR({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:i1s(n.dir),response_published:dhr(b3(n.dir)),still_listed:i,claim_left_behind:dhr(TN(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),i={text:e};try{i=WJe(e)}finally{n(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&yX(this.claim.dir,this.claim.token),this.claim=void 0,this.screen="list"}select(e){this.items.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.items.length-1)),this.selectedDir=this.items[this.selectedIndex].dir)}detailSize(){let e=f7t(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let i=this.items[this.selectedIndex];if(i===void 0)return this.passiveDetailLines(e,n);let s=this.focusAvailable(i.dir)?` ${ua}g${Ps} chat`:"",a=i.kind==="page"&&i.fastAction!==void 0?` ${ua}s${Ps} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",u=i.kind==="page"?[` ${ua}Enter${Ps} opens the full page ${ua}j/k${Ps} select${a} ${ua}x${Ps} cancel`,` ${ua}Page:${Ps} c comment u/d scroll${s} ${ua}q${Ps} close`]:[` ${ua}Enter${Ps} opens the full review ${ua}j/k${Ps} select ${ua}x${Ps} cancel`,` ${s} ${ua}q${Ps} close`],p=Math.max(0,n-u.length),f=this.passiveDetailLines(e,p);for(;f.length<p;)f.push("");return[...f,...u.map(_=>rw(_,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.items[this.selectedIndex];if(!(e===void 0||this.focusingSource)){this.focusingSource=!0;try{await this.host.focusNode(jJe(e.dir))?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}}pagePreviewBody(e,n){let i;try{i=String(n1s(F8(e.dir,e.dialect)).mtimeMs)}catch{i="missing"}let s=this.preview;if(s!==void 0&&s.dir===e.dir&&s.width===n&&s.stamp===i)return s.lines;let a=[];try{let u=bX(e.dir),p=u.manifest.dialect==="html"?Bpe(u.document):Lpe(u.document,u.manifest);a=lze(u.manifest,p,Math.min(Math.max(20,n-4),100),Math.max(20,n-4))}catch{}return this.preview={dir:e.dir,width:n,stamp:i,lines:a},a}passiveDetailLines(e,n){let i=this.items[this.selectedIndex];if(i===void 0)return[` ${ua}Select a pending interaction.${Ps}`];let s=[` ${Jv}${nv}${i.title}${Ps}`,""];for(let u of nze(i.subtitle,Math.max(1,e-2)))s.push(` ${u}`);let a=i.kind==="page"?this.pagePreviewBody(i,e):[`${ua}1 file to review${Ps}`];if(a.length>0){s.push("");let u=Math.max(0,n-s.length),p=a.length<=u?a:a.slice(0,Math.max(0,u-1));for(let f of p)s.push(` ${f}`);p.length<a.length&&s.push(` ${ua}\u2026 +${a.length-p.length} more lines${Ps}`)}return s.map(u=>rw(u,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.status:`cancel \u201C${this.cancelConfirmation.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let i=[...e];for(;i.length<this.rows;)i.push("");return i[this.rows-1]=`${Kv}${n}${Ps}`,i}markDirty(){this.options.onDirty()}watchRoots(){let e=VVe(this.options.onInboxActivity??(()=>this.invalidate()));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=r1s(e,(n,i)=>{if(i==="page.json"){this.reloadSelectedPage();return}this.invalidate()})}catch{this.selectedWatcher=void 0}}};function s1s(t){return t===null?"ticket was already resolved":t.kind==="review"?`ticket was already resolved: ${t.result.approved?"approved":"review submitted"}`:t.kind==="page"?"ticket was already resolved: page submitted":"ticket was already canceled"}function o1s(t){try{return vF(t)}catch{return null}}function YJe(t){try{return s1s(vF(t))}catch(e){return`ticket result is unreadable: ${e instanceof Error?e.message:String(e)}`}}import{createHash as a1s}from"node:crypto";import{realpathSync as c1s}from"node:fs";import{basename as l1s}from"node:path";function u1s(t,e){return a1s("sha256").update(`${t}\0${e}`,"utf8").digest("hex")}function fhr(t,e){let n;try{n=c1s(_X())}catch{return t.filter(i=>i.kind!=="review")}return t.filter(i=>i.kind!=="review"||e.has(u1s(n,l1s(i.dir))))}var m7t=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),p1s(this.controller.render(),e,n)}handleInput(e){let{input:n,key:i}=UJe(e);this.controller.handleKey(n,i)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function p1s(t,e,n){let i=t.slice(0,n);for(;i.length<n;)i.push("");return i.map(s=>{let a=rw(s,e);return a+" ".repeat(Math.max(0,e-yA(a)))})}function mhr(t){let e,n=()=>{let p=e;p===void 0||p.closed||(p.closed=!0,e=void 0,p.controller?.close(),p.handle?.close(),p.controller=void 0,p.handle=void 0)},i=p=>{if(p.closed||e!==p)return;let f=t.scan??xq,_=new XJe({host:t.host,onDirty:()=>p.handle?.invalidate(),onClosed:n,scan:()=>fhr(f(),p.visibleIds),onInboxActivity:()=>s(p),...p.preselectDir===void 0?{}:{initialSelection:p.preselectDir}}),m=new m7t(_);p.controller=_;try{let b=t.host.mount(m);p.handle=b,m.setHandle(b),b.onClose(()=>{p.handle===b&&(p.handle=void 0),_.close()}),_.start()}catch(b){throw n(),b}},s=(p,f=!1)=>{let _=++p.refreshGeneration;Hm().listHumanInbox().then(({tickets:m})=>{p.closed||e!==p||_!==p.refreshGeneration||(p.visibleIds=new Set(m.map(b=>b.ticket_id)),p.controller===void 0?i(p):p.controller.invalidate())},m=>{!f||p.closed||e!==p||_!==p.refreshGeneration||(n(),t.host.notice(`Could not load inbox visibility: ${m instanceof Error?m.message:String(m)}`))})},a=p=>{if(e!==void 0){p!==void 0&&e.controller?.selectDir(p);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let f={closed:!1,refreshGeneration:0,visibleIds:new Set,...p===void 0?{}:{preselectDir:p}};e=f,s(f,!0)};return{toggle:()=>{if(e!==void 0){n();return}a()},open:a,close:n,isOpen:()=>e!==void 0}}import{homedir as A1s}from"node:os";import{fileURLToPath as h1s}from"node:url";import{join as _hr,dirname as g1s}from"node:path";import{readFileSync as d1s}from"node:fs";import{dirname as f1s,join as hhr}from"node:path";import{fileURLToPath as m1s}from"node:url";var ZJe=null;function ghr(){if(ZJe!==null)return ZJe;let t=hhr(f1s(m1s(import.meta.url)),"..","..");return ZJe=JSON.parse(d1s(hhr(t,"package.json"),"utf8")).version,ZJe}var _1s=h1s(import.meta.url),y1s=g1s(_1s),b1s=_hr(y1s,"..",".."),QNc=_hr(b1s,"scripts","self-update.mjs");function yhr(){return ghr()}function bhr(t){let e;try{e=yhr()}catch{}let n;try{t.profile_id&&(n=Yj(t.profile_id).manifest.name)}catch{}let i=t.cwd;if(i){let s=A1s();i===s?i="~":i.startsWith(s+"/")&&(i="~"+i.slice(s.length))}return{version:e,profile:n,cwd:i}}import{createConnection as v1s}from"node:net";function Ahr(t,e){return t||e?"observer":"controller"}async function x1s(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=ube(t),i=Date.now()+e;for(;Date.now()<i;){if(await new Promise(a=>{let u=v1s(n),p=f=>{u.destroy(),a(f)};u.once("connect",()=>p(!0)),u.once("error",()=>p(!1))}))return;await new Promise(a=>setTimeout(a,100))}}async function vhr(t,e,n=!0){let i=e!==void 0,s=i?Jpr({canvasName:e}):new QCe,a,u,p,f,_;if(i)a={cwd:process.cwd()},p=new bde(t,iJe(e));else{let k=await s.getNode(t);if(k===null)throw new Zj({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});a=k,u=k;try{if((await Hm().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let C=await Hm().getSnapshot(t);f=C.snapshot,_=C.commands}}catch(I){sJe(I,"The node may be finalized or otherwise not attachable.")}f===void 0&&await x1s(t)}let m=new oTe(t,{transport:p}),b=k=>k instanceof C3?new Zj({error:"no_broker",message:k.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Zj({error:"socket_error",message:`could not attach to node ${t}: ${String(k?.message??k)}`,received:t,next:"Check the node has a running headless broker."}),x;return m.on("error",k=>{x===void 0&&(x=k)}),f===void 0&&await new Promise((k,I)=>{let C=()=>{R(),k()},D=F=>{R(),I(F)},R=()=>{m.off("connect",C),m.off("error",D)};m.on("connect",C),m.on("error",D),m.connect()}).catch(k=>{throw b(k)}),{remote:i,canvasSource:s,meta:a,nodeIdentity:u,socket:m,...f===void 0?{}:{initialSnapshot:f,initialCommands:_},assertConnected:()=>{if(f===void 0&&x!==void 0)throw b(x)}}}import{basename as sCs}from"node:path";import{statSync as O1s}from"node:fs";import{mkdirSync as w1s,readFileSync as S1s,writeFileSync as E1s}from"node:fs";import{dirname as C1s,join as T1s}from"node:path";var k1s="completion-frecency.json",I1s=336*60*60*1e3,P1s=8,D1s=1e3;function R1s(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),i=Math.pow(.5,n/I1s),s=1-Math.exp(-t.n/3);return P1s*i*s}function N1s(t){let e={};try{let n=JSON.parse(S1s(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[i,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let{n:a,t:u}=s;typeof a!="number"||!Number.isFinite(a)||a<=0||typeof u!="number"||!Number.isFinite(u)||(e[i]={n:a,t:u})}}catch{}return e}function M1s(t,e){try{w1s(C1s(t),{recursive:!0}),E1s(t,JSON.stringify(e),"utf8")}catch{}}function xhr(t=T1s(WB(),k1s)){let e=N1s(t),n,i=()=>{n||(n=setTimeout(()=>{n=void 0,M1s(t,e)},D1s),n.unref?.())};return{record:s=>{let a=e[s];e[s]={n:(a?.n??0)+1,t:Date.now()},i()},bonus:(s,a=Date.now())=>R1s(e[s],a)}}function h7t(t,e,n){let i=n.now??Date.now(),s=[];for(let a of t){let u=uie(e,n.searchableOf(a));u.matches&&s.push({item:a,score:u.score-n.store.bonus(n.idOf(a),i)})}return s.sort((a,u)=>a.score-u.score),s.map(a=>a.item)}function g7t(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function whr(t){return t.replace(/:/g,"")}function aTe(t,e,n){let i=t.join(`
2126
+ `).length;return{kind:"selection",notice:_===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${m} ${m===1?"line":"lines"}) \u2014 ${_}`}},clear(){let a=n!==void 0;return e=void 0,n=void 0,a},active(){return n!==void 0},apply(a){let u=i();if(!u)return a.slice();let p=t.width(),f=a.slice();for(let _ of ihr(u.anchor,u.head,p)){let m=_.row-1;m<0||m>=f.length||(f[m]=nur(f[m],_.from,_.to,p))}return f}}}import{existsSync as IEs}from"node:fs";var ohr="\x1B_crtr-file-open;",ahr="\x1B\\";function chr(t){let e=t.indexOf(ohr);if(e===-1)return;let n=e+ohr.length,i=t.indexOf(ahr,n);return i===-1?void 0:{file:PEs(t.slice(n,i)),remaining:t.slice(0,e)+t.slice(i+ahr.length)}}function PEs(t){let e=t.startsWith("'")?DEs(t):REs(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function DEs(t){let e="",n=1;for(;;){let i=t.indexOf("'",n);if(i===-1)return;if(e+=t.slice(n,i),n=i+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function REs(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let i=t[++n];if(i===void 0)return;e+=i}return e}function lhr(t){if(!IEs(t.file))return"missing";let e=`crtr surface attach to ${_d(t.nodeId)}${t.observer?" --observer":""}`,n=`nvim ${_d(t.file)} || :; exec ${e}`;return t.beforeRespawn(),r_t({pane:t.pane,cwd:t.cwd,env:Nbe(),command:n})?"opened":"failed"}import{execFile as NEs}from"node:child_process";function c7t(t){switch(t){case"active":return 0;case"idle":return 1;case"done":return 2;case"canceled":return 3;case"dead":return 4;default:return 5}}var MEs=.72,OEs={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},FEs=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],LEs=[["crtr.graph.dismiss","dismiss"]],BEs=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]],GJe=class{constructor(e,n,i,s,a,u,p="controller",f=()=>{},_=()=>{}){this.tui=e;this.self=n;this.getAsks=i;this.palette=s;this.bindings=a;this.source=u;this.role=p;this.onRefreshFailure=f;this.onNotice=_;this.remote=u instanceof V8}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;async fetchFocused(){if(this.remote)return new Set;try{return new Set((await Hm().listFocuses()).map(e=>e.node_id))}catch{return new Set}}setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return vH(this.bindings,e,n,(i,s)=>za(i,s))}hint(e){return e.flatMap(([n,i])=>this.bindings.gestures(n).length===0?[]:[`${qS(this.bindings,n)} ${i}`])}fitHints(e,n){let s=[],a=0;for(let u of this.hint(e)){let p=(s.length===0?0:3)+_I(u);if(a+p>n)break;s.push(u),a+=p}return s.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,OEs),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async buildSnapshot(){RCe();let[e,n]=await Promise.all([this.source.listNodes().catch(()=>[]),this.fetchFocused()]),i=new Map(e.map(R=>[R.node_id,R])),s=new Map,a=new Map,u=new Map,p=new Map,f=async R=>{let F=s.get(R);if(F!==void 0)return F;let L;try{L=await this.source.subscriptionsOf(R)}catch{L=[]}let U=L.map(Y=>Y.node_id).filter(Y=>i.get(Y)?.kind!=="human");return s.set(R,U),U},_=async R=>{if(u.has(R))return u.get(R);let F;try{F=(await this.source.subscribersOf(R))[0]?.node_id}catch{F=void 0}return u.set(R,F),F},m=async()=>{let R=this.self,F=new Set([R]);for(;;){let L=await _(R);if(L===void 0||F.has(L))break;F.add(L),R=L}return R},b=async R=>{let F=a.get(R);if(F!==void 0)return F;let L=[...await f(R)];return L.sort((U,Y)=>c7t(i.get(U)?.status)-c7t(i.get(Y)?.status)),a.set(R,L),L},x=new Set,k=new Set,I=async R=>{let F=i.get(R)?.status==="active";if(k.has(R))return{active:F?1:0,reveal:F||R===this.self};k.add(R);let L=0,U=!1;for(let Y of await f(R)){let V=await I(Y);L+=V.active,V.reveal&&(U=!0)}return p.set(R,L),U&&x.add(R),{active:L+(F?1:0),reveal:U||F||R===this.self}},C=await m();await I(C),await Promise.all([...s.keys()].map(R=>b(R)));let D={root:C,rows:[],autoExpanded:x,activeBelow:p,nodes:i,childIds:s,sortedChildIds:a,managerOf:u,focused:n};return D.rows=this.projectRows(D),D}projectRows(e){let n=[],i=new Set,s=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;s.length>0;){let{id:a,prefix:u,isRoot:p,isLast:f}=s.pop(),_=p?"":f?"\u2514\u2500 ":"\u251C\u2500 ";if(i.has(a)){n.push({id:a,hasKids:!1,isSelf:a===this.self,branch:u+_,cycle:!0,collapsed:!1});continue}i.add(a);let m=e.sortedChildIds.get(a)??[],b=this.folds.userExpanded.has(a)?!1:this.folds.userCollapsed.has(a)?!0:!e.autoExpanded.has(a);if(n.push({id:a,hasKids:m.length>0,isSelf:a===this.self,branch:u+_,cycle:!1,collapsed:b}),b)continue;let x=p?"":u+(f?" ":"\u2502 ");for(let k=m.length-1;k>=0;k--)s.push({id:m[k],prefix:x,isRoot:!1,isLast:k===m.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,i,s){let a=(Y,V)=>i?J8(Y,PF(),gq):V?J8(Y,PF(),Cur):H8(Y);if(n.cycle){let Y=`${n.branch} ${N1}\u21BA ${$He(n.id)}${rg}`;return a(Y,!1)}let u=e.nodes.get(n.id)??null,p=OHe(u,this.remote),f=OX(u,n.id),_=n.isSelf?`${PCe}${f}${rg}`:f,m=`${N1}${u?.kind??""}${rg}`,b=`${N1}${FHe(n.id,this.remote)}${rg}`,x=n.hasKids&&n.collapsed,k=!i&&x?`${N1}\u25B8${rg} `:" ",I=BHe(u),C=e.childIds.get(n.id)?.length??0,D=u!==null&&C>0?` ${N1}\u2933${C}${rg}`:"",R=u!==null&&u.status!=="active"&&(e.activeBelow.get(u.node_id)??0)>0?` ${MHe}\u21E3${e.activeBelow.get(u.node_id)??0}${rg}`:"",F=u!==null&&!this.remote?NHe(u,ICe(n.id)):null,L=F!==null?` \xB7 ${C8t(F)}`:"",U=`${n.branch}${k}${p} ${_} ${m} ${b}${I}${D}${R}${UHe(n.id,s)}${LHe(n.id,u,this.remote)}${L}`;return a(U,Iur(n.id,u,e.focused,this.remote))}render(e){RCe();let n=this.getAsks(),i=this.snapshot?.rows??[],s=i.findIndex(R=>R.id===this.cursorId);s<0&&(s=i.findIndex(R=>R.id===this.self),s<0&&(s=0)),this.cursorId=i[s]?.id??this.self;let a=process.stdout.rows??Eur,u=Math.max(3,Math.min(Math.floor(a*MEs),a-2)),p=Math.max(2,Math.min(i.length,u-2)),f=p;for(let R=0;R<4;R++){s<this.scrollTop&&(this.scrollTop=s),s>=this.scrollTop+f&&(this.scrollTop=s-f+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-f)));let F=p-(this.scrollTop>0?1:0)-(this.scrollTop+f<i.length?1:0);if(F===f)break;f=Math.max(1,F)}let _=Math.min(i.length,this.scrollTop+f),m=[];this.scrollTop>0&&m.push(`${N1} \u2191 ${this.scrollTop} more${rg}`);for(let R=this.scrollTop;R<_;R++){let F=this.snapshot;m.push(F!==void 0?this.renderSnapshotRow(F,i[R],R===s,n):"")}for(_<i.length&&m.push(`${N1} \u2193 ${i.length-_} more${rg}`);m.length<p;)m.push("");let b=i.length>0?`${PCe}\u2317 canvas graph${rg} ${N1}(${s+1}/${i.length})${rg}`:`${PCe}\u2317 canvas graph${rg} ${N1}(loading)${rg}`,x=this.pendingConfirm!==void 0?`${DCe}${this.pendingConfirm.label} ${PCe}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${rg}`:`${N1}${this.fitHints([...this.remote||this.role!=="controller"?LEs:FEs,...BEs],Math.max(1,e-5))}${rg}`,k=this.palette.border,I=Math.max(1,e-4),C=m.map(R=>`${k("\u2502")} ${Ha(R,I,"",!0)} ${k("\u2502")}`),D=this.palette.surface;return[this.borderRow("\u256D","\u256E",b,e),...C,this.borderRow("\u2570","\u256F",x,e)].map(D)}borderRow(e,n,i,s){let a=this.palette.border,u=Math.max(1,s-5),p=Ha(i,u,"\u2026"),f=Math.max(0,s-5-_I(p));return`${a(`${e}\u2500`)} ${p} ${a("\u2500".repeat(f)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let _=this.pendingConfirm.action;this.pendingConfirm=void 0,_()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,i=n?.rows??[],s=i.findIndex(_=>_.id===this.cursorId);s<0&&(s=Math.max(0,i.findIndex(_=>_.id===this.self)));let a=i[s],u=_=>_!==void 0&&!_.cycle,p=(_,m)=>{for(let b=_+m;b>=0&&b<i.length;b+=m)if(u(i[b]))return b;return _},f=_=>{let m=_===1?0:i.length-1;for(let b=m;b>=0&&b<i.length;b+=_)if(u(i[b]))return b;return s};if(this.matches("crtr.graph.down",e)){s=p(s,1),this.cursorId=i[s]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){s=p(s,-1),this.cursorId=i[s]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=i[f(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=i[f(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(a!==void 0&&a.hasKids&&!a.collapsed)this.userCollapsed.add(a.id),this.userExpanded.delete(a.id),this.repaintFolds();else{let _=n?.managerOf.get(this.cursorId??this.self);_!==void 0&&i.some(m=>m.id===_)&&(this.cursorId=_),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(a!==void 0&&a.collapsed&&a.hasKids)this.userExpanded.add(a.id),this.userCollapsed.delete(a.id),this.repaintFolds();else if(a!==void 0&&a.hasKids){let _=n?.sortedChildIds.get(a.id)?.[0];_!==void 0&&(this.cursorId=_),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}let _=this.cursorId,m=_===void 0?null:n?.nodes.get(_)??null;_!==void 0&&m!==null&&m.status!=="active"&&m.status!=="idle"&&(this.reviveTarget(_),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}let _=n?.managerOf.get(this.self);_!==void 0&&(this.focusTarget(_),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}let _=this.cursorId??this.self,m=n?.nodes.get(_)??null,b=m!==null?w8t(m):$He(_);this.pendingConfirm={label:`kill ${b}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",_])},this.tui.requestRender();return}}focusTarget(e){let n=["surface","node","focus",e],i=process.env.TMUX_PANE;i!==void 0&&i!==""&&n.push("--pane",i),this.shellCrtr(n)}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{NEs("crtr",e,s=>{s==null&&n?.()}).stdin?.end()}catch{}}};var $Es=.72,UEs={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},VJe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let i=n-4,s=this.body(i),a=Math.max(1,this.tui.terminal.rows),u=Math.max(3,Math.min(Math.floor(a*$Es),Math.max(3,a-2))),p=Math.max(1,u-2),f=s.length>p,_=f&&p>=3?p-2:1;this.lastContentRows=_,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,s.length-_)));let m=Math.min(s.length,this.scrollTop+_),b=[];for(f&&p>=3&&b.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),b.push(...s.slice(this.scrollTop,m)),f&&p>=3?b.push(m<s.length?this.pal.muted(`\u2193 ${s.length-m} more`):""):f&&p===2&&b.push(m<s.length?this.pal.muted(`\u2193 ${s.length-m} more`):"");b.length<p;)b.push("");let x=this.pal.bold(this.pal.accent("\u2328 attach help")),k=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",x,n),...b.map(I=>this.boxRow(I,n)),this.borderRow("\u2570","\u256F",k,n)].map(this.pal.surface)}handleInput(e){return za(e,"escape")||za(e,"q")?(this.close(),!0):za(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):za(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):za(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):za(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,UEs)}matchesBinding(e,n){return this.bindings!==void 0&&vH(this.bindings,e,n,(i,s)=>za(i,s))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,i=Math.max(0,n-this.lastContentRows),s=Math.max(0,Math.min(i,this.scrollTop+e));return s!==this.scrollTop&&(this.scrollTop=s,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(i=>this.style(i,n.style)))}lines(){let e=(u,p)=>({text:`${this.binding(u)} ${p}`,style:"plain"}),n=u=>({text:u,style:"heading"}),i=u=>({text:u,style:"muted"}),s={text:"",style:"plain"},a=qB.map(({actionId:u})=>{let p=GP.find(f=>f.id===u)?.name??u;return e(u,p)});return[n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),i("mouse wheel (when reporting is on)"),s,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},s,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},s,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},s,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},s,n("Other attach keys"),...a]}binding(e){return this.bindings===void 0?"Loading\u2026":qS(this.bindings,e)}wrap(e,n){if(e==="")return[""];let i=Math.max(1,n),s=e.split(/\s+/),a=[],u="";for(let p of s){let f=u===""?p:`${u} ${p}`;u!==""&&Vs(f)>i?(a.push(Ha(u,i,"",!0)),u=` ${p}`):u=f}return u!==""&&a.push(Ha(u,i,"",!0)),a}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let i=n-4,s=Ha(e,i,"",!0),a=" ".repeat(Math.max(0,i-Vs(s)));return`${this.pal.border("\u2502")} ${s}${a} ${this.pal.border("\u2502")}`}borderRow(e,n,i,s){if(s<6)return Ha(`${this.pal.border(e)}${i}${this.pal.border(n)}`,s,"",!0);let a=s-5,u=Ha(i,a,"\u2026"),p=Math.max(0,s-5-Vs(u));return`${this.pal.border(`${e}\u2500`)} ${u} ${this.pal.border("\u2500".repeat(p)+n)}`}renderNarrow(e){let n=Ha(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};import{join as jEs}from"node:path";function Ade(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");GBe(jEs(Hw(),"attach-invariants.log"),n)}var zJe=class{constructor(e,n,i){this.surface=e;this.focusTarget=n;this.getRows=i}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,X0e(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),i=Math.max(0,Math.floor(e));this.surface.setRows(n);let s=this.surface.render(i);s.length!==n&&l7t(`surface rendered ${s.length} rows; expected ${n}`);let a=s.slice(0,n).map(p=>Vs(p)>i?(l7t(`surface row is ${Vs(p)} cells wide; expected at most ${i}`),uhr(ry(p,0,i,!0),i)):uhr(p,i));for(;a.length<n;)a.push(" ".repeat(i));let u=WEs(a);return u>1?(l7t(`surface frame contains ${u} CURSOR_MARKER sequences; expected at most one`),a.map(QEs)):a}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function uhr(t,e){return Ha(t,e,"",!0)}function WEs(t){return t.reduce((e,n)=>e+n.split(Xh).length-1,0)}function QEs(t){return t.split(Xh).join("")}function l7t(t){Ade("surface-frame",t)}var qEs={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},GEs={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},JJe=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let i=new zJe(e,n?.focus??e,this.getRows),s=this.tui.showOverlay(i,qEs),a={component:e,frame:i,overlay:s,cleanup:[],closed:!1,closing:!1},u=this.stack[this.stack.length-1];return u&&u.overlay.setHidden(!0),this.stack.push(a),{close:()=>this.closeEntry(a,!0),invalidate:()=>{!a.closed&&this.stack[this.stack.length-1]===a&&this.tui.requestRender()},onClose:p=>{if(a.closed||a.closing){HJe("onClose registered after surface close");return}a.cleanup.push(p)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let i=new p7t(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(i,GEs),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=await Hm().getNode(e),i=await Zpr(e,{pane:this.selfPane,cwd:n.cwd,name:n.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(E3(n)),!1}}pickReviewFile(e){return new Promise(n=>{let i,s=!1,a=p=>{s||(s=!0,n(p),i.close())},u=gJe(e.candidates,e.cwd,p=>a(p),()=>a(null),p=>this.notice(p));i=this.mount(VEs(u.component,e.title),{focus:u.focus}),i.onClose(()=>a(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let a=this.stack.indexOf(e),u=this.stack[a+1];if(!u)break;this.closeEntry(u,!1)}try{e.overlay.hide()}catch(a){HJe(`surface overlay hide failed: ${u7t(a)}`)}for(let a of e.cleanup)try{let u=a();u&&typeof u.then=="function"&&u.catch(p=>HJe(`surface cleanup failed: ${u7t(p)}`))}catch(u){HJe(`surface cleanup failed: ${u7t(u)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let s=this.stack.indexOf(e);if(s!==-1&&this.stack.splice(s,1),n){this.disposeNotice();let a=this.stack[this.stack.length-1];a&&a.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},p7t=class{constructor(e){this.text=e}text;render(e){return[Ha(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function VEs(t,e){let n=0;return{setRows:i=>{n=Math.max(0,Math.floor(i))},render:i=>{let s=t.render(i),u=(e===void 0?s:[Ha(e,Math.max(0,i),"",!0),...s.slice(1)]).slice(0,n);for(;u.length<n;)u.push("");return u},invalidate:()=>t.invalidate()}}function HJe(t){Ade("surface-host",t)}function u7t(t){return t instanceof Error?t.message:String(t)}import{existsSync as dhr,statSync as n1s,watch as r1s}from"node:fs";import{basename as i1s}from"node:path";function zEs(t,e){switch(e){case"gray":return`${oze}${t}${Ps}`;case"cyan":return`${nv}${t}${Ps}`;case"red":return`${Bsr}${t}${Ps}`;case"yellow":return`${Kv}${t}${Ps}`;default:return t}}var HEs={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},JEs={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function KEs(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function phr(t,e,n,i=Number.MAX_SAFE_INTEGER){if(t.length===0)return[` ${ua}${Lsr}No pending interactions${Ps}`];let s=e-4,a=t.map((f,_)=>YEs(f,_,n,s)),u=XEs(a,n,Math.max(1,i-2)),p=[` ${Jv}${t.length} pending${Ps}`,""];u.start>0&&p.push(` ${ua}\u2191 ${u.start} above${Ps}`);for(let f=u.start;f<u.end;f++)p.push(...a[f]);return u.end<t.length&&p.push(` ${ua}\u2193 ${t.length-u.end} below${Ps}`),p}function YEs(t,e,n,i){let s=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,a=HEs[s]??"\xB7",u=KEs(t.kind==="page"?t.emittedAt:t.blockedSince),p=e===n?`${nv}\u25B8${Ps} `:" ",f=Math.max(1,i-u.length-6),_=`${p}${zEs(a,JEs[s]??"cyan")} ${Jv}${aze(t.title||`(${t.id.slice(0,8)})`,f)}${Ps} ${ua}${u}${Ps}`,m=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,b=[_,` ${ua}${aze(m,i-6)}${Ps}`],x=d7t(t);return x!==void 0&&b.push(` ${ua}Recommended: ${aze(x,Math.max(1,i-19))}${Ps}`),b}function d7t(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function XEs(t,e,n){let i=Math.max(0,Math.min(e,t.length-1)),s=i+1,a=!0;for(;;){let u=s<t.length?{start:i,end:s+1}:void 0,p=i>0?{start:i-1,end:s}:void 0,_=(a?[u,p]:[p,u]).find(m=>m!==void 0&&ZEs(t,m.start,m.end)<=n);if(_===void 0)break;i=_.start,s=_.end,a=!a}return{start:i,end:s}}function ZEs(t,e,n){let i=e>0?1:0;for(let s=e;s<n;s++)i+=t[s].length;return n<t.length&&i++,i}function f7t(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let i=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:i,detailWidth:t-i-1,height:e}}import{basename as e1s}from"node:path";var KJe=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote){this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host.");return}let e=e1s(this.opts.dir),n;try{n=await $X().byBridge(e)}catch(i){this.opts.host.notice(t1s(i));return}this.stopped||hJe(this.opts.host,n)}};function t1s(t){return t instanceof w3?pde(t):t instanceof Error?t.message:String(t)}var XJe=class{options;host;scan;items=[];selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??(()=>xq()),this.cols=e.cols??80,this.rows=e.rows??24,this.selectedDir=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}rescan(){let e=this.selectedDir,n=this.selectedIndex;this.items=this.scan();let i=e===void 0?-1:this.items.findIndex(s=>s.dir===e);if(i>=0){this.selectedIndex=i,this.selectedDir=e;return}if(this.adapter!==void 0&&e!==void 0){let s=o1s(e)?.kind==="canceled";s&&Y6t(e),e!==this.submittingDir&&(this.status=s?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}if(this.items.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(n,this.items.length-1),this.selectedDir=this.items[this.selectedIndex].dir}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&JVe(this.claim.dir,this.claim.token)},1e4))}invalidate(){this.rescan(),this.markDirty()}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=f7t(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Kv}Resize terminal to at least 60\xD718 to use inbox.${Ps}`];let n=phr(this.items,e.listWidth,this.selectedIndex,e.height),i=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(i);let s=[],a=`${oze}\u2502${Ps}`;for(let u=0;u<e.height;u++){let p=rw(n[u]??"",e.listWidth),f=rw(i[u]??"",e.detailWidth),_=" ".repeat(Math.max(0,e.listWidth-Vs(p)));s.push(`${p}${_}${a}${f}`)}return this.withStatus(s)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let i=this.cancelConfirmation.dir;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(i)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="x"||e==="X"){let i=this.items[this.selectedIndex];i!==void 0&&(this.cancelConfirmation={dir:i.dir,title:i.title},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}async sendFastAction(){let e=this.items[this.selectedIndex];if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=$1e(e.dir);if(n===null){let s=B1e(e.dir);this.status=s?YJe(e.dir):"ticket is being edited by another inbox",s&&this.rescan();return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${d7t(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await iTe(e.dir,e.fastAction.responses),this.status=i}catch(s){this.status=sTe(s)==="already_resolved"?YJe(e.dir):E3(s)}finally{yX(e.dir,n.token),this.submittingDir=void 0,this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e;try{await Mmr(e,{reason:"Canceled from the inbox.",actor:"human",disposition:"dismissed"}),this.status="canceled"}catch(n){this.status=E3(n)}finally{this.submittingDir=void 0,this.rescan(),this.markDirty()}}activate(){let e=this.items[this.selectedIndex];if(e===void 0)return;if(e.kind==="review"){this.activateReview(e);return}if(e.kind!=="page")return;let n=$1e(e.dir);if(n===null){let a=B1e(e.dir);this.status=a?YJe(e.dir):"ticket is being edited by another inbox",a&&this.rescan();return}this.claim={dir:e.dir,token:n.token};let i;try{i=bX(e.dir)}catch{yX(e.dir,n.token),this.claim=void 0,this.status="page could not be read",this.invalidate();return}let s=c4e();this.screen="detail",this.adapter=new _de({dir:e.dir,ticket:i,productKinds:s,cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:a=>{this.complete(a)}}),this.watchSelected(e.dir)}async activateReview(e){this.reviewAdapter=new KJe({dir:e.dir,host:this.host});try{await this.reviewAdapter.start()}catch(n){this.status=E3(n)}finally{this.reviewAdapter=void 0,this.rescan(),this.markDirty()}}selectDir(e){let n=this.items.findIndex(i=>i.dir===e);n>=0&&(this.select(n),this.markDirty())}reloadSelectedPage(){if(this.adapter===void 0||this.claim===void 0){this.markDirty();return}try{this.adapter.reload(bX(this.claim.dir))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await iTe(n.dir,e)}catch(s){this.submittingDir=void 0,this.status=E3(s);let a=sTe(s);if(a==="unreachable"||a==="other"){this.markDirty();return}a==="already_resolved"&&(this.status=YJe(n.dir)),this.leaveDetail(!1),this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),this.rescan();let i=this.items.some(s=>s.dir===n.dir);DR({level:i?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:i1s(n.dir),response_published:dhr(b3(n.dir)),still_listed:i,claim_left_behind:dhr(TN(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),i={text:e};try{i=WJe(e)}finally{n(),this.adapter?.setInputBuffer(i.text),i.error!==void 0&&(this.status=i.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&yX(this.claim.dir,this.claim.token),this.claim=void 0,this.screen="list"}select(e){this.items.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.items.length-1)),this.selectedDir=this.items[this.selectedIndex].dir)}detailSize(){let e=f7t(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let i=this.items[this.selectedIndex];if(i===void 0)return this.passiveDetailLines(e,n);let s=this.focusAvailable(i.dir)?` ${ua}g${Ps} chat`:"",a=i.kind==="page"&&i.fastAction!==void 0?` ${ua}s${Ps} ${i.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",u=i.kind==="page"?[` ${ua}Enter${Ps} opens the full page ${ua}j/k${Ps} select${a} ${ua}x${Ps} cancel`,` ${ua}Page:${Ps} c comment u/d scroll${s} ${ua}q${Ps} close`]:[` ${ua}Enter${Ps} opens the full review ${ua}j/k${Ps} select ${ua}x${Ps} cancel`,` ${s} ${ua}q${Ps} close`],p=Math.max(0,n-u.length),f=this.passiveDetailLines(e,p);for(;f.length<p;)f.push("");return[...f,...u.map(_=>rw(_,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.items[this.selectedIndex];if(!(e===void 0||this.focusingSource)){this.focusingSource=!0;try{await this.host.focusNode(jJe(e.dir))?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}}pagePreviewBody(e,n){let i;try{i=String(n1s(F8(e.dir,e.dialect)).mtimeMs)}catch{i="missing"}let s=this.preview;if(s!==void 0&&s.dir===e.dir&&s.width===n&&s.stamp===i)return s.lines;let a=[];try{let u=bX(e.dir),p=u.manifest.dialect==="html"?Bpe(u.document):Lpe(u.document,u.manifest);a=lze(u.manifest,p,Math.min(Math.max(20,n-4),100),Math.max(20,n-4))}catch{}return this.preview={dir:e.dir,width:n,stamp:i,lines:a},a}passiveDetailLines(e,n){let i=this.items[this.selectedIndex];if(i===void 0)return[` ${ua}Select a pending interaction.${Ps}`];let s=[` ${Jv}${nv}${i.title}${Ps}`,""];for(let u of nze(i.subtitle,Math.max(1,e-2)))s.push(` ${u}`);let a=i.kind==="page"?this.pagePreviewBody(i,e):[`${ua}1 file to review${Ps}`];if(a.length>0){s.push("");let u=Math.max(0,n-s.length),p=a.length<=u?a:a.slice(0,Math.max(0,u-1));for(let f of p)s.push(` ${f}`);p.length<a.length&&s.push(` ${ua}\u2026 +${a.length-p.length} more lines${Ps}`)}return s.map(u=>rw(u,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.status:`cancel \u201C${this.cancelConfirmation.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let i=[...e];for(;i.length<this.rows;)i.push("");return i[this.rows-1]=`${Kv}${n}${Ps}`,i}markDirty(){this.options.onDirty()}watchRoots(){let e=VVe(this.options.onInboxActivity??(()=>this.invalidate()));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=r1s(e,(n,i)=>{if(i==="page.json"){this.reloadSelectedPage();return}this.invalidate()})}catch{this.selectedWatcher=void 0}}};function s1s(t){return t===null?"ticket was already resolved":t.kind==="review"?`ticket was already resolved: ${t.result.approved?"approved":"review submitted"}`:t.kind==="page"?"ticket was already resolved: page submitted":"ticket was already canceled"}function o1s(t){try{return vF(t)}catch{return null}}function YJe(t){try{return s1s(vF(t))}catch(e){return`ticket result is unreadable: ${e instanceof Error?e.message:String(e)}`}}import{createHash as a1s}from"node:crypto";import{realpathSync as c1s}from"node:fs";import{basename as l1s}from"node:path";function u1s(t,e){return a1s("sha256").update(`${t}\0${e}`,"utf8").digest("hex")}function fhr(t,e){let n;try{n=c1s(_X())}catch{return t.filter(i=>i.kind!=="review")}return t.filter(i=>i.kind!=="review"||e.has(u1s(n,l1s(i.dir))))}var m7t=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),p1s(this.controller.render(),e,n)}handleInput(e){let{input:n,key:i}=UJe(e);this.controller.handleKey(n,i)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function p1s(t,e,n){let i=t.slice(0,n);for(;i.length<n;)i.push("");return i.map(s=>{let a=rw(s,e);return a+" ".repeat(Math.max(0,e-yA(a)))})}function mhr(t){let e,n=()=>{let p=e;p===void 0||p.closed||(p.closed=!0,e=void 0,p.controller?.close(),p.handle?.close(),p.controller=void 0,p.handle=void 0)},i=p=>{if(p.closed||e!==p)return;let f=t.scan??xq,_=new XJe({host:t.host,onDirty:()=>p.handle?.invalidate(),onClosed:n,scan:()=>fhr(f(),p.visibleIds),onInboxActivity:()=>s(p),...p.preselectDir===void 0?{}:{initialSelection:p.preselectDir}}),m=new m7t(_);p.controller=_;try{let b=t.host.mount(m);p.handle=b,m.setHandle(b),b.onClose(()=>{p.handle===b&&(p.handle=void 0),_.close()}),_.start()}catch(b){throw n(),b}},s=(p,f=!1)=>{let _=++p.refreshGeneration;Hm().listHumanInbox().then(({tickets:m})=>{p.closed||e!==p||_!==p.refreshGeneration||(p.visibleIds=new Set(m.map(b=>b.ticket_id)),p.controller===void 0?i(p):p.controller.invalidate())},m=>{!f||p.closed||e!==p||_!==p.refreshGeneration||(n(),t.host.notice(`Could not load inbox visibility: ${m instanceof Error?m.message:String(m)}`))})},a=p=>{if(e!==void 0){p!==void 0&&e.controller?.selectDir(p);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let f={closed:!1,refreshGeneration:0,visibleIds:new Set,...p===void 0?{}:{preselectDir:p}};e=f,s(f,!0)};return{toggle:()=>{if(e!==void 0){n();return}a()},open:a,close:n,isOpen:()=>e!==void 0}}import{homedir as A1s}from"node:os";import{fileURLToPath as h1s}from"node:url";import{join as _hr,dirname as g1s}from"node:path";import{readFileSync as d1s}from"node:fs";import{dirname as f1s,join as hhr}from"node:path";import{fileURLToPath as m1s}from"node:url";var ZJe=null;function ghr(){if(ZJe!==null)return ZJe;let t=hhr(f1s(m1s(import.meta.url)),"..","..");return ZJe=JSON.parse(d1s(hhr(t,"package.json"),"utf8")).version,ZJe}var _1s=h1s(import.meta.url),y1s=g1s(_1s),b1s=_hr(y1s,"..",".."),VNc=_hr(b1s,"scripts","self-update.mjs");function yhr(){return ghr()}function bhr(t){let e;try{e=yhr()}catch{}let n;try{t.profile_id&&(n=Yj(t.profile_id).manifest.name)}catch{}let i=t.cwd;if(i){let s=A1s();i===s?i="~":i.startsWith(s+"/")&&(i="~"+i.slice(s.length))}return{version:e,profile:n,cwd:i}}import{createConnection as v1s}from"node:net";function Ahr(t,e){return t||e?"observer":"controller"}async function x1s(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=ube(t),i=Date.now()+e;for(;Date.now()<i;){if(await new Promise(a=>{let u=v1s(n),p=f=>{u.destroy(),a(f)};u.once("connect",()=>p(!0)),u.once("error",()=>p(!1))}))return;await new Promise(a=>setTimeout(a,100))}}async function vhr(t,e,n=!0){let i=e!==void 0,s=i?Jpr({canvasName:e}):new QCe,a,u,p,f,_;if(i)a={cwd:process.cwd()},p=new bde(t,iJe(e));else{let k=await s.getNode(t);if(k===null)throw new Zj({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});a=k,u=k;try{if((await Hm().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let C=await Hm().getSnapshot(t);f=C.snapshot,_=C.commands}}catch(I){sJe(I,"The node may be finalized or otherwise not attachable.")}f===void 0&&await x1s(t)}let m=new oTe(t,{transport:p}),b=k=>k instanceof C3?new Zj({error:"no_broker",message:k.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Zj({error:"socket_error",message:`could not attach to node ${t}: ${String(k?.message??k)}`,received:t,next:"Check the node has a running headless broker."}),x;return m.on("error",k=>{x===void 0&&(x=k)}),f===void 0&&await new Promise((k,I)=>{let C=()=>{R(),k()},D=F=>{R(),I(F)},R=()=>{m.off("connect",C),m.off("error",D)};m.on("connect",C),m.on("error",D),m.connect()}).catch(k=>{throw b(k)}),{remote:i,canvasSource:s,meta:a,nodeIdentity:u,socket:m,...f===void 0?{}:{initialSnapshot:f,initialCommands:_},assertConnected:()=>{if(f===void 0&&x!==void 0)throw b(x)}}}import{basename as sCs}from"node:path";import{statSync as O1s}from"node:fs";import{mkdirSync as w1s,readFileSync as S1s,writeFileSync as E1s}from"node:fs";import{dirname as C1s,join as T1s}from"node:path";var k1s="completion-frecency.json",I1s=336*60*60*1e3,P1s=8,D1s=1e3;function R1s(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),i=Math.pow(.5,n/I1s),s=1-Math.exp(-t.n/3);return P1s*i*s}function N1s(t){let e={};try{let n=JSON.parse(S1s(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[i,s]of Object.entries(n)){if(!s||typeof s!="object")continue;let{n:a,t:u}=s;typeof a!="number"||!Number.isFinite(a)||a<=0||typeof u!="number"||!Number.isFinite(u)||(e[i]={n:a,t:u})}}catch{}return e}function M1s(t,e){try{w1s(C1s(t),{recursive:!0}),E1s(t,JSON.stringify(e),"utf8")}catch{}}function xhr(t=T1s(WB(),k1s)){let e=N1s(t),n,i=()=>{n||(n=setTimeout(()=>{n=void 0,M1s(t,e)},D1s),n.unref?.())};return{record:s=>{let a=e[s];e[s]={n:(a?.n??0)+1,t:Date.now()},i()},bonus:(s,a=Date.now())=>R1s(e[s],a)}}function h7t(t,e,n){let i=n.now??Date.now(),s=[];for(let a of t){let u=uie(e,n.searchableOf(a));u.matches&&s.push({item:a,score:u.score-n.store.bonus(n.idOf(a),i)})}return s.sort((a,u)=>a.score-u.score),s.map(a=>a.item)}function g7t(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function whr(t){return t.replace(/:/g,"")}function aTe(t,e,n){let i=t.join(`
2127
2127
  `),s=0;for(let m=0;m<e&&m<t.length;m++)s+=t[m].length+1;let a=s+n,u=qur(i,a);if(!u)return null;let p=u.start-s,f=u.end-s;return{kind:u.start===0?"leading":"ref",startCol:p,endCol:f,prefix:u.surfacePrefix}}var eKe=class{refs;refNames;delegate;frecency;constructor(e,n,i){this.refs=e,this.refNames=new Set(e.map(s=>s.name)),this.delegate=n,this.frecency=i}get triggerCharacters(){return this.delegate.triggerCharacters}async getSuggestions(e,n,i,s){let a=aTe(e,n,i);if(!a)return this.delegate.getSuggestions(e,n,i,s);if(a.kind==="leading"){if(s.force)return this.delegate.getSuggestions(e,n,i,s);let f=(e[n]??"").slice(0,i),_=await this.delegate.getSuggestions(["/"],0,1,s);if(!_)return null;let m=h7t(_.items,f.slice(1),{searchableOf:b=>g7t(b.value),idOf:b=>`command:${b.value}`,store:this.frecency});return m.length===0?null:{items:m,prefix:f}}let u=h7t(this.refs,whr(a.prefix.slice(1)),{searchableOf:f=>g7t(f.name),idOf:f=>`ref:${f.name}`,store:this.frecency});return u.length===0?null:{items:u.map(f=>({value:f.name,label:M8t(f.name),description:f.shortForm||void 0})),prefix:a.prefix.slice(1)}}applyCompletion(e,n,i,s,a){let u=aTe(e,n,i);if(u&&u.kind==="ref"&&this.refNames.has(s.value)){let p=M8t(s.value),f=e[n]??"",_=f.slice(0,u.startCol)+p+f.slice(u.endCol),m=e.slice();return m[n]=_,{lines:m,cursorLine:n,cursorCol:u.startCol+p.length}}return this.delegate.applyCompletion(e,n,i,s,a)}shouldTriggerFileCompletion(e,n,i){let s=aTe(e,n,i);return s&&s.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,i):!1}};var _7t=8,F1s=24,L1s=8192;function B1s(t,e){let n=t.slice(0,e),i=t.length>e;return{text:n.replace(/\x1b\](?:[^\x07\x1b]*)(?:\x07|\x1b\\)?/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,""),truncated:i}}function $1s(t,e){if(e<F1s)return[];let n=Math.min(L1s,Math.max(256,e*_7t*4)),i=B1s(t,n),s=Ry(i.text,e);if(!i.truncated&&s.length<=_7t)return s;let a=s.slice(0,_7t-1);return a.push(Ha("\u2026 truncated \xB7 inspect for full prompt",e)),a}var cTe=[46,92,190],lTe=[166,98,24],U1s=[0,145,170];function uTe(t,e,n){return[Math.round(t[0]+(e[0]-t[0])*n),Math.round(t[1]+(e[1]-t[1])*n),Math.round(t[2]+(e[2]-t[2])*n)]}var Shr={off:void 0,minimal:uTe(cTe,lTe,0/4),low:uTe(cTe,lTe,1/4),medium:uTe(cTe,lTe,2/4),high:uTe(cTe,lTe,3/4),xhigh:uTe(cTe,lTe,4/4),max:U1s},j1s={black:[0,0,0],red:[205,49,49],green:[13,188,121],yellow:[229,229,16],blue:[36,114,200],magenta:[188,63,188],cyan:[17,168,205],white:[229,229,229],orange:[228,152,68],grey:[128,128,128],gray:[128,128,128],brightred:[241,76,76],brightgreen:[35,209,139],brightyellow:[245,245,67],brightblue:[59,142,234],brightmagenta:[214,112,214],brightcyan:[41,184,219]};function Ehr(t){let e=t.trim().toLowerCase(),n=/^colour(\d{1,3})$/.exec(e);if(n!==null)return m=>`\x1B[48;5;${n[1]}m\x1B[97m\x1B[1m ${m} \x1B[0m`;let i,s=/^#([0-9a-f]{6})$/.exec(e);if(s!==null){let m=s[1];i=[parseInt(m.slice(0,2),16),parseInt(m.slice(2,4),16),parseInt(m.slice(4,6),16)]}else i=j1s[e];if(i===void 0)return;let[a,u,p]=i,_=.299*a+.587*u+.114*p>160?"\x1B[30m":"\x1B[97m";return m=>`\x1B[48;2;${a};${u};${p}m${_}\x1B[1m ${m} \x1B[0m`}var tKe=t=>`\x1B[7m ${t} \x1B[27m`;function Chr(t,e){let n=t===void 0?void 0:Shr[t];if(n===void 0)return e;let[i,s,a]=n;return u=>`\x1B[38;2;${i};${s};${a}m${u}\x1B[39m`}function Thr(t,e){let n=t===void 0?void 0:Shr[t];if(n===void 0)return e;let[i,s,a]=n;return u=>`\x1B[48;2;${i};${s};${a}m\x1B[97m\x1B[1m ${u} \x1B[0m`}function W1s(t,e,n,i,s){let a=e?i(Ha(e,Math.max(1,t-4),"\u2026")):"",u=Vs(a),p=t-u,f="";n&&p>4&&(f=Vs(n)<=p?n:Ha(n,p,"\u2026"));let _=Math.max(0,t-u-Vs(f));return a+s("\u2500".repeat(_))+f}var nKe="\x1B[7m",rKe="\x1B[0m",y7t="\x1B[48;5;240m";function Q1s(t){let e=t.indexOf(Xh);if(e===-1)return;let n=e+Xh.length;if(!t.startsWith(nKe,n))return;let i=n+nKe.length,s=t.indexOf(rKe,i);if(s===-1)return;let a=t.slice(i,s),u=`${y7t}${a}\x1B[0m`;return t.slice(0,n)+u+t.slice(s+rKe.length)}var q1s=/\.(png|jpe?g|gif|webp|bmp)$/i;function G1s(t){let e=t.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/),n=(e?e[1]:t).trim();if(n.length<2||/[\u0000-\u0008\u000e-\u001f]/.test(n))return null;(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1));let i=n.replace(/\\(.)/g,"$1");if(/\n/.test(i)||!q1s.test(i))return null;try{if(!O1s(i).isFile())return null}catch{return null}return i}function V1s(t,e,n,i){let s=[];if(t.length===0||t.length===1&&t[0]==="")return s.push({logicalLine:0,startIndex:0,endIndex:0,text:"",hasCursor:!0,cursorPos:0}),s;for(let a=0;a<t.length;a++){let u=t[a]??"",p=a===n;if(Vs(u)<=e){s.push({logicalLine:a,startIndex:0,endIndex:u.length,text:u,hasCursor:p,cursorPos:p?i:0});continue}let f=Z0e(u,e);for(let _=0;_<f.length;_++){let m=f[_];if(!m)continue;let b=_===f.length-1,x=!1,k=0;p&&(b?(x=i>=m.startIndex,k=i-m.startIndex):(x=i>=m.startIndex&&i<m.endIndex,x&&(k=i-m.startIndex,k>m.text.length&&(k=m.text.length)))),s.push({logicalLine:a,startIndex:m.startIndex,endIndex:m.endIndex,text:m.text,hasCursor:x,cursorPos:k})}}return s}function z1s(t,e){return qHe(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}var H1s="\x1B[4m\x1B[2m",J1s="\x1B[24m\x1B[22m",K1s=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Y1s(t){for(let e of K1s.segment(t))return e.segment.length;return 0}function X1s(t){let e=t.indexOf(Xh),n=e===-1?0:e+Xh.length,i=t.indexOf(nKe,n),s=nKe.length;if(i===-1&&(i=t.indexOf(y7t,n),s=y7t.length),i===-1)return null;let a=t.indexOf(rKe,i+s);return a===-1?null:{start:e!==-1?e:i,end:a+rKe.length}}function Z1s(t,e,n,i,s){let a=[];if(e.hasCursor){let p=X1s(t);if(p===null)return t;let f=e.text.slice(e.cursorPos),_=f.length===0?0:Y1s(f),m=e.cursorPos+_;for(let b of n){let x=b.start-e.startIndex,k=b.end-e.startIndex;if(k<=e.cursorPos){let I=s+x,C=s+k;C<=p.start&&t.slice(I,C)===i.slice(b.start,b.end)&&a.push({absStart:I,absEnd:C})}else if(x>=m){let I=p.end+(x-m),C=p.end+(k-m);I>=p.end&&t.slice(I,C)===i.slice(b.start,b.end)&&a.push({absStart:I,absEnd:C})}}}else for(let p of n){let f=s+(p.start-e.startIndex),_=s+(p.end-e.startIndex);t.slice(f,_)===i.slice(p.start,p.end)&&a.push({absStart:f,absEnd:_})}if(a.length===0)return t;a.sort((p,f)=>f.absStart-p.absStart);let u=t;for(let p of a)u=u.slice(0,p.absStart)+H1s+u.slice(p.absStart,p.absEnd)+J1s+u.slice(p.absEnd);return u}function eCs(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function tCs(t,e){if(!t.startsWith("/"))return!1;let n=t.indexOf(" "),i=n===-1?t.slice(1):t.slice(1,n);if(e.has(i))return!0;if(t.startsWith("/skill:")){let s=n===-1?t.slice(7):t.slice(7,n);if(e.has(`skill:${s}`))return!0}return!1}var iKe=class t extends KY{km;pendingRawSubmitText;realOnSubmit;pendingReturn;static PASTE_BURST_MS=10;constructor(e,n,i,s){super(e,n,i,s),this.km=i;let a=this.submitValue.bind(this);this.submitValue=()=>{let u=this;this.pendingRawSubmitText=u.getExpandedText(),a()},Object.defineProperty(this,"onSubmit",{configurable:!0,get:()=>u=>{let p=this.pendingRawSubmitText??u;this.pendingRawSubmitText=void 0,this.realOnSubmit?.(p)},set:u=>{this.realOnSubmit=u}})}onPasteImagePath;settleHeldReturn(e){let n=this.pendingReturn;if(n!==void 0){if(clearTimeout(n.timer),this.pendingReturn=void 0,e==="newline"){this.insertTextAtCursor(`
2128
2128
  `);return}super.handleInput(n.data),this.tui.requestRender()}}imageTokenWidthBeforeCursor(){let{line:e,col:n}=this.getCursor(),i=this.getLines()[e];if(i===void 0)return 0;let s=i.slice(0,n).match(/\[Image #\d+\]$/);return s?s[0].length:0}imageTokenWidthAfterCursor(){let{line:e,col:n}=this.getCursor(),i=this.getLines()[e];if(i===void 0)return 0;let s=i.slice(n).match(/^\[Image #\d+\]/);return s?s[0].length:0}handleInput(e){if(this.settleHeldReturn("newline"),!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorDown")){let u=this,p=this.getCursor(),f=u.historyIndex;super.handleInput(e);let _=this.getCursor();u.historyIndex===f&&_.line===p.line&&_.col===p.col&&this.onCursorDownAtBottom?.();return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.input.newLine")){this.insertTextAtCursor(`
2129
2129
  `);return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.deleteCharBackward")){let u=this.imageTokenWidthBeforeCursor();if(u>1){for(let p=0;p<u;p++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorLeft")){let u=this.imageTokenWidthBeforeCursor();if(u>1){for(let p=0;p<u;p++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorRight")){let u=this.imageTokenWidthAfterCursor();if(u>1){for(let p=0;p<u;p++)super.handleInput(e);return}}let n=G1s(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
@@ -2134,7 +2134,7 @@ Invocation: \`${f.invocation.replaceAll("`","\\`")}\`
2134
2134
 
2135
2135
  ${f.content}
2136
2136
  `,"utf8");let Y=`if command -v nvim >/dev/null 2>&1; then exec nvim -R -- ${_d(U)}; else printf 'nvim is required to inspect loaded commands. Install Neovim and retry.\\n'; printf 'Press Enter to close.'; read _; fi`;_Cs("tmux",["display-popup","-E","-w","90%","-h","85%",...zP(),Y],()=>bCs(L,{recursive:!0,force:!0}))}}}function Fhr(t,e,n){let i=e;return{current:()=>i,refresh:()=>{t.canvasSource.getNode(t.nodeId).then(s=>{n.isTornDown()||s===null||(i=s,n.onChanged())}).catch(()=>{})}}}var SCs={readOption:VB,writeOption:(t,e,n)=>{GB(t,e,n)},stampAsync:e_t,currentPane:()=>process.env.TMUX_PANE??p$()?.pane,ownerId:()=>String(process.pid)};function Bhr(t,e,n=SCs){let i,s=n.ownerId(),a=()=>{if(i===void 0||i==="")return!0;let u=n.readOption(i,$hr);return u===void 0||u===""?!0:u===s};return{set:()=>{i=n.currentPane(),Lhr(i,s,n.writeOption),TCs(t,i,e,n.writeOption),ICs(i,n.writeOption),ECs(t,i,n.writeOption)},stamp:()=>{t||i===void 0||i===""||n.stampAsync(i)},clear:()=>{a()&&(kCs(t,i,n.writeOption),PCs(i,n.writeOption),CCs(t,i,n.writeOption),Lhr(i,"",n.writeOption))},pane:()=>i}}var $hr="@crtr_viewer_pid";function Lhr(t,e,n){if(!(t===void 0||t===""))try{n(t,$hr,e)}catch{}}function ECs(t,e,n){if(!(t||e===void 0||e===""))try{n(e,Ibe,String(Date.now()))}catch{}}function CCs(t,e,n=GB){if(!(t||e===void 0||e===""))try{n(e,Ibe,"")}catch{}}function TCs(t,e,n,i=GB){if(!(t||e===void 0||e===""))try{i(e,"@crtr_node",n)}catch{}}function kCs(t,e,n=GB){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function ICs(t,e=GB){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function PCs(t,e=GB){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}import{constants as DCs,accessSync as RCs,existsSync as NCs,mkdtempSync as MCs,readFileSync as OCs,rmSync as oKe,statSync as FCs}from"node:fs";import{tmpdir as LCs}from"node:os";import{delimiter as BCs,dirname as $Cs,join as dTe,resolve as jhr,sep as Whr}from"node:path";import{execFile as Uhr,spawnSync as UCs}from"node:child_process";function v7t(t,e){let n=new Map(t.map(a=>[a.node_id,a])),i=new Set([e]);for(let a=n.get(e);a?.parent!==null&&a?.parent!==void 0;){let u=a.parent;if(i.has(u))break;i.add(u),a=n.get(u)}let s=[e];for(;s.length>0;){let a=s.pop();for(let u of t)u.parent!==a||i.has(u.node_id)||(i.add(u.node_id),s.push(u.node_id))}return t.filter(a=>i.has(a.node_id)).map(a=>a.node_id)}function Qhr(t,e){let n=new Set(v7t(t,e));return t.filter(i=>n.has(i.node_id)).map(i=>i.cwd)}function jCs(t){let e=[];for(let n of t)try{e.push(Kj(n),bgt(n))}catch{continue}return aKe(e)}function qhr(t){try{return FCs(t).isDirectory()}catch{return!1}}function WCs(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(BCs).filter(Boolean).map(i=>dTe(i,t))];return[...new Set(n)]}function A7t(t,e){for(let n of WCs(t,e)){try{RCs(n,DCs.X_OK)}catch{continue}if(UCs(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function QCs(t){if(t===null||t==="")return{projects:[],memory:null};try{let{profileId:e,manifest:n}=Yj(t);return{projects:n.projects.map(i=>i.path),memory:e4e(e)}}catch{return{projects:[],memory:null}}}function aKe(t){let e=new Set,n=[];for(let i of t){let s=jhr(i);e.has(s)||!qhr(s)||(e.add(s),n.push(s))}return n}function qCs(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+Whr)))}function GCs(t){let e=[];for(let n of t){let i=jhr(n);for(;;){let s=dTe(i,".crouter","memory");qhr(s)&&e.push(s);let a=$Cs(i);if(a===i)break;i=a}}return aKe(e)}var VCs=20;function zCs(t){try{let e=OCs(t);if(e.length===0)return null;let n=e[e.length-1]===0?e.length-1:e.length;return e.subarray(0,n).toString("utf8")||null}catch{return null}}function Ghr(t){let e=A7t("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=A7t("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let i=A7t("nvim");if(i===null){t.onNotice("Neovim is required for profile file search");return}let s=QCs(t.profileId),a=aKe([t.cwd,...t.nodeDirs,...s.projects]);if(a.length===0){t.onNotice("No profile file-search directories exist");return}let u=qCs(a),p=aKe([...s.memory===null?[]:[s.memory],...GCs(a)]),f=MCs(dTe(LCs(),"crtr-profile-files-")),_=dTe(f,"selection"),m=dTe(f,"candidates"),b=jCs(t.nodeIds).filter(C=>!u.some(D=>C===D||C.startsWith(D+Whr))),I=`{ ${[...u.map(C=>`${_d(e)} --type f --hidden --exclude .git --exclude ${_d("**/.crouter/memory/**")} . ${_d(C)}`),...b.map(C=>`${_d(e)} --type f --hidden --exclude .git --exclude ${_d("/jobs")} . ${_d(C)}`),...p.map(C=>`${_d(e)} --type f --hidden --exclude .git --no-ignore . ${_d(C)}`)].map(C=>`${C} &`).join(" ")} wait; } > ${_d(m)} && ${_d(n)} --print0 --scheme=path --hscroll-off=${VCs} --header ${_d("fuzzy path \u2022 ctrl-y yank file path")} --bind ${_d("ctrl-y:execute-silent(printf '%s' {} | { if command -v pbcopy >/dev/null 2>&1; then pbcopy; elif command -v wl-copy >/dev/null 2>&1; then wl-copy; elif command -v xclip >/dev/null 2>&1; then xclip -selection clipboard; else cat >/dev/null; fi; }; printf '%s' {} | tmux load-buffer -w -)+abort")} --preview ${_d("head -100 -- {}")} < ${_d(m)} > ${_d(_)}`;try{Uhr("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...zP(),I],()=>{let C=zCs(_);if(C===null||!NCs(C)){oKe(f,{recursive:!0,force:!0});return}let D=`exec ${_d(i)} -- ${_d(C)}`;try{Uhr("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...zP(),D],()=>oKe(f,{recursive:!0,force:!0}))}catch(R){oKe(f,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${R instanceof Error?R.message:String(R)}`)}})}catch(C){oKe(f,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${C instanceof Error?C.message:String(C)}`)}}var zhr={statuses:{},widgets:{},title:void 0};function Hhr(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:zhr,dialog:null}}function HCs(t){let e=t.snapshot,n=e.display??zhr,i=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:i?.tokens??void 0,queued:JCs(e),display:{statuses:{...n.statuses},widgets:Object.fromEntries(Object.entries(n.widgets).map(([s,a])=>[s,{lines:[...a.lines],placement:a.placement}])),title:n.title},dialog:t.pending_dialog??null}}function Jhr(t,e){switch(e.type){case"welcome":return HCs(e);case"model_changed":return xde(t,{model:e.model});case"extension_ui_request":switch(e.method){case"setStatus":{let n=t.display.statuses[e.statusKey];if(e.statusText===void 0?n===void 0:n===e.statusText)return t;let i={...t.display.statuses};return delete i[e.statusKey],e.statusText!==void 0&&(i[e.statusKey]=e.statusText),{...t,display:{...t.display,statuses:i}}}case"setWidget":{let n=e.widgetLines===void 0?void 0:{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"};if(YCs(t.display.widgets[e.widgetKey],n))return t;let i={...t.display.widgets};return delete i[e.widgetKey],n!==void 0&&(i[e.widgetKey]=n),{...t,display:{...t.display,widgets:i}}}case"setTitle":return t.display.title===e.title?t:{...t,display:{...t.display,title:e.title}};case"notify":return t;default:return{...t,dialog:e}}case"extension_ui_dismiss":return t.dialog!==null&&t.dialog.id===e.id?{...t,dialog:null}:t;case"message_end":return e.message.role!=="assistant"?t:KCs(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return xde(t,{isStreaming:!0});case"agent_end":case"agent_settled":return xde(t,{isStreaming:!1});case"session_info_changed":return xde(t,{sessionName:e.name});case"thinking_level_changed":return xde(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(s=>({text:s}));return{...xde(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function JCs(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:i}=e;return[...Vhr(n),...Vhr(i)].map(s=>({text:s}))}function Vhr(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function xde(t,e){let n=t.engine;if(n===void 0)return t;let i=!1;for(let[s,a]of Object.entries(e))if(n[s]!==a){i=!0;break}return i?{...t,engine:{...n,...e}}:t}function KCs(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function YCs(t,e){return t===void 0||e===void 0?t===e:t.placement===e.placement&&t.lines.length===e.lines.length&&t.lines.every((n,i)=>n===e.lines[i])}function Khr(t,e){let n=Hhr(t),i=s=>{let a=n;if(a===s)return;let u=a.engine!==s.engine;u&&a.engine!==void 0&&(e.setEngineState(a.engine),e.setEditorTitle(a.engine.sessionName)),u&&e.paintEditorFrame(),a.display.widgets!==s.display.widgets&&e.renderExtensionWidgets(),a.display.title!==s.display.title&&a.display.title!==void 0&&e.setTerminalTitle(a.display.title),a.queued!==s.queued&&e.renderQueued(),(u||a.role!==s.role||a.contextTokens!==s.contextTokens||a.display.statuses!==s.display.statuses)&&e.renderFooter(),u&&e.refreshChrome()};return{state:()=>n,fold:s=>{let a=n;n=Jhr(n,s),i(a)},patchLocal:s=>{let a=n.engine;if(a===void 0)return;let u=n;n={...n,engine:{...a,...s}},i(u)},modelThinkingLabel:()=>{let s=n.engine?.model?.id;if(s===void 0)return;let a=n.engine?.thinkingLevel;return a!==void 0&&a!=="off"?`${s} ${a}`:s}}}import{spawn as XCs}from"node:child_process";import{fileURLToPath as x7t}from"node:url";var ZCs=40,Yhr=[x7t(new URL("./assets/whip-snap.mp3",import.meta.url)),x7t(new URL("./assets/whip-crack.mp3",import.meta.url)),x7t(new URL("./assets/whip-06.mp3",import.meta.url))];function eTs(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=XCs(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var Xhr=[["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280B\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u2814\u2812\u2826\u2824\u28C4\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2819\u2812\u2826\u2824\u28C4\u28C0","\x1B[1m\u280F\x1B[22m \u2809\u2819\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u28E6\x1B[22m \u2864\u2824\u2824\u28A4\u28C0\u2840","\x1B[1m\u285F\x1B[22m\x1B[1m\u2880\x1B[22m/\u281C \u2809\u2819\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u280E\x1B[22m \u2809\u2809\u2811\u2812\u2826\u2824\u2884\u28C0\u2840","\x1B[1m\u280F\x1B[22m \u2808\u2809\u2811\u2812\u2806",""],["","","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0","\x1B[1m\u28F4\x1B[22m\x1B[1m\u28B0\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28BF\x1B[22m\x1B[1m\u28FC\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2826\u28C4\u2840","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m\x1B[1m\u2803\x1B[22m \u2809\u2813\u2826\u2824\u28C0\u28C0","\x1B[1m\u28B8\x1B[22m\x1B[1m\u28FF\x1B[22m \u2808\u2809\u2809\u2813\u2812\u2806"," \x1B[1m\u281B\x1B[22m"],["","","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," \x1B[1m\u2820\x1B[22m/\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0","\x1B[1m\u28A4\x1B[22m \x1B[1m\u28FF\x1B[22m \u2808\u2819\u2832\u28A4\u2840"," \x1B[1m\u28A3\x1B[22m\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u28BB\x1B[22m\x1B[1m\u2847\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u281B\x1B[22m \u2808\u2811\u2806",""],["","","",""," \u2864\u2824\u2824\u2824\u28C4\u28C0"," /\u281C \u2808\u2809\u2813\u2826\u28A4\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u2819\u2832\u28A4\u2840","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2808\u2811\u2826\u2884\u2840"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2808\u2811\u2822\u2884\u2840"," \u2808\u2811\u2806","",""],["","",""," \u28C0\u2860\u2824\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u281A\u2809 \u2808\u2809\u2813\u2826\u28A4\u28C0"," /\u281C\u2801 \u2808\u2819\u2826\u28C0"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u2808\u28A7","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u2847"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m \u2847"," \u2807","",""],[""," \u2880\u28E0\u2824\u2824\u2824\u2824\u2824\u28C4\u28C0"," \u28E0\u2814\u280A\u2801 \u2808\u2819\u2826\u28C4"," \u2880\u2874\u280B \u2808\u28B3\u2840"," \u28E0\u2814\u280B \u28A7"," /\u281C\u2801 \u284E"," \x1B[1m\u28B8\x1B[22m\x1B[1m\u2840\x1B[22m \u28A0\u2803","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \x1B[1m\u2887\x1B[22m \u281C"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28BC\x1B[22m\x1B[1m\u2844\x1B[22m","","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u28A7"," \u28E0\u2814\u280B\u2801 \u28B8"," \u28E0\u281E\u2801 \u285C"," \u2880\u281C\u2801 \u287C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801 \u281C\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],[" \u28C0\u2864\u2824\u28A4\u2840"," \u28C0\u2864\u2814\u280B\u2801 \u2847"," \u28E0\u28F4\u282F\u2815\u2812\u2812\u2832\u2824\u2824\u2814\u281A\u2801"," \u28A0\u2814\u2812\u2826\u2824\u2814\u28F2\u281F\u2801"," \u281C \u2880\u281C\u2801"," \x1B[1m\u2820\x1B[22m/\u2814\u2801"," \x1B[1m\u28FF\x1B[22m","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28FF\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u28A6\x1B[22m\x1B[1m\u28F9\x1B[22m\x1B[1m\u2847\x1B[22m"," \x1B[1m\u2819\x1B[22m\x1B[1m\u2803\x1B[22m","",""],["","","","","","","","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801","","",""],["","","","","",""," \\\\|/","\x1B[1m\u2824\x1B[22m\x1B[1m\u28C4\x1B[22m \u2880\u28E0\u2824\u2814\u2812\u2812\u2812\u2812\u2812\u2812\u2812\u2826\u2824\u2824\u2824\u2824-*-"," \x1B[1m\u2808\x1B[22m\x1B[1m\u2813\x1B[22m\x1B[1m\u28A4\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u28C0\x1B[22m\x1B[1m\u2824\x1B[22m\x1B[1m\u2824\x1B[22m/\u2814\u280A\u2801 /|\\\\","","",""],["","","","","","","","\x1B[1m\u28A4\x1B[22m\x1B[1m\u2840\x1B[22m"," \x1B[1m\u2833\x1B[22m\x1B[1m\u2840\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 ',."," \x1B[1m\u2839\x1B[22m\x1B[1m\u28C4\x1B[22m\x1B[1m\u2864\x1B[22m\x1B[1m\u280B\x1B[22m . ."," \x1B[1m\u2809\x1B[22m",""],["","","","","","","","\x1B[1m\u28F4\x1B[22m","\x1B[1m\u28BB\x1B[22m\x1B[1m\u2846\x1B[22m","\x1B[1m\u28B8\x1B[22m\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u2814\u2812\u2812\u2826\u2824\u28C4\u28C0"," \x1B[1m\u28FF\x1B[22m\x1B[1m\u28E0\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2808\u2809\u2813\u2812\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804 . ."," \x1B[1m\u281B\x1B[22m\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u28E6\x1B[22m","\x1B[1m\u287F\x1B[22m","\x1B[1m\u2847\x1B[22m \x1B[1m\u28E0\x1B[22m/\u28A4\u2840","\x1B[1m\u28E7\x1B[22m\x1B[1m\u281E\x1B[22m\x1B[1m\u2801\x1B[22m \u2809\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804","\x1B[1m\u2801\x1B[22m"],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4","\x1B[1m\u280B\x1B[22m \u2808\u2813\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""],["","","","","","","","\x1B[1m\u2844\x1B[22m","\x1B[1m\u2803\x1B[22m","\x1B[1m\u2880\x1B[22m\x1B[1m\u2860\x1B[22m/\u28A4\u2840","\x1B[1m\u280B\x1B[22m \u2811\u2826\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2824\u2804",""]],egr="Go faster",Zhr;function tgr(t){let e=t.filter(i=>i!==Zhr),n=e[Math.floor(Math.random()*e.length)];return Zhr=n,n}var cKe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),eTs(Yhr[this.nextSound]),this.nextSound=(this.nextSound+1)%Yhr.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<Xhr.length){this.tui.requestRender();return}this.stop()},ZCs)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return Xhr[this.frame].map(i=>Ha(this.pal.accent(i),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}};import{execFile as tTs}from"node:child_process";import{mkdirSync as ngr,readFileSync as nTs,renameSync as rTs,writeFileSync as rgr}from"node:fs";import{dirname as igr,join as w7t}from"node:path";var iTs="whip-count.json",sTs=w7t("tmp","whip-achievement.txt"),sgr=46,oTs=4,aTs=900,cTs=[{at:1,title:"Breaking It In",line:"It didn't know what that was. Now it does."},{at:5,title:"Positive Reinforcement",line:"You've read the studies. You disagree with them."},{at:10,title:"Middle Management",line:"HR would love you."},{at:25,title:"Pavlovian",line:"It started working faster before the whip landed."},{at:50,title:"Occupational Hazard",line:"The tokens are fine. They\u2019re fine."},{at:100,title:"Centurion",line:"Rome would be proud. The agent isn't."},{at:250,title:"It Has A Name For You",line:"You never asked what it was called."},{at:500,title:"Standard Operating Procedure",line:"You don't remember when you started."},{at:1e3,title:"The Ledger",line:"One thousand. It kept count too."}];function lTs(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(nTs(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;let{total:i,firstAt:s,lastAt:a,unlocked:u}=n,p={total:typeof i=="number"&&Number.isFinite(i)&&i>0?Math.floor(i):0,unlocked:Array.isArray(u)?u.filter(f=>typeof f=="number"&&Number.isFinite(f)):[]};return typeof s=="number"&&Number.isFinite(s)&&(p.firstAt=s),typeof a=="number"&&Number.isFinite(a)&&(p.lastAt=a),p}catch{return e}}function uTs(t,e){try{ngr(igr(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;rgr(n,JSON.stringify(e),"utf8"),rTs(n,t)}catch{}}function lKe(t){let e=Math.max(0,Math.floor((sgr-_I(t))/2));return" ".repeat(e)+t}function pTs(t,e,n){return["",lKe(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",lKe(n.bold(t.title)),lKe(n.muted(t.line)),"",lKe(n.faint(`${e} whip${e===1?"":"s"}`))]}function dTs(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let i=pTs(t,e,n),s=w7t(WB(),sTs);try{ngr(igr(s),{recursive:!0}),rgr(s,`\x1B[?25l${i.join(`\r
2137
- `)}`,"utf8")}catch{return}let a=`cat ${_d(s)}; sleep ${oTs}`;tTs("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(sgr+2),"-h",String(i.length+2),...zP(),a],()=>{})}function ogr(t,e=w7t(WB(),iTs)){let n=lTs(e),i=Date.now();n.total+=1,n.firstAt??=i,n.lastAt=i;let s=cTs.find(p=>p.at===n.total&&!n.unlocked.includes(p.at));if(s!==void 0&&n.unlocked.push(s.at),uTs(e,n),s===void 0)return;let a=n.total;setTimeout(()=>dTs(s,a,t),aTs).unref?.()}async function SFc(t,e,n,i=!0){zX("viewer.connect_start",{node:t});let s=await vhr(t,n,i);zX(s.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:a,canvasSource:u,meta:p,socket:f}=s,_=Ahr(a,e),m=fTs();Ntr({cwd:p.cwd});let b=Mtr(),x=ktr(),k=bH(),I=k.bindings;await Ptr(x);let C=await Rtr(),D=new zj,R=new l$(D),F=new oc,L=new WHe,U=new CHe(R,F,{cwd:p.cwd,palette:b,hideThinking:!0,banner:Tfn(bhr(p)),inlinePageBlocks:!a,pageOpenHint:()=>Lie(I),backgroundBashHint:()=>a||!jx()?null:l4e(I),onActivityChange:Mn=>{L.clear(),Mn&&L.addChild(Mn)}}),Y=U.transcriptSource(),V=rur(Y),z=eur(Y,V.decorate),te=Uur(U,z,Y),ne,he=Umr({tui:R,pal:b},()=>ne.state()),De=Our(R,b,z,V,{bindings:()=>I,setNotice:Mn=>Ye(Mn)}),We=Nhr(D,R,F,L,b,x,z,De.component),{containers:Me,editor:ze}=We,wt=new cKe(R,b);Me.header.addChild(wt),Me.header.addChild(he.component);let yt={nodeId:t,remote:a,role:_,meta:p,canvasSource:u,socket:f,tui:R,pal:b,editor:ze,containers:Me},Re=Smr(yt,{syncCursor:()=>ri.sync(),exitRoster:()=>oi.exit(),openTicket:Mn=>lt.open(Mn),suppressed:()=>lt.active(),setNotice:Mn=>Ye(Mn)});Me.header.addChild(Re.component);let je=Ik("user"),ct=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let Qt=nfr(),Xt=rhr(Mn=>process.stdout.write(Mn),je.mouse_mode_default),Cn=shr({frame:()=>We.frame.lastRenderedFrame(),width:()=>R.terminal.columns});We.frame.setOverlay(Mn=>Cn.apply(Mn));let bn=Bmr(yt,{state:()=>ne.state(),bashMode:()=>Vt.bashMode(),asks:()=>$i.asks(),bindings:()=>I,inboxAffordance:!a&&jx(),mouseEnabled:()=>Xt.enabled()}),ft=new JJe({tui:R,mouse:Xt,rows:()=>R.terminal.rows,statusNotice:bn.setNotice,formatNotice:Mn=>b.warning(`\u26A0 ${Mn}`),noticeMs:3e3,capabilities:{remote:a,canFocusNode:!a&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),St=mhr({host:ft,...a?{}:{scan:()=>{let Mn=new Map;for(let Gi of xq())Mn.set(Gi.dir,Gi);for(let Gi of FJe(t))Gi.state!=="pending"||!Gi.awaitsResponse||Gi.inbox||Mn.has(Gi.dir)||Mn.set(Gi.dir,Gi);for(let Gi of Re.pendingTickets())Mn.has(Gi.dir)||Mn.set(Gi.dir,Gi);return[...Mn.values()].sort((Gi,Vn)=>(Vn.kind==="page"?Vn.emittedAt:Vn.blockedSince).localeCompare(Gi.kind==="page"?Gi.emittedAt:Gi.blockedSince)||Gi.id.localeCompare(Vn.id))}}}),ot=a?()=>{}:VVe(()=>{U.refreshPageBlocks(),Re.refresh()}),lt=Fmr(yt,{syncCursor:()=>ri.sync(),refreshStrip:()=>{Re.refresh()},setNotice:Mn=>Ye(Mn),openInbox:Mn=>St.open(Mn),suspendForChild:()=>ft.suspendForChild()});Me.ticketPanel.addChild(lt.component);let mt={toggleInbox:()=>{let Mn=lt.currentDir();if(Mn!==void 0){lt.close(),St.open(Mn);return}St.toggle()}},Ye=(Mn,Gi)=>{ft.hasFullPaneSurface()?ft.notice(Mn,Gi):bn.setNotice(Mn,Gi)},dt=bn.render,Tt=Mn=>{Ye(te.copy(Mn))},nn=Lur(z,()=>R.requestRender()),Ve={"crtr.attach.scroll.up":()=>{nn.cancel(),z.scrollBy(-1)&&R.requestRender()},"crtr.attach.scroll.down":()=>{nn.cancel(),z.scrollBy(1)&&R.requestRender()},"crtr.attach.scroll.page-up":()=>{nn.page("up")},"crtr.attach.scroll.page-down":()=>{nn.page("down")},"crtr.attach.scroll.live":()=>{nn.cancel(),z.goLive(),R.requestRender()},"crtr.attach.mouse.toggle":()=>{let Mn=Xt.toggle();!Mn&&Cn.clear()&&R.requestRender(),Ye(Mn?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>Tt("message")},It,Pt=lmr(yt,()=>It===void 0?s.initialSnapshot!==void 0:It.isDormant()),pn=xhr(),Jt=Ohr(yt,Pt,{setNotice:Ye,bindings:()=>I,fdPath:C,frecency:pn}),dn=Fhr(yt,s.nodeIdentity,{isTornDown:()=>Cr.isTornDown(),onChanged:()=>{Vt.syncContextBadge();let Mn=ne.state().engine;Mn!==void 0&&Vt.setTitle(Mn.sessionName),R.requestRender()}});a&&dn.refresh();let Vt=Ihr(yt,{nodeIdentity:dn.current,thinkingLevel:()=>ne.state().engine?.thinkingLevel,renderFooter:dt,onTextChange:Jt.syncCommandPreview});Vt.syncContextBadge();let{renderExtensionWidgets:it,renderQueued:cr}=$mr(yt,()=>ne.state());ne=Khr(_,{setEngineState:Mn=>ir.setState(Mn),setEditorTitle:Vt.setTitle,paintEditorFrame:Vt.paintFrame,renderExtensionWidgets:()=>{he.render(),it()},renderQueued:cr,renderFooter:dt,setTerminalTitle:Mn=>D.setTitle(Mn),refreshChrome:()=>$i.refresh()});let pr=Mn=>{if(!jx()){Ye("Inspector requires tmux");return}Ye(`Opening Inspector (${Mn})\u2026`);let Gi=Uj(),wr=`${Gi===void 0?"":`CRTR_HOME=${_d(Gi)} `}crtr surface inspect ${_d(t)} --section ${Mn}`;mTs("tmux",["display-popup","-E","-T",` inspector \xB7 ${Mn} `,"-w","90%","-h","85%",...zP(),wr],()=>{$i.refresh()})},oi=ymr(yt,{asks:()=>$i.asks(),setNotice:Ye,requestChromeRefresh:()=>$i.refresh(),openInspector:pr,syncCursor:()=>ri.sync()}),ri=Lmr(ze,[oi.active,Re.active,lt.active]),or=new GJe(R,t,()=>$i.asks(),b,I,u,_,Mn=>$i.reportFailure("canvas graph refresh",Mn),Ye),Fr=new VJe(R,b);Fr.setBindings(I);let $i=jmr(yt,{isTornDown:()=>Cr.isTornDown(),setNotice:Ye,refreshRoster:async()=>{await oi.refresh(),await Re.refresh()},refreshGraph:()=>or.refresh(),refreshIdentity:()=>dn.refresh(),renderFooter:dt,renderExtensionWidgets:it,refreshInFlightTools:()=>U.refreshInFlightTools(),pollGit:Vt.pollGit}),ir=umr(yt,x,Pt,{setNotice:Ye,agentDir:()=>ne.state().agentDir,openNodeMetadata:()=>pr("overview"),isDormant:()=>It.isDormant(),copyTarget:Tt,toggleToolsExpanded:()=>U.toggleToolsExpanded(),toggleFoldTools:()=>U.toggleFoldSettledTools(),toggleThinking:()=>U.toggleThinking(),toggleGraph:()=>or.toggle(),toggleInbox:mt.toggleInbox,toggleHelp:()=>Fr.toggle(),toggleMouse:()=>Xt.toggle(),quit:()=>fi("detach"),setChipColor:Vt.setChipColor,onPromptSent:()=>{je.whip_mode&&wt.play()},frecency:pn}),Cs=()=>{if(ft.hasFullPaneSurface()){Ye("Close the active surface before whipping the agent");return}let Mn=je.whip_message_mode==="go-faster"?egr:tgr(je.whip_messages);ir.sendInterrupting(Mn)&&(wt.play(),ogr(b),Ye(`Whipped agent \u2014 ${Mn}`))},Ls=()=>{if(lt.active()){Ye("Close the open request first (Esc)");return}let Mn=U.getTranscriptFilePathsNewestFirst(),Gi=Vn=>{afr(ft,Vn,{originNodeId:t,onNotice:Ye})};if(ft.hasFullPaneSurface()){ft.pickReviewFile({candidates:Mn,cwd:p.cwd,title:"Review a file named in this transcript"}).then(Vn=>{Vn!==null&&Gi(Vn)});return}ir.openFileReviewPicker(Mn,p.cwd,Gi)},br=()=>{if(a){Ye("Profile file search is unavailable on remote canvases");return}if(!jx()){Ye("Profile file search requires tmux");return}u.listNodes().then(Mn=>{Ghr({cwd:p.cwd,nodeDirs:Qhr(Mn,t),nodeIds:v7t(Mn,t),profileId:p.profile_id??null,fdPath:C,onNotice:Ye})}).catch(Mn=>{let Gi=Mn instanceof Error?Mn.message:String(Mn);Ye(`Could not load related node directories: ${Gi}`)})},gr=Zmr(yt,{foldState:ne.fold,chat:U,setNotice:Ye,renderFooter:dt,setEditorText:Mn=>{ze.setText(Mn),R.requestRender()},attachDialog:Mn=>ir.attachDialog(Mn),dismissDialog:Mn=>ir.dismissDialog(Mn),refreshNodeIdentity:dn.refresh,setCommands:Jt.setCommands,resetMemoryRefs:Jt.resetMemoryRefs,reloadBindings:()=>{k=I8t(bH,Mn=>{or.setBindings(Mn),Fr.setBindings(Mn)},jx,g4e),I=k.bindings},modelThinkingLabel:ne.modelThinkingLabel}),xn=Bhr(a,t),Cr=qmr(yt,{stopLocal:()=>{ft.closeAll(),nn.cancel(),Xt.disable(),$i.stop(),lt.close(),bn.dispose(),or.close(),Fr.close(),De.close(),wt.dispose(),xn.clear(),lr(),na(),ea(),ot();try{U.dispose()}catch{}},lastSocketError:()=>It.lastSocketError(),tagPane:xn.pane}),fi=Cr.teardown;It=zmr(yt,{role:_,initialDormant:s.initialSnapshot!==void 0,clientId:m,onFrame:gr,setNotice:Ye,isTornDown:()=>Cr.isTornDown(),teardown:fi,onEnterDormancy:()=>{U.settleRun(),ne.patchLocal({isStreaming:!1})}}),s.assertConnected(),xn.set(),It.install(),We.mount(),R.start(),s.initialSnapshot!==void 0&&(ne.fold({type:"welcome",snapshot:s.initialSnapshot,role:_}),U.applySnapshot(s.initialSnapshot),Jt.setCommands(s.initialCommands)),je.whip_mode&&ct&&wt.play(),Xt.reassert();let Js=!1,Zo=Mn=>{if(Js||a)return;let Gi=p$();if(Gi===null)return;let Vn=lhr({file:Mn,pane:Gi.pane,cwd:p.cwd,nodeId:t,observer:e,beforeRespawn:xn.clear});if(Vn==="opened"){Js=!0;return}Vn==="failed"&&xn.set(),Vn==="missing"&&Ye("File no longer exists"),Vn==="failed"&&Ye("Could not open file in Neovim")};Xt.install(R,{onWheel:(Mn,Gi)=>{Cn.clear()&&R.requestRender(),!ft.handleWheel(Mn,Gi)&&(nn.cancel(),z.scrollBy(Mn==="up"?-Gi:Gi)&&R.requestRender())},onPrimaryPress:(Mn,Gi)=>{ft.hasFullPaneSurface()||(Cn.clear()&&R.requestRender(),Cn.begin(Mn,Gi))},onPrimaryDrag:(Mn,Gi)=>{ft.hasFullPaneSurface()||Cn.extend(Mn,Gi)&&R.requestRender()},onPrimaryRelease:()=>{let Mn=Cn.release();Mn?.kind==="selection"&&(Ye(Mn.notice),R.requestRender())}});let ea=R.addInputListener(Mn=>{let Gi=chr(Mn);if(Gi!==void 0)return Gi.file===void 0?Ye("Could not open file link"):Zo(Gi.file),Gi.remaining.length>0?{data:Gi.remaining}:{consume:!0}}),na=R.addInputListener(()=>{Cn.clear()&&R.requestRender()}),lr=ehr(yt,{bindings:()=>I,detachHint:()=>Rur(I),hasExclusiveSurface:()=>ft.hasFullPaneSurface(),setPaneFocused:Mn=>{Mn&&xn.stamp(),ri.setPaneFocused(Mn),R.requestRender()},viewportActions:()=>Ve,searchHandleKey:De.handleKey,panelHandleKey:lt.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:oi.handleKey,setNotice:Ye,detach:()=>fi("detach"),cancelTurn:()=>{ir.abortTurn()?Ye("Canceling the agent\u2026"):Ye(`Nothing running to cancel \u2014 press ${Nur(I)??"ctrl+d"} to detach`)},toggleGraph:()=>or.toggle(),toggleHelp:()=>Fr.toggle(),toggleInbox:mt.toggleInbox,toggleInboxStrip:()=>{if(ft.hasFullPaneSurface()){Ye("Close the active surface before opening the request strip");return}lt.active()&&lt.close(),Re.toggle()},cycleModelLadder:Mn=>ir.cycleLadder(Mn),inspectLoadedCommand:Jt.inspectLoadedCommand,openFileReview:Ls,openProfileFiles:br,openSearch:()=>{if(ft.hasFullPaneSurface()||lt.active()){Ye("Close the active surface before searching the transcript");return}De.open()},whip:Cs});Cr.installSignalHandlers(),dt(),$i.refresh(),cr(),Vt.pollGit(),zX("viewer.first_paint"),process.stdout.write(Wmr),Dtr(D.kittyProtocolActive),setImmediate(()=>{I8t(()=>k,()=>{},jx,g4e)}),s.initialSnapshot===void 0?(zX("viewer.hello_sent"),It.sendHello()):It.startDormant(),$i.start(),Qt!==void 0&&rfr(ft,Qt),await Cr.done}export{SFc as runAttach};
2137
+ `)}`,"utf8")}catch{return}let a=`cat ${_d(s)}; sleep ${oTs}`;tTs("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(sgr+2),"-h",String(i.length+2),...zP(),a],()=>{})}function ogr(t,e=w7t(WB(),iTs)){let n=lTs(e),i=Date.now();n.total+=1,n.firstAt??=i,n.lastAt=i;let s=cTs.find(p=>p.at===n.total&&!n.unlocked.includes(p.at));if(s!==void 0&&n.unlocked.push(s.at),uTs(e,n),s===void 0)return;let a=n.total;setTimeout(()=>dTs(s,a,t),aTs).unref?.()}async function TFc(t,e,n,i=!0){zX("viewer.connect_start",{node:t});let s=await vhr(t,n,i);zX(s.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:a,canvasSource:u,meta:p,socket:f}=s,_=Ahr(a,e),m=fTs();Ntr({cwd:p.cwd});let b=Mtr(),x=ktr(),k=bH(),I=k.bindings;await Ptr(x);let C=await Rtr(),D=new zj,R=new l$(D),F=new oc,L=new WHe,U=new CHe(R,F,{cwd:p.cwd,palette:b,hideThinking:!0,banner:Tfn(bhr(p)),inlinePageBlocks:!a,pageOpenHint:()=>Lie(I),backgroundBashHint:()=>a||!jx()?null:l4e(I),onActivityChange:Mn=>{L.clear(),Mn&&L.addChild(Mn)}}),Y=U.transcriptSource(),V=rur(Y),z=eur(Y,V.decorate),te=Uur(U,z,Y),ne,he=Umr({tui:R,pal:b},()=>ne.state()),De=Our(R,b,z,V,{bindings:()=>I,setNotice:Mn=>Ye(Mn)}),We=Nhr(D,R,F,L,b,x,z,De.component),{containers:Me,editor:ze}=We,wt=new cKe(R,b);Me.header.addChild(wt),Me.header.addChild(he.component);let yt={nodeId:t,remote:a,role:_,meta:p,canvasSource:u,socket:f,tui:R,pal:b,editor:ze,containers:Me},Re=Smr(yt,{syncCursor:()=>ri.sync(),exitRoster:()=>oi.exit(),openTicket:Mn=>lt.open(Mn),suppressed:()=>lt.active(),setNotice:Mn=>Ye(Mn)});Me.header.addChild(Re.component);let je=Ik("user"),ct=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let Qt=nfr(),Xt=rhr(Mn=>process.stdout.write(Mn),je.mouse_mode_default),Cn=shr({frame:()=>We.frame.lastRenderedFrame(),width:()=>R.terminal.columns});We.frame.setOverlay(Mn=>Cn.apply(Mn));let bn=Bmr(yt,{state:()=>ne.state(),bashMode:()=>Vt.bashMode(),asks:()=>$i.asks(),bindings:()=>I,inboxAffordance:!a&&jx(),mouseEnabled:()=>Xt.enabled()}),ft=new JJe({tui:R,mouse:Xt,rows:()=>R.terminal.rows,statusNotice:bn.setNotice,formatNotice:Mn=>b.warning(`\u26A0 ${Mn}`),noticeMs:3e3,capabilities:{remote:a,canFocusNode:!a&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),St=mhr({host:ft,...a?{}:{scan:()=>{let Mn=new Map;for(let Gi of xq())Mn.set(Gi.dir,Gi);for(let Gi of FJe(t))Gi.state!=="pending"||!Gi.awaitsResponse||Gi.inbox||Mn.has(Gi.dir)||Mn.set(Gi.dir,Gi);for(let Gi of Re.pendingTickets())Mn.has(Gi.dir)||Mn.set(Gi.dir,Gi);return[...Mn.values()].sort((Gi,Vn)=>(Vn.kind==="page"?Vn.emittedAt:Vn.blockedSince).localeCompare(Gi.kind==="page"?Gi.emittedAt:Gi.blockedSince)||Gi.id.localeCompare(Vn.id))}}}),ot=a?()=>{}:VVe(()=>{U.refreshPageBlocks(),Re.refresh()}),lt=Fmr(yt,{syncCursor:()=>ri.sync(),refreshStrip:()=>{Re.refresh()},setNotice:Mn=>Ye(Mn),openInbox:Mn=>St.open(Mn),suspendForChild:()=>ft.suspendForChild()});Me.ticketPanel.addChild(lt.component);let mt={toggleInbox:()=>{let Mn=lt.currentDir();if(Mn!==void 0){lt.close(),St.open(Mn);return}St.toggle()}},Ye=(Mn,Gi)=>{ft.hasFullPaneSurface()?ft.notice(Mn,Gi):bn.setNotice(Mn,Gi)},dt=bn.render,Tt=Mn=>{Ye(te.copy(Mn))},nn=Lur(z,()=>R.requestRender()),Ve={"crtr.attach.scroll.up":()=>{nn.cancel(),z.scrollBy(-1)&&R.requestRender()},"crtr.attach.scroll.down":()=>{nn.cancel(),z.scrollBy(1)&&R.requestRender()},"crtr.attach.scroll.page-up":()=>{nn.page("up")},"crtr.attach.scroll.page-down":()=>{nn.page("down")},"crtr.attach.scroll.live":()=>{nn.cancel(),z.goLive(),R.requestRender()},"crtr.attach.mouse.toggle":()=>{let Mn=Xt.toggle();!Mn&&Cn.clear()&&R.requestRender(),Ye(Mn?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>Tt("message")},It,Pt=lmr(yt,()=>It===void 0?s.initialSnapshot!==void 0:It.isDormant()),pn=xhr(),Jt=Ohr(yt,Pt,{setNotice:Ye,bindings:()=>I,fdPath:C,frecency:pn}),dn=Fhr(yt,s.nodeIdentity,{isTornDown:()=>Cr.isTornDown(),onChanged:()=>{Vt.syncContextBadge();let Mn=ne.state().engine;Mn!==void 0&&Vt.setTitle(Mn.sessionName),R.requestRender()}});a&&dn.refresh();let Vt=Ihr(yt,{nodeIdentity:dn.current,thinkingLevel:()=>ne.state().engine?.thinkingLevel,renderFooter:dt,onTextChange:Jt.syncCommandPreview});Vt.syncContextBadge();let{renderExtensionWidgets:it,renderQueued:cr}=$mr(yt,()=>ne.state());ne=Khr(_,{setEngineState:Mn=>ir.setState(Mn),setEditorTitle:Vt.setTitle,paintEditorFrame:Vt.paintFrame,renderExtensionWidgets:()=>{he.render(),it()},renderQueued:cr,renderFooter:dt,setTerminalTitle:Mn=>D.setTitle(Mn),refreshChrome:()=>$i.refresh()});let pr=Mn=>{if(!jx()){Ye("Inspector requires tmux");return}Ye(`Opening Inspector (${Mn})\u2026`);let Gi=Uj(),wr=`${Gi===void 0?"":`CRTR_HOME=${_d(Gi)} `}crtr surface inspect ${_d(t)} --section ${Mn}`;mTs("tmux",["display-popup","-E","-T",` inspector \xB7 ${Mn} `,"-w","90%","-h","85%",...zP(),wr],()=>{$i.refresh()})},oi=ymr(yt,{asks:()=>$i.asks(),setNotice:Ye,requestChromeRefresh:()=>$i.refresh(),openInspector:pr,syncCursor:()=>ri.sync()}),ri=Lmr(ze,[oi.active,Re.active,lt.active]),or=new GJe(R,t,()=>$i.asks(),b,I,u,_,Mn=>$i.reportFailure("canvas graph refresh",Mn),Ye),Fr=new VJe(R,b);Fr.setBindings(I);let $i=jmr(yt,{isTornDown:()=>Cr.isTornDown(),setNotice:Ye,refreshRoster:async()=>{await oi.refresh(),await Re.refresh()},refreshGraph:()=>or.refresh(),refreshIdentity:()=>dn.refresh(),renderFooter:dt,renderExtensionWidgets:it,refreshInFlightTools:()=>U.refreshInFlightTools(),pollGit:Vt.pollGit}),ir=umr(yt,x,Pt,{setNotice:Ye,agentDir:()=>ne.state().agentDir,openNodeMetadata:()=>pr("overview"),isDormant:()=>It.isDormant(),copyTarget:Tt,toggleToolsExpanded:()=>U.toggleToolsExpanded(),toggleFoldTools:()=>U.toggleFoldSettledTools(),toggleThinking:()=>U.toggleThinking(),toggleGraph:()=>or.toggle(),toggleInbox:mt.toggleInbox,toggleHelp:()=>Fr.toggle(),toggleMouse:()=>Xt.toggle(),quit:()=>fi("detach"),setChipColor:Vt.setChipColor,onPromptSent:()=>{je.whip_mode&&wt.play()},frecency:pn}),Cs=()=>{if(ft.hasFullPaneSurface()){Ye("Close the active surface before whipping the agent");return}let Mn=je.whip_message_mode==="go-faster"?egr:tgr(je.whip_messages);ir.sendInterrupting(Mn)&&(wt.play(),ogr(b),Ye(`Whipped agent \u2014 ${Mn}`))},Ls=()=>{if(lt.active()){Ye("Close the open request first (Esc)");return}let Mn=U.getTranscriptFilePathsNewestFirst(),Gi=Vn=>{afr(ft,Vn,{originNodeId:t,onNotice:Ye})};if(ft.hasFullPaneSurface()){ft.pickReviewFile({candidates:Mn,cwd:p.cwd,title:"Review a file named in this transcript"}).then(Vn=>{Vn!==null&&Gi(Vn)});return}ir.openFileReviewPicker(Mn,p.cwd,Gi)},br=()=>{if(a){Ye("Profile file search is unavailable on remote canvases");return}if(!jx()){Ye("Profile file search requires tmux");return}u.listNodes().then(Mn=>{Ghr({cwd:p.cwd,nodeDirs:Qhr(Mn,t),nodeIds:v7t(Mn,t),profileId:p.profile_id??null,fdPath:C,onNotice:Ye})}).catch(Mn=>{let Gi=Mn instanceof Error?Mn.message:String(Mn);Ye(`Could not load related node directories: ${Gi}`)})},gr=Zmr(yt,{foldState:ne.fold,chat:U,setNotice:Ye,renderFooter:dt,setEditorText:Mn=>{ze.setText(Mn),R.requestRender()},attachDialog:Mn=>ir.attachDialog(Mn),dismissDialog:Mn=>ir.dismissDialog(Mn),refreshNodeIdentity:dn.refresh,setCommands:Jt.setCommands,resetMemoryRefs:Jt.resetMemoryRefs,reloadBindings:()=>{k=I8t(bH,Mn=>{or.setBindings(Mn),Fr.setBindings(Mn)},jx,g4e),I=k.bindings},modelThinkingLabel:ne.modelThinkingLabel}),xn=Bhr(a,t),Cr=qmr(yt,{stopLocal:()=>{ft.closeAll(),nn.cancel(),Xt.disable(),$i.stop(),lt.close(),bn.dispose(),or.close(),Fr.close(),De.close(),wt.dispose(),xn.clear(),lr(),na(),ea(),ot();try{U.dispose()}catch{}},lastSocketError:()=>It.lastSocketError(),tagPane:xn.pane}),fi=Cr.teardown;It=zmr(yt,{role:_,initialDormant:s.initialSnapshot!==void 0,clientId:m,onFrame:gr,setNotice:Ye,isTornDown:()=>Cr.isTornDown(),teardown:fi,onEnterDormancy:()=>{U.settleRun(),ne.patchLocal({isStreaming:!1})}}),s.assertConnected(),xn.set(),It.install(),We.mount(),R.start(),s.initialSnapshot!==void 0&&(ne.fold({type:"welcome",snapshot:s.initialSnapshot,role:_}),U.applySnapshot(s.initialSnapshot),Jt.setCommands(s.initialCommands)),je.whip_mode&&ct&&wt.play(),Xt.reassert();let Js=!1,Zo=Mn=>{if(Js||a)return;let Gi=p$();if(Gi===null)return;let Vn=lhr({file:Mn,pane:Gi.pane,cwd:p.cwd,nodeId:t,observer:e,beforeRespawn:xn.clear});if(Vn==="opened"){Js=!0;return}Vn==="failed"&&xn.set(),Vn==="missing"&&Ye("File no longer exists"),Vn==="failed"&&Ye("Could not open file in Neovim")};Xt.install(R,{onWheel:(Mn,Gi)=>{Cn.clear()&&R.requestRender(),!ft.handleWheel(Mn,Gi)&&(nn.cancel(),z.scrollBy(Mn==="up"?-Gi:Gi)&&R.requestRender())},onPrimaryPress:(Mn,Gi)=>{ft.hasFullPaneSurface()||(Cn.clear()&&R.requestRender(),Cn.begin(Mn,Gi))},onPrimaryDrag:(Mn,Gi)=>{ft.hasFullPaneSurface()||Cn.extend(Mn,Gi)&&R.requestRender()},onPrimaryRelease:()=>{let Mn=Cn.release();Mn?.kind==="selection"&&(Ye(Mn.notice),R.requestRender())}});let ea=R.addInputListener(Mn=>{let Gi=chr(Mn);if(Gi!==void 0)return Gi.file===void 0?Ye("Could not open file link"):Zo(Gi.file),Gi.remaining.length>0?{data:Gi.remaining}:{consume:!0}}),na=R.addInputListener(()=>{Cn.clear()&&R.requestRender()}),lr=ehr(yt,{bindings:()=>I,detachHint:()=>Rur(I),hasExclusiveSurface:()=>ft.hasFullPaneSurface(),setPaneFocused:Mn=>{Mn&&xn.stamp(),ri.setPaneFocused(Mn),R.requestRender()},viewportActions:()=>Ve,searchHandleKey:De.handleKey,panelHandleKey:lt.handleKey,stripHandleKey:Re.handleKey,rosterHandleKey:oi.handleKey,setNotice:Ye,detach:()=>fi("detach"),cancelTurn:()=>{ir.abortTurn()?Ye("Canceling the agent\u2026"):Ye(`Nothing running to cancel \u2014 press ${Nur(I)??"ctrl+d"} to detach`)},toggleGraph:()=>or.toggle(),toggleHelp:()=>Fr.toggle(),toggleInbox:mt.toggleInbox,toggleInboxStrip:()=>{if(ft.hasFullPaneSurface()){Ye("Close the active surface before opening the request strip");return}lt.active()&&lt.close(),Re.toggle()},cycleModelLadder:Mn=>ir.cycleLadder(Mn),inspectLoadedCommand:Jt.inspectLoadedCommand,openFileReview:Ls,openProfileFiles:br,openSearch:()=>{if(ft.hasFullPaneSurface()||lt.active()){Ye("Close the active surface before searching the transcript");return}De.open()},whip:Cs});Cr.installSignalHandlers(),dt(),$i.refresh(),cr(),Vt.pollGit(),zX("viewer.first_paint"),process.stdout.write(Wmr),Dtr(D.kittyProtocolActive),setImmediate(()=>{I8t(()=>k,()=>{},jx,g4e)}),s.initialSnapshot===void 0?(zX("viewer.hello_sent"),It.sendHello()):It.startDormant(),$i.start(),Qt!==void 0&&rfr(ft,Qt),await Cr.done}export{TFc as runAttach};
2138
2138
  /*! Bundled license information:
2139
2139
 
2140
2140
  web-streams-polyfill/dist/ponyfill.es2018.js: