@north-light/cli 0.3.655 → 0.3.657
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/api/contract.d.ts +1 -1
- package/dist/api/contract.js +1 -1
- package/dist/api/dto/docs.d.ts +6 -3
- package/dist/clients/attach/session/document-links.d.ts +3 -2
- package/dist/clients/attach/session/document-links.js +1 -1
- package/dist/clients/attach/viewer.js +3 -3
- package/dist/core/graph/events.d.ts +1 -1
- package/dist/core/graph/events.js +8 -8
- package/dist/daemon/api/canvas-host.d.ts +9 -0
- package/dist/daemon/api/canvas-host.js +1 -0
- package/dist/daemon/api/document-listener.js +1 -11
- package/dist/daemon/api/document-page.d.ts +18 -0
- package/dist/daemon/api/document-page.js +11 -0
- package/dist/daemon/api/handlers/document-access.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +3 -2
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/doc-editor/editor.js +24 -24
- package/package.json +2 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +13 -13
|
@@ -88,7 +88,7 @@ To prepare for this change:
|
|
|
88
88
|
- If you want libpq compatibility now, use 'uselibpqcompat=true&sslmode=${t}'
|
|
89
89
|
|
|
90
90
|
See https://www.postgresql.org/docs/current/libpq-ssl.html for libpq SSL mode definitions.`))}rJe.exports=aR;aR.parse=aR;aR.toClientConfig=nJe;aR.parseIntoClientConfig=Svn});var Lfe=$((Cli,aJe)=>{"use strict";var Cvn=Z("dns"),sJe=C$(),oJe=iJe().parse,Jc=function(t,e,n){return e[t]?e[t]:(n===void 0?n=process.env["PG"+t.toUpperCase()]:n===!1||(n=process.env[n]),n||sJe[t])},_vn=function(){switch(process.env.PGSSLMODE){case"disable":return!1;case"prefer":case"require":case"verify-ca":case"verify-full":return!0;case"no-verify":return{rejectUnauthorized:!1}}return sJe.ssl},cR=function(t){return"'"+(""+t).replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'"},$d=function(t,e,n){let r=e[n];r!=null&&t.push(n+"="+cR(r))},Bfe=class{constructor(e){if(e=typeof e=="string"?oJe(e):e||{},e.connectionString&&(e=Object.assign({},e,oJe(e.connectionString))),this.user=Jc("user",e),this.database=Jc("database",e),this.database===void 0&&(this.database=this.user),this.port=parseInt(Jc("port",e),10),this.host=Jc("host",e),Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:Jc("password",e)}),this.binary=Jc("binary",e),this.options=Jc("options",e),this.ssl=typeof e.ssl>"u"?_vn():e.ssl,typeof this.ssl=="string"&&this.ssl==="true"&&(this.ssl=!0),this.ssl==="no-verify"&&(this.ssl={rejectUnauthorized:!1}),this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this.sslnegotiation=Jc("sslnegotiation",e,"PGSSLNEGOTIATION"),this.sslnegotiation!==void 0&&this.sslnegotiation!=="postgres"&&this.sslnegotiation!=="direct")throw new Error(`Invalid sslnegotiation value: "${this.sslnegotiation}". Valid values are "postgres" and "direct".`);if(this.sslnegotiation==="direct"&&!this.ssl)throw new Error("sslnegotiation=direct requires SSL to be enabled");this.client_encoding=Jc("client_encoding",e),this.replication=Jc("replication",e),this.isDomainSocket=!(this.host||"").indexOf("/"),this.application_name=Jc("application_name",e,"PGAPPNAME"),this.fallback_application_name=Jc("fallback_application_name",e,!1),this.statement_timeout=Jc("statement_timeout",e,!1),this.lock_timeout=Jc("lock_timeout",e,!1),this.idle_in_transaction_session_timeout=Jc("idle_in_transaction_session_timeout",e,!1),this.query_timeout=Jc("query_timeout",e,!1),e.connectionTimeoutMillis===void 0?this.connect_timeout=process.env.PGCONNECT_TIMEOUT||0:this.connect_timeout=Math.floor(e.connectionTimeoutMillis/1e3),e.keepAlive===!1?this.keepalives=0:e.keepAlive===!0&&(this.keepalives=1),typeof e.keepAliveInitialDelayMillis=="number"&&(this.keepalives_idle=Math.floor(e.keepAliveInitialDelayMillis/1e3))}getLibpqConnectionString(e){let n=[];$d(n,this,"user"),$d(n,this,"password"),$d(n,this,"port"),$d(n,this,"application_name"),$d(n,this,"fallback_application_name"),$d(n,this,"connect_timeout"),$d(n,this,"options");let r=typeof this.ssl=="object"?this.ssl:this.ssl?{sslmode:this.ssl}:{};if($d(n,r,"sslmode"),$d(n,r,"sslca"),$d(n,r,"sslkey"),$d(n,r,"sslcert"),$d(n,r,"sslrootcert"),$d(n,this,"sslnegotiation"),this.database&&n.push("dbname="+cR(this.database)),this.replication&&n.push("replication="+cR(this.replication)),this.host&&n.push("host="+cR(this.host)),this.isDomainSocket)return e(null,n.join(" "));this.client_encoding&&n.push("client_encoding="+cR(this.client_encoding)),Cvn.lookup(this.host,function(i,o){return i?e(i,null):(n.push("hostaddr="+cR(o)),e(null,n.join(" ")))})}};aJe.exports=Bfe});var Nfe=$((_li,uJe)=>{"use strict";var Ivn=S$(),cJe=/^([A-Za-z]+)(?: (\d+))?(?: (\d+))?/,Ofe=class{constructor(e,n){this.command=null,this.rowCount=null,this.oid=null,this.rows=[],this.fields=[],this._parsers=void 0,this._types=n,this.RowCtor=null,this.rowAsArray=e==="array",this.rowAsArray&&(this.parseRow=this._parseRowAsArray),this._prebuiltEmptyResultObject=null}addCommandComplete(e){let n;e.text?n=cJe.exec(e.text):n=cJe.exec(e.command),n&&(this.command=n[1],n[3]?(this.oid=parseInt(n[2],10),this.rowCount=parseInt(n[3],10)):n[2]&&(this.rowCount=parseInt(n[2],10)))}_parseRowAsArray(e){let n=new Array(e.length);for(let r=0,i=e.length;r<i;r++){let o=e[r];o!==null?n[r]=this._parsers[r](o):n[r]=null}return n}parseRow(e){let n={...this._prebuiltEmptyResultObject};for(let r=0,i=e.length;r<i;r++){let o=e[r],s=this.fields[r].name;if(o!==null){let a=this.fields[r].format==="binary"?Buffer.from(o):o;n[s]=this._parsers[r](a)}else n[s]=null}return n}addRow(e){this.rows.push(e)}addFields(e){this.fields=e,this.fields.length&&(this._parsers=new Array(e.length));let n=Object.create(null);for(let r=0;r<e.length;r++){let i=e[r];n[i.name]=null,this._types?this._parsers[r]=this._types.getTypeParser(i.dataTypeID,i.format||"text"):this._parsers[r]=Ivn.getTypeParser(i.dataTypeID,i.format||"text")}this._prebuiltEmptyResultObject={...n}}};uJe.exports=Ofe});var hJe=$((Ili,pJe)=>{"use strict";var{EventEmitter:kvn}=Z("events"),lJe=Nfe(),dJe=hS(),$fe=class extends kvn{constructor(e,n,r){super(),e=dJe.normalizeQueryConfig(e,n,r),this.text=e.text,this.values=e.values,this.rows=e.rows,this.types=e.types,this.name=e.name,this.queryMode=e.queryMode,this.binary=e.binary,this.portal=e.portal||"",this.callback=e.callback,this._rowMode=e.rowMode,process.domain&&e.callback&&(this.callback=process.domain.bind(e.callback)),this._result=new lJe(this._rowMode,this.types),this._results=this._result,this._canceledDueToError=!1}requiresPreparation(){return this.queryMode==="extended"||this.name||this.rows?!0:!this.text||!this.values?!1:this.values.length>0}_checkForMultirow(){this._result.command&&(Array.isArray(this._results)||(this._results=[this._result]),this._result=new lJe(this._rowMode,this._result._types),this._results.push(this._result))}handleRowDescription(e){this._checkForMultirow(),this._result.addFields(e.fields),this._accumulateRows=this.callback||!this.listeners("row").length}handleDataRow(e){let n;if(!this._canceledDueToError){try{n=this._result.parseRow(e.fields)}catch(r){this._canceledDueToError=r;return}this.emit("row",n,this._result),this._accumulateRows&&this._result.addRow(n)}}handleCommandComplete(e,n){this._checkForMultirow(),this._result.addCommandComplete(e),this.rows&&n.sync()}handleEmptyQuery(e){this.rows&&e.sync()}handleError(e,n){if(this._canceledDueToError&&(e=this._canceledDueToError,this._canceledDueToError=!1),this.callback)return this.callback(e);this.emit("error",e)}handleReadyForQuery(e){if(this._canceledDueToError)return this.handleError(this._canceledDueToError,e);if(this.callback)try{this.callback(null,this._results)}catch(n){process.nextTick(()=>{throw n})}this.emit("end",this._results)}submit(e){if(typeof this.text!="string"&&typeof this.name!="string")return new Error("A query must have either text or a name. Supplying neither is unsupported.");let n=e.parsedStatements[this.name]||e.submittedNamedStatements[this.name];if(this.text&&n&&this.text!==n)return new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);if(this.values&&!Array.isArray(this.values))return new Error("Query values must be an array");if(this.requiresPreparation()){e.stream.cork&&e.stream.cork();try{this.prepare(e)}finally{e.stream.uncork&&e.stream.uncork()}}else e.query(this.text);return null}hasBeenParsed(e){return this.name&&(e.parsedStatements[this.name]!==void 0||e.submittedNamedStatements[this.name]!==void 0)}handlePortalSuspended(e){this._getRows(e,this.rows)}_getRows(e,n){e.execute({portal:this.portal,rows:n}),n?e.flush():e.sync()}prepare(e){this.hasBeenParsed(e)||(e.parse({text:this.text,name:this.name,types:this.types}),this.name&&(e.submittedNamedStatements[this.name]=this.text));try{e.bind({portal:this.portal,statement:this.name,values:this.values,binary:this.binary,valueMapper:dJe.prepareValue})}catch(n){e.close({type:"S",name:this.name}),e.sync(),this.handleError(n,e);return}e.describe({type:"P",name:this.portal||""}),this._getRows(e,this.rows)}handleCopyInResponse(e){e.sendCopyFail("No source stream defined")}handleCopyData(e,n){}};pJe.exports=$fe});var Zfe=$(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.NoticeMessage=Fn.DataRowMessage=Fn.CommandCompleteMessage=Fn.ReadyForQueryMessage=Fn.NotificationResponseMessage=Fn.BackendKeyDataMessage=Fn.AuthenticationMD5Password=Fn.ParameterStatusMessage=Fn.ParameterDescriptionMessage=Fn.RowDescriptionMessage=Fn.Field=Fn.CopyResponse=Fn.CopyDataMessage=Fn.DatabaseError=Fn.copyDone=Fn.emptyQuery=Fn.replicationStart=Fn.portalSuspended=Fn.noData=Fn.closeComplete=Fn.bindComplete=Fn.parseComplete=void 0;Fn.parseComplete={name:"parseComplete",length:5};Fn.bindComplete={name:"bindComplete",length:5};Fn.closeComplete={name:"closeComplete",length:5};Fn.noData={name:"noData",length:5};Fn.portalSuspended={name:"portalSuspended",length:5};Fn.replicationStart={name:"replicationStart",length:4};Fn.emptyQuery={name:"emptyQuery",length:4};Fn.copyDone={name:"copyDone",length:4};var Ffe=class extends Error{constructor(e,n,r){super(e),this.length=n,this.name=r}};Fn.DatabaseError=Ffe;var Ufe=class{constructor(e,n){this.length=e,this.chunk=n,this.name="copyData"}};Fn.CopyDataMessage=Ufe;var Qfe=class{constructor(e,n,r,i){this.length=e,this.name=n,this.binary=r,this.columnTypes=new Array(i)}};Fn.CopyResponse=Qfe;var Wfe=class{constructor(e,n,r,i,o,s,a){this.name=e,this.tableID=n,this.columnID=r,this.dataTypeID=i,this.dataTypeSize=o,this.dataTypeModifier=s,this.format=a}};Fn.Field=Wfe;var Hfe=class{constructor(e,n){this.length=e,this.fieldCount=n,this.name="rowDescription",this.fields=new Array(this.fieldCount)}};Fn.RowDescriptionMessage=Hfe;var qfe=class{constructor(e,n){this.length=e,this.parameterCount=n,this.name="parameterDescription",this.dataTypeIDs=new Array(this.parameterCount)}};Fn.ParameterDescriptionMessage=qfe;var Gfe=class{constructor(e,n,r){this.length=e,this.parameterName=n,this.parameterValue=r,this.name="parameterStatus"}};Fn.ParameterStatusMessage=Gfe;var jfe=class{constructor(e,n){this.length=e,this.salt=n,this.name="authenticationMD5Password"}};Fn.AuthenticationMD5Password=jfe;var zfe=class{constructor(e,n,r){this.length=e,this.processID=n,this.secretKey=r,this.name="backendKeyData"}};Fn.BackendKeyDataMessage=zfe;var Vfe=class{constructor(e,n,r,i){this.length=e,this.processId=n,this.channel=r,this.payload=i,this.name="notification"}};Fn.NotificationResponseMessage=Vfe;var Kfe=class{constructor(e,n){this.length=e,this.status=n,this.name="readyForQuery"}};Fn.ReadyForQueryMessage=Kfe;var Yfe=class{constructor(e,n){this.length=e,this.text=n,this.name="commandComplete"}};Fn.CommandCompleteMessage=Yfe;var Jfe=class{constructor(e,n){this.length=e,this.fields=n,this.name="dataRow",this.fieldCount=n.length}};Fn.DataRowMessage=Jfe;var Xfe=class{constructor(e,n){this.length=e,this.message=n,this.name="notice"}};Fn.NoticeMessage=Xfe});var fJe=$(tz=>{"use strict";Object.defineProperty(tz,"__esModule",{value:!0});tz.Writer=void 0;var eme=class{constructor(e=256){this.size=e,this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(e)}ensure(e){if(this.buffer.length-this.offset<e){let r=this.buffer,i=r.length+(r.length>>1)+e;this.buffer=Buffer.allocUnsafe(i),r.copy(this.buffer,0,0,this.offset)}}addInt32(e){return this.ensure(4),this.buffer[this.offset++]=e>>>24&255,this.buffer[this.offset++]=e>>>16&255,this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addInt16(e){return this.ensure(2),this.buffer[this.offset++]=e>>>8&255,this.buffer[this.offset++]=e>>>0&255,this}addCString(e){if(!e)this.ensure(1);else{let n=Buffer.byteLength(e);this.ensure(n+1),this.buffer.write(e,this.offset,"utf-8"),this.offset+=n}return this.buffer[this.offset++]=0,this}addString(e=""){let n=Buffer.byteLength(e);return this.ensure(n),this.buffer.write(e,this.offset),this.offset+=n,this}addInt32PrefixedString(e){let n=Buffer.byteLength(e);this.ensure(4+n);let r=this.buffer,i=this.offset;return r[i++]=n>>>24&255,r[i++]=n>>>16&255,r[i++]=n>>>8&255,r[i++]=n>>>0&255,r.write(e,i,"utf-8"),this.offset=i+n,this}add(e){return this.ensure(e.length),e.copy(this.buffer,this.offset),this.offset+=e.length,this}reserveUnsafe(e){let n=this.offset;return this.ensure(e),this.offset+=e,n}join(e){if(e){this.buffer[this.headerPosition]=e;let n=this.offset-(this.headerPosition+1);this.buffer.writeInt32BE(n,this.headerPosition+1)}return this.buffer.slice(e?0:5,this.offset)}flush(e){let n=this.join(e);return this.offset=5,this.headerPosition=0,this.buffer=Buffer.allocUnsafe(this.size),n}clear(){this.offset=5,this.headerPosition=0}};tz.Writer=eme});var yJe=$(rz=>{"use strict";Object.defineProperty(rz,"__esModule",{value:!0});rz.serialize=void 0;var mJe=fJe(),Ui=new mJe.Writer,Tvn=t=>{Ui.addInt16(3).addInt16(0);for(let r of Object.keys(t))Ui.addCString(r).addCString(t[r]);Ui.addCString("client_encoding").addCString("UTF8");let e=Ui.addCString("").flush(),n=e.length+4;return new mJe.Writer().addInt32(n).add(e).flush()},Rvn=()=>{let t=Buffer.allocUnsafe(8);return t.writeInt32BE(8,0),t.writeInt32BE(80877103,4),t},Mvn=t=>Ui.addCString(t).flush(112),Pvn=function(t,e){return Ui.addCString(t).addInt32PrefixedString(e),Ui.flush(112)},Dvn=function(t){return Ui.addString(t).flush(112)},Bvn=t=>Ui.addCString(t).flush(81),gJe=[],Lvn=t=>{let e=t.name||"";e.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",e,e.length),console.error("This can cause conflicts and silent errors executing queries"));let n=t.types||gJe,r=n.length,i=Ui.addCString(e).addCString(t.text).addInt16(r);for(let o=0;o<r;o++)i.addInt32(n[o]);return Ui.flush(80)},Ovn=function(t,e,n){let r=t.length;for(let i=0;i<r;i++){let o=e?e(t[i],i):t[i],s=0;o==null?Ui.addInt32(-1):o instanceof Buffer?(s=1,Ui.addInt32(o.length),Ui.add(o)):Ui.addInt32PrefixedString(o);let a=Ui.buffer;a[n++]=0,a[n++]=s}},Nvn=(t={})=>{let e=t.portal||"",n=t.statement||"",r=t.binary||!1,i=t.values||gJe,o=i.length;Ui.addCString(e).addCString(n),Ui.addInt16(o);let s=Ui.reserveUnsafe(o*2);Ui.addInt16(o);try{Ovn(i,t.valueMapper,s)}catch(a){throw Ui.clear(),a}return Ui.addInt16(1),Ui.addInt16(r?1:0),Ui.flush(66)},$vn=Buffer.from([69,0,0,0,9,0,0,0,0,0]),Fvn=t=>{if(!t||!t.portal&&!t.rows)return $vn;let e=t.portal||"",n=t.rows||0,r=Buffer.byteLength(e),i=4+r+1+4,o=Buffer.allocUnsafe(1+i);return o[0]=69,o.writeInt32BE(i,1),o.write(e,5,"utf-8"),o[r+5]=0,o.writeUInt32BE(n,o.length-4),o},Uvn=(t,e)=>{let n=Buffer.allocUnsafe(16);return n.writeInt32BE(16,0),n.writeInt16BE(1234,4),n.writeInt16BE(5678,6),n.writeInt32BE(t,8),n.writeInt32BE(e,12),n},tme=(t,e)=>{let r=4+Buffer.byteLength(e)+1,i=Buffer.allocUnsafe(1+r);return i[0]=t,i.writeInt32BE(r,1),i.write(e,5,"utf-8"),i[r]=0,i},Qvn=Ui.addCString("P").flush(68),Wvn=Ui.addCString("S").flush(68),Hvn=t=>t.name?tme(68,`${t.type}${t.name||""}`):t.type==="P"?Qvn:Wvn,qvn=t=>{let e=`${t.type}${t.name||""}`;return tme(67,e)},Gvn=t=>Ui.add(t).flush(100),jvn=t=>tme(102,t),nz=t=>Buffer.from([t,0,0,0,4]),zvn=nz(72),Vvn=nz(83),Kvn=nz(88),Yvn=nz(99),Jvn={startup:Tvn,password:Mvn,requestSsl:Rvn,sendSASLInitialResponseMessage:Pvn,sendSCRAMClientFinalMessage:Dvn,query:Bvn,parse:Lvn,bind:Nvn,execute:Fvn,describe:Hvn,close:qvn,flush:()=>zvn,sync:()=>Vvn,end:()=>Kvn,copyData:Gvn,copyDone:()=>Yvn,copyFail:jvn,cancel:Uvn};rz.serialize=Jvn});var AJe=$(iz=>{"use strict";Object.defineProperty(iz,"__esModule",{value:!0});iz.BufferReader=void 0;var nme=class{constructor(e=0){this.offset=e,this.buffer=Buffer.allocUnsafe(0),this.encoding="utf-8"}setBuffer(e,n){this.offset=e,this.buffer=n}int16(){let e=this.buffer.readInt16BE(this.offset);return this.offset+=2,e}byte(){let e=this.buffer[this.offset];return this.offset++,e}int32(){let e=this.buffer.readInt32BE(this.offset);return this.offset+=4,e}uint32(){let e=this.buffer.readUInt32BE(this.offset);return this.offset+=4,e}string(e){let n=this.buffer.toString(this.encoding,this.offset,this.offset+e);return this.offset+=e,n}cstring(){let e=this.offset,n=e;for(;this.buffer[n++];);return this.offset=n,this.buffer.toString(this.encoding,e,n-1)}bytes(e){let n=this.buffer.slice(this.offset,this.offset+e);return this.offset+=e,n}};iz.BufferReader=nme});var vJe=$(oz=>{"use strict";Object.defineProperty(oz,"__esModule",{value:!0});oz.Parser=void 0;var Jo=Zfe(),Xvn=AJe(),ime=1,Zvn=4,xJe=ime+Zvn,Fd=-1,rme=Buffer.allocUnsafe(0),ome=class{constructor(e){if(this.buffer=rme,this.bufferLength=0,this.bufferOffset=0,this.reader=new Xvn.BufferReader,e?.mode==="binary")throw new Error("Binary mode not supported yet");this.mode=e?.mode||"text"}parse(e,n){this.mergeBuffer(e);let r=this.bufferOffset+this.bufferLength,i=this.bufferOffset;for(;i+xJe<=r;){let o=this.buffer[i],s=this.buffer.readUInt32BE(i+ime),a=ime+s;if(a+i<=r){let c=this.handlePacket(i+xJe,o,s,this.buffer);n(c),i+=a}else break}i===r?(this.buffer=rme,this.bufferLength=0,this.bufferOffset=0):(this.bufferLength=r-i,this.bufferOffset=i)}mergeBuffer(e){if(this.bufferLength>0){let n=this.bufferLength+e.byteLength;if(n+this.bufferOffset>this.buffer.byteLength){let i;if(n<=this.buffer.byteLength&&this.bufferOffset>=this.bufferLength)i=this.buffer;else{let o=this.buffer.byteLength*2;for(;n>=o;)o*=2;i=Buffer.allocUnsafe(o)}this.buffer.copy(i,0,this.bufferOffset,this.bufferOffset+this.bufferLength),this.buffer=i,this.bufferOffset=0}e.copy(this.buffer,this.bufferOffset+this.bufferLength),this.bufferLength=n}else this.buffer=e,this.bufferOffset=0,this.bufferLength=e.byteLength}handlePacket(e,n,r,i){let{reader:o}=this;o.setBuffer(e,i);let s;switch(n){case 50:s=Jo.bindComplete;break;case 49:s=Jo.parseComplete;break;case 51:s=Jo.closeComplete;break;case 110:s=Jo.noData;break;case 115:s=Jo.portalSuspended;break;case 99:s=Jo.copyDone;break;case 87:s=Jo.replicationStart;break;case 73:s=Jo.emptyQuery;break;case 68:s=uEn(o);break;case 67:s=tEn(o);break;case 90:s=eEn(o);break;case 65:s=oEn(o);break;case 82:s=pEn(o,r);break;case 83:s=lEn(o);break;case 75:s=dEn(o);break;case 69:s=wJe(o,"error");break;case 78:s=wJe(o,"notice");break;case 84:s=sEn(o);break;case 116:s=cEn(o);break;case 71:s=rEn(o);break;case 72:s=iEn(o);break;case 100:s=nEn(o,r);break;default:return new Jo.DatabaseError("received invalid response: "+n.toString(16),r,"error")}return o.setBuffer(0,rme),s.length=r,s}};oz.Parser=ome;var eEn=t=>{let e=t.string(1);return new Jo.ReadyForQueryMessage(Fd,e)},tEn=t=>{let e=t.cstring();return new Jo.CommandCompleteMessage(Fd,e)},nEn=(t,e)=>{let n=t.bytes(e-4);return new Jo.CopyDataMessage(Fd,n)},rEn=t=>bJe(t,"copyInResponse"),iEn=t=>bJe(t,"copyOutResponse"),bJe=(t,e)=>{let n=t.byte()!==0,r=t.int16(),i=new Jo.CopyResponse(Fd,e,n,r);for(let o=0;o<r;o++)i.columnTypes[o]=t.int16();return i},oEn=t=>{let e=t.int32(),n=t.cstring(),r=t.cstring();return new Jo.NotificationResponseMessage(Fd,e,n,r)},sEn=t=>{let e=t.int16(),n=new Jo.RowDescriptionMessage(Fd,e);for(let r=0;r<e;r++)n.fields[r]=aEn(t);return n},aEn=t=>{let e=t.cstring(),n=t.uint32(),r=t.int16(),i=t.uint32(),o=t.int16(),s=t.int32(),a=t.int16()===0?"text":"binary";return new Jo.Field(e,n,r,i,o,s,a)},cEn=t=>{let e=t.int16(),n=new Jo.ParameterDescriptionMessage(Fd,e);for(let r=0;r<e;r++)n.dataTypeIDs[r]=t.uint32();return n},uEn=t=>{let e=t.int16(),n=new Array(e);for(let r=0;r<e;r++){let i=t.int32();n[r]=i===-1?null:t.string(i)}return new Jo.DataRowMessage(Fd,n)},lEn=t=>{let e=t.cstring(),n=t.cstring();return new Jo.ParameterStatusMessage(Fd,e,n)},dEn=t=>{let e=t.int32(),n=t.int32();return new Jo.BackendKeyDataMessage(Fd,e,n)},pEn=(t,e)=>{let n=t.int32(),r={name:"authenticationOk",length:e};switch(n){case 0:break;case 3:r.length===8&&(r.name="authenticationCleartextPassword");break;case 5:if(r.length===12){r.name="authenticationMD5Password";let i=t.bytes(4);return new Jo.AuthenticationMD5Password(Fd,i)}break;case 10:{r.name="authenticationSASL",r.mechanisms=[];let i;do i=t.cstring(),i&&r.mechanisms.push(i);while(i)}break;case 11:r.name="authenticationSASLContinue",r.data=t.string(e-8);break;case 12:r.name="authenticationSASLFinal",r.data=t.string(e-8);break;default:throw new Error("Unknown authenticationOk message type "+n)}return r},wJe=(t,e)=>{let n={},r=t.string(1);for(;r!=="\0";)n[r]=t.cstring(),r=t.string(1);let i=n.M,o=e==="notice"?new Jo.NoticeMessage(Fd,i):new Jo.DatabaseError(i,Fd,e);return o.severity=n.S,o.code=n.C,o.detail=n.D,o.hint=n.H,o.position=n.P,o.internalPosition=n.p,o.internalQuery=n.q,o.where=n.W,o.schema=n.s,o.table=n.t,o.column=n.c,o.dataType=n.d,o.constraint=n.n,o.file=n.F,o.line=n.L,o.routine=n.R,o}});var sme=$(gS=>{"use strict";Object.defineProperty(gS,"__esModule",{value:!0});gS.DatabaseError=gS.serialize=void 0;gS.parse=gEn;var hEn=Zfe();Object.defineProperty(gS,"DatabaseError",{enumerable:!0,get:function(){return hEn.DatabaseError}});var fEn=yJe();Object.defineProperty(gS,"serialize",{enumerable:!0,get:function(){return fEn.serialize}});var mEn=vJe();function gEn(t,e){let n=new mEn.Parser;return t.on("data",r=>n.parse(r,e)),new Promise(r=>t.on("end",()=>r()))}});var EJe=$(ame=>{"use strict";Object.defineProperty(ame,"__esModule",{value:!0});ame.default={}});var CJe=$((Lli,SJe)=>{var{getStream:yEn,getSecureStream:AEn}=vEn();SJe.exports={getStream:yEn,getSecureStream:AEn};function xEn(){function t(n){let r=Z("net");return new r.Socket}function e(n){return Z("tls").connect(n)}return{getStream:t,getSecureStream:e}}function wEn(){function t(n){let{CloudflareSocket:r}=EJe();return new r(n)}function e(n){return n.socket.startTls(n),n.socket}return{getStream:t,getSecureStream:e}}function bEn(){if(typeof navigator=="object"&&navigator!==null&&typeof navigator.userAgent=="string")return navigator.userAgent==="Cloudflare-Workers";if(typeof Response=="function"){let t=new Response(null,{cf:{thing:!0}});if(typeof t.cf=="object"&&t.cf!==null&&t.cf.thing)return!0}return!1}function vEn(){return bEn()?wEn():xEn()}});var ume=$((Oli,IJe)=>{"use strict";var EEn=Z("events").EventEmitter,{parse:SEn,serialize:Qa}=sme(),_Je=CJe(),{getStream:CEn}=_Je,_En=Qa.flush(),IEn=Qa.sync(),kEn=Qa.end(),cme=class extends EEn{constructor(e){super(),e=e||{},this.stream=e.stream||CEn(e.ssl),typeof this.stream=="function"&&(this.stream=this.stream(e)),this._keepAlive=e.keepAlive,this._keepAliveInitialDelayMillis=e.keepAliveInitialDelayMillis,this.parsedStatements={},this.submittedNamedStatements={},this.ssl=e.ssl||!1,this.sslNegotiation=e.sslNegotiation||"postgres",this._ending=!1,this._emitMessage=!1;let n=this;this.on("newListener",function(r){r==="message"&&(n._emitMessage=!0)})}connect(e,n){let r=this;this._connecting=!0,this.stream.setNoDelay(!0),this.stream.connect(e,n),this.stream.once("connect",function(){r._keepAlive&&r.stream.setKeepAlive(!0,r._keepAliveInitialDelayMillis),r.emit("connect")});let i=function(o){r._ending&&(o.code==="ECONNRESET"||o.code==="EPIPE")||r.emit("error",o)};if(this.stream.on("error",i),this.stream.on("close",function(){r.emit("end")}),!this.ssl)return this.attachListeners(this.stream);if(this.sslNegotiation==="direct")return this.stream.once("connect",function(){r.upgradeToSSL(n,i)});this.stream.once("data",function(o){switch(o.toString("utf8")){case"S":break;case"N":return r.stream.end(),r.emit("error",new Error("The server does not support SSL connections"));default:return r.stream.end(),r.emit("error",new Error("There was an error establishing an SSL connection"))}r.upgradeToSSL(n,i)})}upgradeToSSL(e,n){let r=this,i={socket:r.stream,host:e};r.ssl!==!0&&(Object.assign(i,r.ssl),"key"in r.ssl&&(i.key=r.ssl.key)),r.sslNegotiation==="direct"&&(i.ALPNProtocols=["postgresql"]);let o=Z("net");o.isIP&&o.isIP(e)===0&&(i.servername=e);try{r.stream=_Je.getSecureStream(i)}catch(s){return r.emit("error",s)}r.attachListeners(r.stream),r.stream.on("error",n),r.emit("sslconnect")}attachListeners(e){SEn(e,n=>{let r=n.name==="error"?"errorMessage":n.name;this._emitMessage&&this.emit("message",n),this.emit(r,n)})}requestSsl(){this.stream.write(Qa.requestSsl())}startup(e){this.stream.write(Qa.startup(e))}cancel(e,n){this._send(Qa.cancel(e,n))}password(e){this._send(Qa.password(e))}sendSASLInitialResponseMessage(e,n){this._send(Qa.sendSASLInitialResponseMessage(e,n))}sendSCRAMClientFinalMessage(e){this._send(Qa.sendSCRAMClientFinalMessage(e))}_send(e){return this.stream.writable?this.stream.write(e):!1}query(e){this._send(Qa.query(e))}parse(e){this._send(Qa.parse(e))}bind(e){this._send(Qa.bind(e))}execute(e){this._send(Qa.execute(e))}flush(){this.stream.writable&&this.stream.write(_En)}sync(){this._send(IEn)}ref(){this.stream.ref()}unref(){this.stream.unref()}end(){if(this._ending=!0,!this._connecting||!this.stream.writable){this.stream.end();return}return this.stream.write(kEn,()=>{this.stream.end()})}close(e){this._send(Qa.close(e))}describe(e){this._send(Qa.describe(e))}sendCopyFromChunk(e){this._send(Qa.copyData(e))}endCopyFrom(){this._send(Qa.copyDone())}sendCopyFail(e){this._send(Qa.copyFail(e))}};IJe.exports=cme});var MJe=$((Nli,RJe)=>{"use strict";var{Transform:TEn}=Z("stream"),{StringDecoder:REn}=Z("string_decoder"),Ux=Symbol("last"),sz=Symbol("decoder");function MEn(t,e,n){let r;if(this.overflow){if(r=this[sz].write(t).split(this.matcher),r.length===1)return n();r.shift(),this.overflow=!1}else this[Ux]+=this[sz].write(t),r=this[Ux].split(this.matcher);this[Ux]=r.pop();for(let i=0;i<r.length;i++)try{TJe(this,this.mapper(r[i]))}catch(o){return n(o)}if(this.overflow=this[Ux].length>this.maxLength,this.overflow&&!this.skipOverflow){n(new Error("maximum buffer reached"));return}n()}function PEn(t){if(this[Ux]+=this[sz].end(),this[Ux])try{TJe(this,this.mapper(this[Ux]))}catch(e){return t(e)}t()}function TJe(t,e){e!==void 0&&t.push(e)}function kJe(t){return t}function DEn(t,e,n){switch(t=t||/\r?\n/,e=e||kJe,n=n||{},arguments.length){case 1:typeof t=="function"?(e=t,t=/\r?\n/):typeof t=="object"&&!(t instanceof RegExp)&&!t[Symbol.split]&&(n=t,t=/\r?\n/);break;case 2:typeof t=="function"?(n=e,e=t,t=/\r?\n/):typeof e=="object"&&(n=e,e=kJe)}n=Object.assign({},n),n.autoDestroy=!0,n.transform=MEn,n.flush=PEn,n.readableObjectMode=!0;let r=new TEn(n);return r[Ux]="",r[sz]=new REn("utf8"),r.matcher=t,r.mapper=e,r.maxLength=n.maxLength,r.skipOverflow=n.skipOverflow||!1,r.overflow=!1,r._destroy=function(i,o){this._writableState.errorEmitted=!1,o(i)},r}RJe.exports=DEn});var BJe=$(($li,wA)=>{"use strict";var PJe=Z("path"),BEn=Z("stream").Stream,LEn=MJe(),DJe=Z("util"),OEn=5432,az=process.platform==="win32",I$=process.stderr,NEn=56,$En=7,FEn=61440,UEn=32768;function QEn(t){return(t&FEn)==UEn}var uR=["host","port","database","user","password"],lme=uR.length,WEn=uR[lme-1];function dme(){var t=I$ instanceof BEn&&I$.writable===!0;if(t){var e=Array.prototype.slice.call(arguments).concat(`
|
|
91
|
-
`);I$.write(DJe.format.apply(DJe,e))}}Object.defineProperty(wA.exports,"isWin",{get:function(){return az},set:function(t){az=t}});wA.exports.warnTo=function(t){var e=I$;return I$=t,e};wA.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(az?PJe.join(e.APPDATA||"./","postgresql","pgpass.conf"):PJe.join(e.HOME||"./",".pgpass"));return n};wA.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:az?!0:(e=e||"<unkn>",QEn(t.mode)?t.mode&(NEn|$En)?(dme('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(dme('WARNING: password file "%s" is not a plain file',e),!1))};var HEn=wA.exports.match=function(t,e){return uR.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||OEn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};wA.exports.getPassword=function(t,e,n){var r,i=e.pipe(LEn());function o(c){var u=qEn(c);u&&GEn(u)&&HEn(t,u)&&(r=u[WEn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),dme("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var qEn=wA.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[uR[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==lme-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===lme?s:null,s},GEn=wA.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<uR.length;n+=1){var r=e[n],i=t[uR[n]]||"",o=r(i);if(!o)return!1}return!0}});var OJe=$((Uli,pme)=>{"use strict";var Fli=Z("path"),LJe=Z("fs"),cz=BJe();pme.exports=function(t,e){var n=cz.getFileName();LJe.stat(n,function(r,i){if(r||!cz.usePgPass(i,n))return e(void 0);var o=LJe.createReadStream(n);cz.getPassword(t,o,e)})};pme.exports.warnTo=cz.warnTo});var UJe=$((Qli,FJe)=>{var jEn=Z("events").EventEmitter,NJe=hS(),k$=Z("util"),uz=eJe(),zEn=ez(),VEn=Lfe(),hme=hJe(),KEn=C$(),YEn=ume(),JEn=Rfe(),$Je=k$.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),XEn=k$.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),ZEn=k$.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),eSn=k$.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),tSn=k$.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");function nSn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var lz=class extends jEn{constructor(e){super(),this.connectionParameters=new VEn(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let n=e||{};n.Promise&&eSn(),this._Promise=n.Promise||global.Promise,this._types=new zEn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=nSn(n.scramMaxIterations,uz.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new YEn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||KEn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return $Je(),this._activeQuery}set activeQuery(e){$Je(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{OJe()(this.connectionParameters,i=>{i!==void 0&&(ZEn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await JEn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=uz.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await uz.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{uz.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return NJe.escapeIdentifier(e)}escapeLiteral(e){return NJe.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new hme(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof hme)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&tSn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return XEn(),this._queryQueue}};lz.Query=hme;FJe.exports=lz});var HJe=$((Wli,WJe)=>{"use strict";var rSn=Z("events").EventEmitter,fme=function(){},QJe=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},mme=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},lR=class{constructor(e){this.callback=e}};function iSn(){throw new Error("Release called on client which has already been released to the pool.")}function dz(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function oSn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var gme=class extends rSn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||n||yme().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=QJe(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=dz(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new lR(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new lR(i),s=setTimeout(()=>{QJe(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new lR(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=oSn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,fme);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,fme)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new lR((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,fme);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&iSn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new mme(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=dz(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=dz(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=dz(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};WJe.exports=gme});var jJe=$((Hli,GJe)=>{"use strict";var qJe=Z("events").EventEmitter,sSn=Z("util"),Ame=hS(),dR=GJe.exports=function(t,e,n){qJe.call(this),t=Ame.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};sSn.inherits(dR,qJe);var aSn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};dR.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=aSn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};dR.prototype.then=function(t,e){return this._getPromise().then(t,e)};dR.prototype.catch=function(t){return this._getPromise().catch(t)};dR.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};dR.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let r=(this.values||[]).map(Ame.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(Ame.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var JJe=$((qli,YJe)=>{var cSn=Z("util"),zJe;try{zJe=Z("pg-native")}catch(t){throw t}var uSn=ez(),VJe=Z("events").EventEmitter,lSn=Z("util"),dSn=Lfe(),KJe=jJe(),pSn=cSn.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),xc=YJe.exports=function(t){VJe.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new uSn(t.types),this.native=new zJe({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new dSn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};xc.Query=KJe;lSn.inherits(xc,VJe);xc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};xc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};xc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};xc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new KJe(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&pSn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};xc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};xc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};xc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};xc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=hS();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};xc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};xc.prototype.ref=function(){};xc.prototype.unref=function(){};xc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};xc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};xc.prototype.isConnected=function(){return this._connected};xc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var xme=$((Gli,XJe)=>{"use strict";XJe.exports=JJe()});var yme=$((zli,pz)=>{"use strict";var hSn=UJe(),fSn=C$(),mSn=ume(),gSn=Nfe(),ySn=hS(),ASn=HJe(),xSn=ez(),{DatabaseError:wSn}=sme(),{escapeIdentifier:bSn,escapeLiteral:vSn}=hS(),ESn=t=>class extends ASn{constructor(n){super(n,t)}},ZJe=function(t){this.defaults=fSn,this.Client=t,this.Query=this.Client.Query,this.Pool=ESn(this.Client),this._pools=[],this.Connection=mSn,this.types=S$(),this.DatabaseError=wSn,this.TypeOverrides=xSn,this.escapeIdentifier=bSn,this.escapeLiteral=vSn,this.Result=gSn,this.utils=ySn},eXe=hSn,tXe=!1;try{tXe=!!process.env.NODE_PG_FORCE_NATIVE}catch{}tXe&&(eXe=xme());pz.exports=new ZJe(eXe);Object.defineProperty(pz.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new ZJe(xme())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(pz.exports,"native",{value:t}),t}})});var Ud,Vli,Kli,Yli,Jli,Xli,Zli,edi,tdi,ndi,rdi,idi,nXe,rXe=x(()=>{Ud=sn(yme(),1),Vli=Ud.default.Client,Kli=Ud.default.Pool,Yli=Ud.default.Connection,Jli=Ud.default.types,Xli=Ud.default.Query,Zli=Ud.default.DatabaseError,edi=Ud.default.escapeIdentifier,tdi=Ud.default.escapeLiteral,ndi=Ud.default.Result,rdi=Ud.default.TypeOverrides,idi=Ud.default.defaults,nXe=Ud.default});var SSn,CSn,wme,adi,iXe=x(()=>{"use strict";rXe();SSn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call"],CSn=new Set(SSn),wme=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new nXe.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);CSn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},adi=new wme});var oXe=x(()=>{"use strict";A$()});function RSn(t){switch(t){case kSn:return"context-nudge";case _Sn:return"bearings";case TSn:return"review-boundary";case ISn:return"situational";default:return}}function vme(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&":"&","<":"<",">":">",""":'"',"'":"'"})[e])}function bme(t){let e={};hz.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){hz.lastIndex=n;let r=hz.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=vme(o??s??""),n=hz.lastIndex}return e}function Eme(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function MSn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=bme(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=bme(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:vme(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function PSn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function lXe(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=bme(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?vme(r):r;return PSn(i,s,a,i==="inbox"?MSn(a):[])}function pR(t){let e=Eme(t),n=lXe(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=RSn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function yS(t){return t.disposition==="human-answer"&&lXe(t.body.trim())===null}var _Sn,ISn,kSn,TSn,sXe,aXe,cXe,uXe,hz,AS=x(()=>{"use strict";_Sn="crtr-context",ISn="crtr-situational-context",kSn="crtr-context-nudge",TSn="crtr-review-boundary",sXe="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",aXe="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",cXe="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",uXe="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";hz=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var dXe=x(()=>{"use strict";AS()});function DSn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function y$(){let t=DSn();if(t===void 0)return $x({autostart:!1});let e=uYe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new ng({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function pXe(t,e){return y$().appendNodeLog(t,{record:e,expected_execution_id:BSn()})}function BSn(){let t=k7e();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function hXe(t,e){return y$().recordNodeFault(t,e)}async function fXe(t,e={}){return y$().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var A$=x(()=>{"use strict";V3();lYe();K3();tg();Kc();dYe();xS();iXe();oXe();dXe()});function OSn(t,e){mXe=mXe.then(async()=>{try{let{appended:n}=await pXe(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
|
|
91
|
+
`);I$.write(DJe.format.apply(DJe,e))}}Object.defineProperty(wA.exports,"isWin",{get:function(){return az},set:function(t){az=t}});wA.exports.warnTo=function(t){var e=I$;return I$=t,e};wA.exports.getFileName=function(t){var e=t||process.env,n=e.PGPASSFILE||(az?PJe.join(e.APPDATA||"./","postgresql","pgpass.conf"):PJe.join(e.HOME||"./",".pgpass"));return n};wA.exports.usePgPass=function(t,e){return Object.prototype.hasOwnProperty.call(process.env,"PGPASSWORD")?!1:az?!0:(e=e||"<unkn>",QEn(t.mode)?t.mode&(NEn|$En)?(dme('WARNING: password file "%s" has group or world access; permissions should be u=rw (0600) or less',e),!1):!0:(dme('WARNING: password file "%s" is not a plain file',e),!1))};var HEn=wA.exports.match=function(t,e){return uR.slice(0,-1).reduce(function(n,r,i){return i==1&&Number(t[r]||OEn)===Number(e[r])?n&&!0:n&&(e[r]==="*"||e[r]===t[r])},!0)};wA.exports.getPassword=function(t,e,n){var r,i=e.pipe(LEn());function o(c){var u=qEn(c);u&&GEn(u)&&HEn(t,u)&&(r=u[WEn],i.end())}var s=function(){e.destroy(),n(r)},a=function(c){e.destroy(),dme("WARNING: error on reading file: %s",c),n(void 0)};e.on("error",a),i.on("data",o).on("end",s).on("error",a)};var qEn=wA.exports.parseLine=function(t){if(t.length<11||t.match(/^\s+#/))return null;for(var e="",n="",r=0,i=0,o=0,s={},a=!1,c=function(l,d,p){var h=t.substring(d,p);Object.hasOwnProperty.call(process.env,"PGPASS_NO_DEESCAPE")||(h=h.replace(/\\([:\\])/g,"$1")),s[uR[l]]=h},u=0;u<t.length-1;u+=1){if(e=t.charAt(u+1),n=t.charAt(u),a=r==lme-1,a){c(r,i);break}u>=0&&e==":"&&n!=="\\"&&(c(r,i,u+1),i=u+2,r+=1)}return s=Object.keys(s).length===lme?s:null,s},GEn=wA.exports.isValidEntry=function(t){for(var e={0:function(s){return s.length>0},1:function(s){return s==="*"?!0:(s=Number(s),isFinite(s)&&s>0&&s<9007199254740992&&Math.floor(s)===s)},2:function(s){return s.length>0},3:function(s){return s.length>0},4:function(s){return s.length>0}},n=0;n<uR.length;n+=1){var r=e[n],i=t[uR[n]]||"",o=r(i);if(!o)return!1}return!0}});var OJe=$((Uli,pme)=>{"use strict";var Fli=Z("path"),LJe=Z("fs"),cz=BJe();pme.exports=function(t,e){var n=cz.getFileName();LJe.stat(n,function(r,i){if(r||!cz.usePgPass(i,n))return e(void 0);var o=LJe.createReadStream(n);cz.getPassword(t,o,e)})};pme.exports.warnTo=cz.warnTo});var UJe=$((Qli,FJe)=>{var jEn=Z("events").EventEmitter,NJe=hS(),k$=Z("util"),uz=eJe(),zEn=ez(),VEn=Lfe(),hme=hJe(),KEn=C$(),YEn=ume(),JEn=Rfe(),$Je=k$.deprecate(()=>{},"Client.activeQuery is deprecated and will be removed in pg@9.0"),XEn=k$.deprecate(()=>{},"Client.queryQueue is deprecated and will be removed in pg@9.0."),ZEn=k$.deprecate(()=>{},"pgpass support is deprecated and will be removed in pg@9.0. You can provide an async function as the password property to the Client/Pool constructor that returns a password instead. Within this function you can call the pgpass module in your own code."),eSn=k$.deprecate(()=>{},"Passing a custom Promise implementation to the Client/Pool constructor is deprecated and will be removed in pg@9.0."),tSn=k$.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead.");function nSn(t,e){if(typeof t=="number")return Number.isFinite(t)?t:e;if(typeof t=="string"&&t.trim()!==""){let n=Number(t);return Number.isFinite(n)?n:e}return e}var lz=class extends jEn{constructor(e){super(),this.connectionParameters=new VEn(e),this.user=this.connectionParameters.user,this.database=this.connectionParameters.database,this.port=this.connectionParameters.port,this.host=this.connectionParameters.host,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:this.connectionParameters.password}),this.replication=this.connectionParameters.replication;let n=e||{};n.Promise&&eSn(),this._Promise=n.Promise||global.Promise,this._types=new zEn(n.types),this._ending=!1,this._ended=!1,this._connecting=!1,this._connected=!1,this._connectionError=!1,this._queryable=!0,this._activeQuery=null,this._txStatus=null,this.enableChannelBinding=!!n.enableChannelBinding,this.scramMaxIterations=nSn(n.scramMaxIterations,uz.DEFAULT_MAX_SCRAM_ITERATIONS),this.connection=n.connection||new YEn({stream:n.stream,ssl:this.connectionParameters.ssl,sslNegotiation:this.connectionParameters.sslnegotiation,keepAlive:n.keepAlive||!1,keepAliveInitialDelayMillis:n.keepAliveInitialDelayMillis||0,encoding:this.connectionParameters.client_encoding||"utf8"}),this._queryQueue=[],this._sentQueryQueue=[],this.pipeline=!!n.pipeline,this.binary=n.binary||KEn.binary,this.processID=null,this.secretKey=null,this.ssl=this.connectionParameters.ssl||!1,this.sslNegotiation=this.connectionParameters.sslnegotiation||"postgres",this.ssl&&this.ssl.key&&Object.defineProperty(this.ssl,"key",{enumerable:!1}),this._connectionTimeoutMillis=n.connectionTimeoutMillis||0}get activeQuery(){return $Je(),this._activeQuery}set activeQuery(e){$Je(),this._activeQuery=e}_getActiveQuery(){return this._activeQuery}_errorAllQueries(e){let n=i=>{process.nextTick(()=>{i.handleError(e,this.connection)})},r=this._getActiveQuery();r&&(n(r),this._activeQuery=null),this._sentQueryQueue.forEach(n),this._sentQueryQueue.length=0,this._queryQueue.forEach(n),this._queryQueue.length=0}_connect(e){let n=this,r=this.connection;if(this._connectionCallback=e,this._connecting||this._connected){let i=new Error("Client has already been connected. You cannot reuse a client.");process.nextTick(()=>{e(i)});return}this._connecting=!0,this._connectionTimeoutMillis>0&&(this.connectionTimeoutHandle=setTimeout(()=>{r._ending=!0,r.stream.destroy(new Error("timeout expired"))},this._connectionTimeoutMillis),this.connectionTimeoutHandle.unref&&this.connectionTimeoutHandle.unref()),this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){n.ssl?n.sslNegotiation!=="direct"&&r.requestSsl():r.startup(n.getStartupConf())}),r.on("sslconnect",function(){r.startup(n.getStartupConf())}),this._attachListeners(r),r.once("end",()=>{let i=this._ending?new Error("Connection terminated"):new Error("Connection terminated unexpectedly");clearTimeout(this.connectionTimeoutHandle),this._errorAllQueries(i),this._ended=!0,this._ending||(this._connecting&&!this._connectionError?this._connectionCallback?this._connectionCallback(i):this._handleErrorEvent(i):this._connectionError||this._handleErrorEvent(i)),process.nextTick(()=>{this.emit("end")})})}connect(e){if(e){this._connect(e);return}return new this._Promise((n,r)=>{this._connect(i=>{i?r(i):n(this)})})}_attachListeners(e){e.on("authenticationCleartextPassword",this._handleAuthCleartextPassword.bind(this)),e.on("authenticationMD5Password",this._handleAuthMD5Password.bind(this)),e.on("authenticationSASL",this._handleAuthSASL.bind(this)),e.on("authenticationSASLContinue",this._handleAuthSASLContinue.bind(this)),e.on("authenticationSASLFinal",this._handleAuthSASLFinal.bind(this)),e.on("backendKeyData",this._handleBackendKeyData.bind(this)),e.on("error",this._handleErrorEvent.bind(this)),e.on("errorMessage",this._handleErrorMessage.bind(this)),e.on("readyForQuery",this._handleReadyForQuery.bind(this)),e.on("notice",this._handleNotice.bind(this)),e.on("rowDescription",this._handleRowDescription.bind(this)),e.on("dataRow",this._handleDataRow.bind(this)),e.on("portalSuspended",this._handlePortalSuspended.bind(this)),e.on("emptyQuery",this._handleEmptyQuery.bind(this)),e.on("commandComplete",this._handleCommandComplete.bind(this)),e.on("parseComplete",this._handleParseComplete.bind(this)),e.on("copyInResponse",this._handleCopyInResponse.bind(this)),e.on("copyData",this._handleCopyData.bind(this)),e.on("notification",this._handleNotification.bind(this))}_getPassword(e){let n=this.connection;if(typeof this.password=="function")this._Promise.resolve().then(()=>this.password(this.connectionParameters)).then(r=>{if(r!==void 0){if(typeof r!="string"){n.emit("error",new TypeError("Password must be a string"));return}this.connectionParameters.password=this.password=r}else this.connectionParameters.password=this.password=null;e()}).catch(r=>{n.emit("error",r)});else if(this.password!==null)e();else try{OJe()(this.connectionParameters,i=>{i!==void 0&&(ZEn(),this.connectionParameters.password=this.password=i),e()})}catch(r){this.emit("error",r)}}_handleAuthCleartextPassword(e){this._getPassword(()=>{this.connection.password(this.password)})}_handleAuthMD5Password(e){this._getPassword(async()=>{try{let n=await JEn.postgresMd5PasswordHash(this.user,this.password,e.salt);this.connection.password(n)}catch(n){this.emit("error",n)}})}_handleAuthSASL(e){this._getPassword(()=>{try{this.saslSession=uz.startSession(e.mechanisms,this.enableChannelBinding&&this.connection.stream,this.scramMaxIterations),this.connection.sendSASLInitialResponseMessage(this.saslSession.mechanism,this.saslSession.response)}catch(n){this.connection.emit("error",n)}})}async _handleAuthSASLContinue(e){try{await uz.continueSession(this.saslSession,this.password,e.data,this.enableChannelBinding&&this.connection.stream),this.connection.sendSCRAMClientFinalMessage(this.saslSession.response)}catch(n){this.connection.emit("error",n)}}_handleAuthSASLFinal(e){try{uz.finalizeSession(this.saslSession,e.data),this.saslSession=null}catch(n){this.connection.emit("error",n)}}_handleBackendKeyData(e){this.processID=e.processID,this.secretKey=e.secretKey}_handleReadyForQuery(e){this._connecting&&(this._connecting=!1,this._connected=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback&&(this._connectionCallback(null,this),this._connectionCallback=null),this.emit("connect"));let n=this._getActiveQuery();this._activeQuery=null,this._txStatus=e?.status??null,this.readyForQuery=!0,n&&n.handleReadyForQuery(this.connection),this._pulseQueryQueue()}_handleErrorWhileConnecting(e){if(!this._connectionError){if(this._connectionError=!0,clearTimeout(this.connectionTimeoutHandle),this._connectionCallback)return this._connectionCallback(e);this.emit("error",e)}}_handleErrorEvent(e){if(this._connecting)return this._handleErrorWhileConnecting(e);this._queryable=!1,this._errorAllQueries(e),this.emit("error",e)}_handleErrorMessage(e){if(this._connecting)return this._handleErrorWhileConnecting(e);let n=this._getActiveQuery();if(!n){this._handleErrorEvent(e);return}this._activeQuery=null,n.name&&delete this.connection.submittedNamedStatements[n.name],n.handleError(e,this.connection)}_handleRowDescription(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected rowDescription message from backend.");this._handleErrorEvent(r);return}n.handleRowDescription(e)}_handleDataRow(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected dataRow message from backend.");this._handleErrorEvent(r);return}n.handleDataRow(e)}_handlePortalSuspended(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected portalSuspended message from backend.");this._handleErrorEvent(r);return}n.handlePortalSuspended(this.connection)}_handleEmptyQuery(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected emptyQuery message from backend.");this._handleErrorEvent(r);return}n.handleEmptyQuery(this.connection)}_handleCommandComplete(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected commandComplete message from backend.");this._handleErrorEvent(r);return}n.handleCommandComplete(e,this.connection)}_handleParseComplete(){let e=this._getActiveQuery();if(e==null){let n=new Error("Received unexpected parseComplete message from backend.");this._handleErrorEvent(n);return}e.name&&(this.connection.parsedStatements[e.name]=e.text,delete this.connection.submittedNamedStatements[e.name])}_handleCopyInResponse(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyInResponse message from backend.");this._handleErrorEvent(r);return}n.handleCopyInResponse(this.connection)}_handleCopyData(e){let n=this._getActiveQuery();if(n==null){let r=new Error("Received unexpected copyData message from backend.");this._handleErrorEvent(r);return}n.handleCopyData(e,this.connection)}_handleNotification(e){this.emit("notification",e)}_handleNotice(e){this.emit("notice",e)}getStartupConf(){let e=this.connectionParameters,n={user:e.user,database:e.database},r=e.application_name||e.fallback_application_name;return r&&(n.application_name=r),e.replication&&(n.replication=""+e.replication),e.statement_timeout&&(n.statement_timeout=String(parseInt(e.statement_timeout,10))),e.lock_timeout&&(n.lock_timeout=String(parseInt(e.lock_timeout,10))),e.idle_in_transaction_session_timeout&&(n.idle_in_transaction_session_timeout=String(parseInt(e.idle_in_transaction_session_timeout,10))),e.options&&(n.options=e.options),n}cancel(e,n){if(e.activeQuery===n){let r=this.connection;this.host&&this.host.indexOf("/")===0?r.connect(this.host+"/.s.PGSQL."+this.port):r.connect(this.port,this.host),r.on("connect",function(){r.cancel(e.processID,e.secretKey)})}else e._queryQueue.indexOf(n)!==-1?e._queryQueue.splice(e._queryQueue.indexOf(n),1):e._sentQueryQueue.indexOf(n)!==-1&&(n.callback=()=>{})}setTypeParser(e,n,r){return this._types.setTypeParser(e,n,r)}getTypeParser(e,n){return this._types.getTypeParser(e,n)}escapeIdentifier(e){return NJe.escapeIdentifier(e)}escapeLiteral(e){return NJe.escapeLiteral(e)}_pulseQueryQueue(){if(this.pipeline){this._pulsePipelinedQueryQueue();return}if(this.readyForQuery===!0){this._activeQuery=this._queryQueue.shift();let e=this._getActiveQuery();if(e){this.readyForQuery=!1,this.hasExecuted=!0;let n=e.submit(this.connection);n&&process.nextTick(()=>{e.handleError(n,this.connection),this.readyForQuery=!0,this._pulseQueryQueue()})}else this.hasExecuted&&(this._activeQuery=null,this.emit("drain"))}}_pulsePipelinedQueryQueue(){if(!(!this._connected||!this._queryable)){for(;this._queryQueue.length>0;){let e=this._queryQueue.shift();this.hasExecuted=!0;let n=e.submit(this.connection);if(n){process.nextTick(()=>{e.handleError(n,this.connection)});continue}this._sentQueryQueue.push(e)}this.readyForQuery&&!this._activeQuery&&this._sentQueryQueue.length>0&&(this._activeQuery=this._sentQueryQueue.shift(),this.readyForQuery=!1),!this._activeQuery&&this._sentQueryQueue.length===0&&this._queryQueue.length===0&&this.hasExecuted&&this.emit("drain")}}query(e,n,r){let i,o;if(e==null)throw new TypeError("Client was passed a null or undefined query");if(typeof e.submit=="function")o=i=e,i.callback||(typeof n=="function"?i.callback=n:r&&(i.callback=r));else if(i=new hme(e,n,r),!i.callback)o=new this._Promise((a,c)=>{i.callback=(u,l)=>u?c(u):a(l)}).catch(a=>{throw Error.captureStackTrace(a),a});else if(typeof i.callback!="function")throw new TypeError("callback is not a function");let s=e.query_timeout||this.connectionParameters.query_timeout;if(s){let a=i.callback||(()=>{}),c=setTimeout(()=>{let u=new Error("Query read timeout");process.nextTick(()=>{i.handleError(u,this.connection)}),a(u),i.callback=()=>{};let l=this._queryQueue.indexOf(i);if(l>-1)this._queryQueue.splice(l,1);else if(this.pipeline){this.connection.stream.destroy();return}this._pulseQueryQueue()},s);i.callback=(u,l)=>{clearTimeout(c),a(u,l)}}if(this.binary&&!i.binary&&(i.binary=!0),i._result&&!i._result._types&&(i._result._types=this._types),this.pipeline){let a=typeof e.submit=="function"&&!(i instanceof hme)?"Custom query classes such as pg-cursor and pg-query-stream are":i.rows?"The `rows` option is":null;if(a)return process.nextTick(()=>{i.handleError(new Error(`${a} not supported in pipeline mode`),this.connection)}),o}return this._queryable?this._ending?(process.nextTick(()=>{i.handleError(new Error("Client was closed and is not queryable"),this.connection)}),o):(this._queryQueue.length>0&&!this.pipeline&&tSn(),this._queryQueue.push(i),this._pulseQueryQueue(),o):(process.nextTick(()=>{i.handleError(new Error("Client has encountered a connection error and is not queryable"),this.connection)}),o)}ref(){this.connection.ref()}unref(){this.connection.unref()}getTransactionStatus(){return this._txStatus}end(e){if(this._ending=!0,!this.connection._connecting||this._ended)if(e){e();return}else return this._Promise.resolve();if(this._queryable?this.pipeline&&(this._getActiveQuery()||this._sentQueryQueue.length>0||this._queryQueue.length>0)?this.once("drain",()=>this.connection.end()):this._getActiveQuery()?this.connection.stream.destroy():this.connection.end():this.connection.stream.destroy(),e)this.connection.once("end",e);else return new this._Promise(n=>{this.connection.once("end",n)})}get queryQueue(){return XEn(),this._queryQueue}};lz.Query=hme;FJe.exports=lz});var HJe=$((Wli,WJe)=>{"use strict";var rSn=Z("events").EventEmitter,fme=function(){},QJe=(t,e)=>{let n=t.findIndex(e);return n===-1?void 0:t.splice(n,1)[0]},mme=class{constructor(e,n,r){this.client=e,this.idleListener=n,this.timeoutId=r}},lR=class{constructor(e){this.callback=e}};function iSn(){throw new Error("Release called on client which has already been released to the pool.")}function dz(t,e){if(e)return{callback:e,result:void 0};let n,r,i=function(s,a){s?n(s):r(a)},o=new t(function(s,a){r=s,n=a}).catch(s=>{throw Error.captureStackTrace(s),s});return{callback:i,result:o}}function oSn(t,e){return function n(r){r.client=e,e.removeListener("error",n),e.on("error",()=>{t.log("additional client error after disconnection due to error",r)}),t._remove(e),t.emit("error",r,e)}}var gme=class extends rSn{constructor(e,n){super(),this.options=Object.assign({},e),e!=null&&"password"in e&&Object.defineProperty(this.options,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),e!=null&&e.ssl&&e.ssl.key&&Object.defineProperty(this.options.ssl,"key",{enumerable:!1}),this.options.max=this.options.max||this.options.poolSize||10,this.options.min=this.options.min||0,this.options.maxUses=this.options.maxUses||1/0,this.options.allowExitOnIdle=this.options.allowExitOnIdle||!1,this.options.maxLifetimeSeconds=this.options.maxLifetimeSeconds||0,this.log=this.options.log||function(){},this.Client=this.options.Client||n||yme().Client,this.Promise=this.options.Promise||global.Promise,typeof this.options.idleTimeoutMillis>"u"&&(this.options.idleTimeoutMillis=1e4),this._clients=[],this._idle=[],this._expired=new WeakSet,this._pendingQueue=[],this._endCallback=void 0,this.ending=!1,this.ended=!1}_promiseTry(e){let n=this.Promise;return typeof n.try=="function"?n.try(e):new n(r=>r(e()))}_isFull(){return this._clients.length>=this.options.max}_isAboveMin(){return this._clients.length>this.options.min}_pulseQueue(){if(this.log("pulse queue"),this.ended){this.log("pulse queue ended");return}if(this.ending){this.log("pulse queue on ending"),this._idle.length&&this._idle.slice().map(n=>{this._remove(n.client)}),this._clients.length||(this.ended=!0,this._endCallback());return}if(!this._pendingQueue.length){this.log("no queued requests");return}if(!this._idle.length&&this._isFull())return;let e=this._pendingQueue.shift();if(this._idle.length){let n=this._idle.pop();clearTimeout(n.timeoutId);let r=n.client;r.ref&&r.ref();let i=n.idleListener;return this._acquireClient(r,e,i,!1)}if(!this._isFull())return this.newClient(e);throw new Error("unexpected condition")}_remove(e,n){let r=QJe(this._idle,o=>o.client===e);r!==void 0&&clearTimeout(r.timeoutId),this._clients=this._clients.filter(o=>o!==e);let i=this;e.end(()=>{i.emit("remove",e),typeof n=="function"&&n()})}connect(e){if(this.ending){let i=new Error("Cannot use a pool after calling end on the pool");return e?e(i):this.Promise.reject(i)}let n=dz(this.Promise,e),r=n.result;if(this._isFull()||this._idle.length){if(this._idle.length&&process.nextTick(()=>this._pulseQueue()),!this.options.connectionTimeoutMillis)return this._pendingQueue.push(new lR(n.callback)),r;let i=(a,c,u)=>{clearTimeout(s),n.callback(a,c,u)},o=new lR(i),s=setTimeout(()=>{QJe(this._pendingQueue,a=>a.callback===i),o.timedOut=!0,n.callback(new Error("timeout exceeded when trying to connect"))},this.options.connectionTimeoutMillis);return s.unref&&s.unref(),this._pendingQueue.push(o),r}return this.newClient(new lR(n.callback)),r}newClient(e){let n=new this.Client(this.options);this._clients.push(n);let r=oSn(this,n);this.log("checking client timeout");let i,o=!1;this.options.connectionTimeoutMillis&&(i=setTimeout(()=>{n.connection?(this.log("ending client due to timeout"),o=!0,n.connection.stream.destroy()):n.isConnected()||(this.log("ending client due to timeout"),o=!0,n.end())},this.options.connectionTimeoutMillis)),this.log("connecting new client"),n.connect(s=>{if(i&&clearTimeout(i),n.on("error",r),s)this.log("client failed to connect",s),this._clients=this._clients.filter(a=>a!==n),o&&(s=new Error("Connection terminated due to connection timeout",{cause:s})),this._pulseQueue(),e.timedOut||e.callback(s,void 0,fme);else{if(this.log("new client connected"),this.options.onConnect){this._promiseTry(()=>this.options.onConnect(n)).then(()=>{this._afterConnect(n,e,r)},a=>{this._clients=this._clients.filter(c=>c!==n),n.end(()=>{this._pulseQueue(),e.timedOut||e.callback(a,void 0,fme)})});return}return this._afterConnect(n,e,r)}})}_afterConnect(e,n,r){if(this.options.maxLifetimeSeconds!==0){let i=setTimeout(()=>{this.log("ending client due to expired lifetime"),this._expired.add(e),this._idle.findIndex(s=>s.client===e)!==-1&&this._acquireClient(e,new lR((s,a,c)=>c()),r,!1)},this.options.maxLifetimeSeconds*1e3);i.unref(),e.once("end",()=>clearTimeout(i))}return this._acquireClient(e,n,r,!0)}_acquireClient(e,n,r,i){i&&this.emit("connect",e),this.emit("acquire",e),e.release=this._releaseOnce(e,r),e.removeListener("error",r),n.timedOut?i&&this.options.verify?this.options.verify(e,e.release):e.release():i&&this.options.verify?this.options.verify(e,o=>{if(o)return e.release(o),n.callback(o,void 0,fme);n.callback(void 0,e,e.release)}):n.callback(void 0,e,e.release)}_releaseOnce(e,n){let r=!1;return i=>{r&&iSn(),r=!0,this._release(e,n,i)}}_release(e,n,r){if(e.on("error",n),e._poolUseCount=(e._poolUseCount||0)+1,this.emit("release",r,e),r||this.ending||!e._queryable||e._ending||e._poolUseCount>=this.options.maxUses)return e._poolUseCount>=this.options.maxUses&&this.log("remove expended client"),this._remove(e,this._pulseQueue.bind(this));if(this._expired.has(e))return this.log("remove expired client"),this._expired.delete(e),this._remove(e,this._pulseQueue.bind(this));let o;this.options.idleTimeoutMillis&&this._isAboveMin()&&(o=setTimeout(()=>{this._isAboveMin()&&(this.log("remove idle client"),this._remove(e,this._pulseQueue.bind(this)))},this.options.idleTimeoutMillis),this.options.allowExitOnIdle&&o.unref()),this.options.allowExitOnIdle&&e.unref(),this._idle.push(new mme(e,n,o)),this._pulseQueue()}query(e,n,r){if(typeof e=="function"){let o=dz(this.Promise,e);return setImmediate(function(){return o.callback(new Error("Passing a function as the first parameter to pool.query is not supported"))}),o.result}typeof n=="function"&&(r=n,n=void 0);let i=dz(this.Promise,r);return r=i.callback,this.connect((o,s)=>{if(o)return r(o);let a=!1,c=u=>{a||(a=!0,s.release(u),r(u))};s.once("error",c),this.log("dispatching query");try{s.query(e,n,(u,l)=>{if(this.log("query dispatched"),s.removeListener("error",c),!a)return a=!0,s.release(u),u?r(u):r(void 0,l)})}catch(u){return s.release(u),r(u)}}),i.result}end(e){if(this.log("ending"),this.ending){let r=new Error("Called end on pool more than once");return e?e(r):this.Promise.reject(r)}this.ending=!0;let n=dz(this.Promise,e);return this._endCallback=n.callback,this._pulseQueue(),n.result}get waitingCount(){return this._pendingQueue.length}get idleCount(){return this._idle.length}get expiredCount(){return this._clients.reduce((e,n)=>e+(this._expired.has(n)?1:0),0)}get totalCount(){return this._clients.length}};WJe.exports=gme});var jJe=$((Hli,GJe)=>{"use strict";var qJe=Z("events").EventEmitter,sSn=Z("util"),Ame=hS(),dR=GJe.exports=function(t,e,n){qJe.call(this),t=Ame.normalizeQueryConfig(t,e,n),this.text=t.text,this.values=t.values,this.name=t.name,this.queryMode=t.queryMode,this.callback=t.callback,this.state="new",this._arrayMode=t.rowMode==="array",this._emitRowEvents=!1,this.on("newListener",function(r){r==="row"&&(this._emitRowEvents=!0)}.bind(this))};sSn.inherits(dR,qJe);var aSn={sqlState:"code",statementPosition:"position",messagePrimary:"message",messageDetail:"detail",messageHint:"hint",context:"where",schemaName:"schema",tableName:"table",columnName:"column",dataTypeName:"dataType",constraintName:"constraint",sourceFile:"file",sourceLine:"line",sourceFunction:"routine"};dR.prototype.handleError=function(t){let e=this.native&&this.native.pq.resultErrorFields();if(e)for(let n in e){let r=aSn[n]||n;t[r]=e[n]}this.callback?this.callback(t):this.emit("error",t),this.state="error"};dR.prototype.then=function(t,e){return this._getPromise().then(t,e)};dR.prototype.catch=function(t){return this._getPromise().catch(t)};dR.prototype._getPromise=function(){return this._promise?this._promise:(this._promise=new Promise(function(t,e){this._once("end",t),this._once("error",e)}.bind(this)),this._promise)};dR.prototype.submit=function(t){this.state="running";let e=this;this.native=t.native,t.native.arrayMode=this._arrayMode;let n=function(r,i,o){if(t.native.arrayMode=!1,setImmediate(function(){e.emit("_done")}),r)return e.handleError(r);e._emitRowEvents&&(o.length>1?i.forEach((s,a)=>{s.forEach(c=>{e.emit("row",c,o[a])})}):i.forEach(function(s){e.emit("row",s,o)})),e.state="end",e.emit("end",o),e.callback&&e.callback(null,o)};if(process.domain&&(n=process.domain.bind(n)),this.name){this.name.length>63&&(console.error("Warning! Postgres only supports 63 characters for query names."),console.error("You supplied %s (%s)",this.name,this.name.length),console.error("This can cause conflicts and silent errors executing queries"));let r=(this.values||[]).map(Ame.prepareValue);if(t.namedQueries[this.name]!==void 0){if(this.text&&t.namedQueries[this.name]!==this.text){let i=new Error(`Prepared statements must be unique - '${this.name}' was used for a different statement`);return n(i)}return t.native.execute(this.name,r,n)}return t.native.prepare(this.name,this.text,r.length,function(i){return i?n(i):(t.namedQueries[e.name]=e.text,e.native.execute(e.name,r,n))})}else if(this.values){if(!Array.isArray(this.values)){let i=new Error("Query values must be an array");return n(i)}let r=this.values.map(Ame.prepareValue);t.native.query(this.text,r,n)}else this.queryMode==="extended"?t.native.query(this.text,[],n):t.native.query(this.text,n)}});var JJe=$((qli,YJe)=>{var cSn=Z("util"),zJe;try{zJe=Z("pg-native")}catch(t){throw t}var uSn=ez(),VJe=Z("events").EventEmitter,lSn=Z("util"),dSn=Lfe(),KJe=jJe(),pSn=cSn.deprecate(()=>{},"Calling client.query() when the client is already executing a query is deprecated and will be removed in pg@9.0. Use async/await or an external async flow control mechanism instead."),xc=YJe.exports=function(t){VJe.call(this),t=t||{},this._Promise=t.Promise||global.Promise,this._types=new uSn(t.types),this.native=new zJe({types:this._types}),this._queryQueue=[],this._ending=!1,this._connecting=!1,this._connected=!1,this._queryable=!0,this.pipeline=!!t.pipeline,this._pipelineInFlight=!1;let e=this.connectionParameters=new dSn(t);t.nativeConnectionString&&(e.nativeConnectionString=t.nativeConnectionString),this.user=e.user,Object.defineProperty(this,"password",{configurable:!0,enumerable:!1,writable:!0,value:e.password}),this.database=e.database,this.host=e.host,this.port=e.port,this.namedQueries={}};xc.Query=KJe;lSn.inherits(xc,VJe);xc.prototype._errorAllQueries=function(t){let e=n=>{process.nextTick(()=>{n.native=this.native,n.handleError(t)})};this._hasActiveQuery()&&(e(this._activeQuery),this._activeQuery=null),this._queryQueue.forEach(e),this._queryQueue.length=0};xc.prototype._connect=function(t){let e=this;if(this._connecting){process.nextTick(()=>t(new Error("Client has already been connected. You cannot reuse a client.")));return}this._connecting=!0,this.connectionParameters.getLibpqConnectionString(function(n,r){if(e.connectionParameters.nativeConnectionString&&(r=e.connectionParameters.nativeConnectionString),n)return t(n);e.native.connect(r,function(i){if(i)return e.native.end(),t(i);e._connected=!0,e.native.on("error",function(o){e._queryable=!1,e._errorAllQueries(o),e.emit("error",o)}),e.native.on("notification",function(o){e.emit("notification",{channel:o.relname,payload:o.extra})}),e.emit("connect"),e._pulseQueryQueue(!0),t(null,this)})})};xc.prototype.connect=function(t){if(t){this._connect(t);return}return new this._Promise((e,n)=>{this._connect(r=>{r?n(r):e(this)})})};xc.prototype.query=function(t,e,n){let r,i,o,s,a;if(t==null)throw new TypeError("Client was passed a null or undefined query");if(typeof t.submit=="function")o=t.query_timeout||this.connectionParameters.query_timeout,i=r=t,typeof e=="function"&&(t.callback=e);else if(o=t.query_timeout||this.connectionParameters.query_timeout,r=new KJe(t,e,n),!r.callback){let c,u;i=new this._Promise((l,d)=>{c=l,u=d}).catch(l=>{throw Error.captureStackTrace(l),l}),r.callback=(l,d)=>l?u(l):c(d)}return o&&(a=r.callback||(()=>{}),s=setTimeout(()=>{let c=new Error("Query read timeout");process.nextTick(()=>{r.handleError(c,this.connection)}),a(c),r.callback=()=>{};let u=this._queryQueue.indexOf(r);u>-1&&this._queryQueue.splice(u,1),this._pulseQueryQueue()},o),r.callback=(c,u)=>{clearTimeout(s),a(c,u)}),this._queryable?this._ending?(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client was closed and is not queryable"))}),i):(this._queryQueue.length>0&&!this.pipeline&&pSn(),this._queryQueue.push(r),this._pulseQueryQueue(),i):(r.native=this.native,process.nextTick(()=>{r.handleError(new Error("Client has encountered a connection error and is not queryable"))}),i)};xc.prototype.end=function(t){let e=this;this._ending=!0,this._connecting&&!this._connected&&this.once("connect",()=>{this.end(()=>{})});let n;t||(n=new this._Promise(function(i,o){t=s=>s?o(s):i()}));let r=function(){e.native.end(function(){e._connected=!1,e._errorAllQueries(new Error("Connection terminated")),process.nextTick(()=>{e.emit("end"),t&&t()})})};return this.pipeline&&(this._pipelineInFlight||this._queryQueue.length>0)?this.once("drain",r):r(),n};xc.prototype._hasActiveQuery=function(){return this._activeQuery&&this._activeQuery.state!=="error"&&this._activeQuery.state!=="end"};xc.prototype._pulseQueryQueue=function(t){if(!this._connected)return;if(this.pipeline&&!t)return this._pulsePipelinedQueryQueue();if(this._hasActiveQuery())return;let e=this._queryQueue.shift();if(!e){t||this.emit("drain");return}this._activeQuery=e,e.submit(this);let n=this;e.once("_done",function(){n._pulseQueryQueue()})};xc.prototype._pulsePipelinedQueryQueue=function(){if(!this._connected||this._pipelineInFlight)return;if(this._queryQueue.length===0){this.hasExecuted&&this.emit("drain");return}this._pipelineInFlight=!0;let t=this,e=[],n=[],r=hS();for(;this._queryQueue.length>0;){let i=this._queryQueue.shift();this.hasExecuted=!0,n.push(i);let o=i.values?i.values.map(r.prepareValue):null,s={text:i.text,name:i.name,arrayMode:i._arrayMode};o&&(s.values=o),i.name&&this.namedQueries[i.name]&&(s._alreadyPrepared=!0),e.push(s)}this.native.pipeline(e,function(i,o){if(t._pipelineInFlight=!1,i){t._connected=!1,t._queryable=!1;for(let s=0;s<n.length;s++){let a=n[s];a.native=t.native,a.handleError(i)}t._errorAllQueries(i),t.emit("error",i),t.emit("end");return}for(let s=0;s<n.length;s++){let a=n[s],c=o[s];a.native=t.native,c.err?a.handleError(c.err):(a.name&&(t.namedQueries[a.name]=a.text),a.state="end",a.emit("end",c.result),a.callback&&a.callback(null,c.result)),setImmediate(function(){a.emit("_done")})}t._pulsePipelinedQueryQueue()})};xc.prototype.cancel=function(t){this._activeQuery===t?this.native.cancel(function(){}):this._queryQueue.indexOf(t)!==-1&&this._queryQueue.splice(this._queryQueue.indexOf(t),1)};xc.prototype.ref=function(){};xc.prototype.unref=function(){};xc.prototype.setTypeParser=function(t,e,n){return this._types.setTypeParser(t,e,n)};xc.prototype.getTypeParser=function(t,e){return this._types.getTypeParser(t,e)};xc.prototype.isConnected=function(){return this._connected};xc.prototype.getTransactionStatus=function(){return this.native.getTransactionStatus()}});var xme=$((Gli,XJe)=>{"use strict";XJe.exports=JJe()});var yme=$((zli,pz)=>{"use strict";var hSn=UJe(),fSn=C$(),mSn=ume(),gSn=Nfe(),ySn=hS(),ASn=HJe(),xSn=ez(),{DatabaseError:wSn}=sme(),{escapeIdentifier:bSn,escapeLiteral:vSn}=hS(),ESn=t=>class extends ASn{constructor(n){super(n,t)}},ZJe=function(t){this.defaults=fSn,this.Client=t,this.Query=this.Client.Query,this.Pool=ESn(this.Client),this._pools=[],this.Connection=mSn,this.types=S$(),this.DatabaseError=wSn,this.TypeOverrides=xSn,this.escapeIdentifier=bSn,this.escapeLiteral=vSn,this.Result=gSn,this.utils=ySn},eXe=hSn,tXe=!1;try{tXe=!!process.env.NODE_PG_FORCE_NATIVE}catch{}tXe&&(eXe=xme());pz.exports=new ZJe(eXe);Object.defineProperty(pz.exports,"native",{configurable:!0,enumerable:!1,get(){let t=null;try{t=new ZJe(xme())}catch(e){if(e.code!=="MODULE_NOT_FOUND")throw e}return Object.defineProperty(pz.exports,"native",{value:t}),t}})});var Ud,Vli,Kli,Yli,Jli,Xli,Zli,edi,tdi,ndi,rdi,idi,nXe,rXe=x(()=>{Ud=sn(yme(),1),Vli=Ud.default.Client,Kli=Ud.default.Pool,Yli=Ud.default.Connection,Jli=Ud.default.types,Xli=Ud.default.Query,Zli=Ud.default.DatabaseError,edi=Ud.default.escapeIdentifier,tdi=Ud.default.escapeLiteral,ndi=Ud.default.Result,rdi=Ud.default.TypeOverrides,idi=Ud.default.defaults,nXe=Ud.default});var SSn,CSn,wme,adi,iXe=x(()=>{"use strict";rXe();SSn=["mail","node","grant","run_event","report","structured_request","queue","spend_limits","environment_image","fault_retry","settings","machine","machine_call","document"],CSn=new Set(SSn),wme=class{dirty=new Map;subscribers=new Set;scheduled;checkIntervalMs;checkTimeoutMs;reconnectMs;constructor(e={}){this.checkIntervalMs=e.checkIntervalMs??3e4,this.checkTimeoutMs=e.checkTimeoutMs??1e4,this.reconnectMs=e.reconnectMs??1e3}async subscribe(e,n={}){let r={listener:e,kinds:new Set(n.kinds??["mail","node"]),onListenStart:n.onListenStart};return this.subscribers.add(r),this.listener!==void 0&&r.onListenStart!==void 0&&queueMicrotask(()=>{this.subscribers.has(r)&&this.callListenStart(r)}),()=>{this.subscribers.delete(r)}}markMail(e){this.mark("mail",e)}markNode(e){this.mark("node",e)}markSignal(e,n){this.mark(e,n)}mark(e,n){let r=`${e}:${n}`;this.dirty.has(r)||this.dirty.set(r,{id:n,kind:e}),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty.values()];this.dirty.clear();for(let{id:n,kind:r}of e)for(let i of this.subscribers)if(i.kinds.has(r))try{i.listener(n,r)}catch{}}callListenStart(e){try{e.onListenStart?.()}catch{}}async listen(e){this.listener!==void 0||this.listening!==void 0||(this.url=e,this.listening=this.connectListener().finally(()=>{this.listening=void 0}),await this.listening)}listener;listening;url;reconnect;check;async connectListener(){let e=new nXe.Client({connectionString:this.url,application_name:`crtr-signal-${process.pid}`,keepAlive:!0});e.on("notification",r=>{let i=r.payload??"",o=i.indexOf(":");if(o<0)return;let s=i.slice(0,o);CSn.has(s)&&this.mark(s,i.slice(o+1))});let n=()=>{this.listener===e&&(this.dropListener(e),this.scheduleReconnect())};e.on("error",n),e.on("end",n);try{await e.connect(),await e.query("LISTEN crtr_signal")}catch(r){throw e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{}),r}if(this.url===void 0){e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{});return}this.listener=e,this.startChecks(e,n);for(let r of[...this.subscribers])this.callListenStart(r)}startChecks(e,n){this.stopChecks(),this.check=setInterval(()=>{if(this.listener!==e)return;let r,i=new Promise((o,s)=>{r=setTimeout(()=>s(new Error("listen connection check timed out")),this.checkTimeoutMs)});Promise.race([e.query("SELECT 1"),i]).catch(()=>n()).finally(()=>clearTimeout(r))},this.checkIntervalMs),this.check.unref()}stopChecks(){this.check!==void 0&&clearInterval(this.check),this.check=void 0}dropListener(e){this.listener=void 0,this.stopChecks(),e.removeAllListeners(),e.on("error",()=>{}),e.end().catch(()=>{})}scheduleReconnect(){this.url===void 0||this.reconnect!==void 0||(this.reconnect=setTimeout(()=>{this.reconnect=void 0,this.url!==void 0&&(this.listening=this.connectListener().catch(()=>this.scheduleReconnect()).finally(()=>{this.listening=void 0}))},this.reconnectMs))}close(){this.url=void 0,this.reconnect!==void 0&&clearTimeout(this.reconnect),this.reconnect=void 0,this.stopChecks();let e=this.listener;return this.listener=void 0,this.scheduled!==void 0&&clearImmediate(this.scheduled),this.scheduled=void 0,this.dirty.clear(),this.subscribers.clear(),e===void 0?Promise.resolve():(e.removeAllListeners("notification"),e.removeAllListeners("error"),e.on("error",()=>{}),e.end().catch(()=>{}))}},adi=new wme});var oXe=x(()=>{"use strict";A$()});function RSn(t){switch(t){case kSn:return"context-nudge";case _Sn:return"bearings";case TSn:return"review-boundary";case ISn:return"situational";default:return}}function vme(t){return t.replace(/&(?:amp|lt|gt|quot|apos);/g,e=>({"&":"&","<":"<",">":">",""":'"',"'":"'"})[e])}function bme(t){let e={};hz.lastIndex=0;let n=0;for(;n<t.length&&!/^\s*$/.test(t.slice(n));){hz.lastIndex=n;let r=hz.exec(t);if(r===null)return null;let[,i,o,s]=r;if(i===void 0||Object.hasOwn(e,i))return null;e[i]=vme(o??s??""),n=hz.lastIndex}return e}function Eme(t){return typeof t.content=="string"?t.content:Array.isArray(t.content)?t.content.filter(e=>typeof e=="object"&&e!==null&&e.type==="text"&&typeof e.text=="string").map(e=>e.text).join(""):""}function MSn(t){let e=[],n=/<from\b([^>]*)>([\s\S]*?)<\/from>/g;for(let r of t.matchAll(n)){let i=bme(r[1]??"");if(i?.id===void 0)continue;let o=[],s=r[2]??"",a=/<entry\b([^>]*)>([\s\S]*?)<\/entry>/g;for(let u of s.matchAll(a)){let l=bme(u[1]??"");if(l?.kind===void 0)continue;let d=l.disposition==="human-answer"||l.disposition==="human-canceled"?l.disposition:"report";o.push({kind:l.kind,disposition:d,body:vme(u[2]??""),...l.ref===void 0?{}:{ref:l.ref}})}let c=i.updates===void 0?Number.NaN:Number(i.updates);e.push({id:i.id,updates:Number.isFinite(c)?c:o.length,finished:i.finished==="true"||o.some(u=>u.kind==="final"),entries:o})}return e}function PSn(t,e,n,r){return{kind:t,facts:e,body:n,senders:r}}function lXe(t){let e=/^<runtime\b([^>]*)>/.exec(t);if(e===null||!t.endsWith("</runtime>"))return null;let n=bme(e[1]??"");if(n?.kind===void 0)return null;let r=t.slice(e[0].length,-10),{kind:i,...o}=n,s=Object.freeze(o),a=i.includes(":")?vme(r):r;return PSn(i,s,a,i==="inbox"?MSn(a):[])}function pR(t){let e=Eme(t),n=lXe(e);if(n!==null)return n;if(t.role!=="custom")return null;let r=RSn(t.customType);return r===void 0?null:{kind:r,facts:Object.freeze({}),body:e,senders:[]}}function yS(t){return t.disposition==="human-answer"&&lXe(t.body.trim())===null}var _Sn,ISn,kSn,TSn,sXe,aXe,cXe,uXe,hz,AS=x(()=>{"use strict";_Sn="crtr-context",ISn="crtr-situational-context",kSn="crtr-context-nudge",TSn="crtr-review-boundary",sXe="Provider credentials were just updated (a new login landed). Your previous turn stopped on a provider authentication failure. Continue from where you left off and retry the work that failed.",aXe="The network connection is back online. Your previous turn stopped on a connection error (the network was down). Continue from where you left off and retry the work that failed.",cXe="Your previous turn stopped on a connection error reaching the model provider. Retrying now: continue from where you left off and retry the work that failed.",uXe="Your previous turn stopped on a provider fault. Continue from where you left off and retry the work that failed.";hz=/\s+([A-Za-z_:][A-Za-z0-9_:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)')/gy});var dXe=x(()=>{"use strict";AS()});function DSn(){let t=process.env.CRTR_API_URL;if(!(t===void 0||t==="")){if(!/^https?:\/\//.test(t))throw new Error(`CRTR_API_URL must be an http(s) URL: ${t}`);return t}}function y$(){let t=DSn();if(t===void 0)return $x({autostart:!1});let e=uYe();if(e===void 0)throw new Error("broker has no node token for CRTR_API_URL");return new ng({baseUrl:t,headers:{authorization:`Bearer ${e}`}})}function pXe(t,e){return y$().appendNodeLog(t,{record:e,expected_execution_id:BSn()})}function BSn(){let t=k7e();if(t===void 0||t==="")throw new Error("broker launch is missing CRTR_EXECUTION_ID");return t}async function hXe(t,e){return y$().recordNodeFault(t,e)}async function fXe(t,e={}){return y$().clearNodeFault(t,{...e.link===void 0?{}:{link:e.link},...e.preserveEpisode===void 0?{}:{preserve_episode:e.preserveEpisode}}).then(n=>n.cleared)}var A$=x(()=>{"use strict";V3();lYe();K3();tg();Kc();dYe();xS();iXe();oXe();dXe()});function OSn(t,e){mXe=mXe.then(async()=>{try{let{appended:n}=await pXe(t,e);n||process.stderr.write(`[broker] log.jsonl refused record: ${e}
|
|
92
92
|
`)}catch(n){process.stderr.write(`[broker] log.jsonl append failed (${n instanceof Error?n.message:String(n)}): ${e}
|
|
93
93
|
`)}})}function Rl(t){let e=q3();if(e===void 0)return!1;if(e.component==="broker"&&e.node_id!==void 0&&t.node_id!==void 0&&t.node_id!==e.node_id)throw new TypeError(`broker event target node_id must match bound node_id; received ${t.node_id}`);if(t.level==="debug"&&process.env.CRTR_LOG!=="debug")return!1;let n=SKe({...t,component:e.component,...e.node_id===void 0?{}:{node_id:e.node_id},...e.stream_id===void 0?{}:{stream_id:e.stream_id}}),r=_Ke(n);return e.component==="broker"&&e.node_id!==void 0&&(LSn??=ZE())?(OSn(e.node_id,r),!0):e.component==="daemon"?yKe(e.path,r):D3(e.path,r)}var LSn,mXe,xS=x(()=>{"use strict";Hhe();CKe();IKe();cfe();Kc();A$();mXe=Promise.resolve()});var gXe,yXe=x(()=>{"use strict";xS();gXe={sandboxUsdPerGbHour:"CRTR_LEDGER_SANDBOX_USD_PER_GB_HOUR",sandboxStandbyS:"CRTR_LEDGER_SANDBOX_STANDBY_S",storageUsdPerGbMonth:"CRTR_LEDGER_STORAGE_USD_PER_GB_MONTH",sandboxDiskUsdPerGbMonth:"CRTR_LEDGER_SANDBOX_DISK_USD_PER_GB_MONTH",infraFreeUsdPerMonth:"CRTR_LEDGER_INFRA_FREE_USD_PER_MONTH",takePct:"CRTR_LEDGER_TAKE_PCT",r2Move:"CRTR_LEDGER_R2_MOVE"}});var AXe=x(()=>{"use strict"});var Sme=x(()=>{"use strict"});import{createHash as NSn}from"node:crypto";function bXe(t){return t===void 0?"absent":NSn("sha256").update(JSON.stringify(t)).digest("hex")}function vXe(t,e){wXe.set(t,e)}function fz(){let t;try{t=Khe()}catch(n){if(n instanceof p$)return xXe();if(n instanceof d$)return Cme??xXe();throw n}let e=wXe.get(t);if(e!==void 0)return e;if(Cme!==void 0)return Cme;throw new _me(t)}function EXe(t){$Sn=t}function SXe(t){FSn=t}function mz(t){let e=fz().settings[t];return{settings:e===void 0?null:structuredClone(e),revision:bXe(e)}}function CXe(t){let e=fz().state[t];return e===void 0?{marketplaces:{},plugins:{},activeCanvas:null}:structuredClone(e)}function _Xe(){return structuredClone(fz().profiles)}function IXe(t){let e=fz().profiles.find(n=>n.profileId===t);return e===void 0?null:structuredClone(e)}var T$,_me,wXe,xXe,Cme,$Sn,FSn,R$=x(()=>{"use strict";eR();T$=class extends Error{constructor(){super("settings changed since the supplied revision"),this.name="SettingsRevisionConflictError"}},_me=class extends Error{constructor(e){super(`settings for ${e} are not loaded in this process`),this.name="PersonSettingsNotLoadedError"}},wXe=new Map;xXe=()=>({profiles:[],defaults:{},settings:{},state:{},apps:{}});$Sn=async()=>{throw new Error("no settings transport installed in this process")}});var kXe=x(()=>{"use strict"});function QSn(t){return t.grantee??"app:terminal"}function WSn(t){if(!TXe.test(t))throw ZT(`invalid profile id: ${t}`,{received:t,next:"Profile ids look like <slug>-<8-hex-chars> (as printed by `crtr profile new`). Pass an exact id or a profile name, not a raw path."})}function gz(t){WSn(t);let e=IXe(t);if(e===null)throw M3(`profile not found: ${t}`,{received:t});return $Ke(QSn(e.manifest),t).dir}function HSn(){return{entries:_Xe(),unreadableIds:[]}}function yz(){return HSn().entries}function qSn(t){let e=yz(),n=GSn(e,t,RXe);return n?{kind:"resolved",entry:n}:{kind:"absent"}}function GSn(t,e,n){if(TXe.test(e)){let i=t.find(o=>n(o).profileId===e);if(i!==void 0)return i}let r=t.filter(i=>n(i).name===e);if(r.length===1)return r[0];if(r.length>1){let i=r.map(o=>n(o).profileId);throw uKe(`profile name "${e}" matches ${i.length} profiles: ${i.join(", ")}`,{received:e,candidates:i,next:`Re-run with one exact profile id: ${i.join(", ")}.`})}return null}function jSn(t,e,n){let r=t.map(i=>`${n(i).profileId} (${n(i).name})`);return M3(`profile not found: ${e}`,{received:e,available:r,next:r.length>0?`Re-run with one of the profiles on this host: ${r.join(", ")} \u2014 or create one with \`crtr profile new --name <name>\`.`:"No profiles exist on this host yet \u2014 create one with `crtr profile new --name <name>`."})}function Qx(t){let e=qSn(t);if(e.kind==="resolved")return e.entry;throw jSn(yz(),t,RXe)}var TXe,RXe,hR=x(()=>{"use strict";Yc();xA();Sme();_l();R$();Qp();kXe();eR();TXe=/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/;RXe=t=>({profileId:t.profileId,name:t.manifest.name})});import{homedir as MXe}from"node:os";import{existsSync as zSn,statSync as VSn}from"node:fs";import{join as Az,resolve as PXe,dirname as KSn,sep as Ime}from"node:path";function Qd(){return Az(Zm(),"scope")}function YSn(t,e){if(!zSn(t)||If(t)===If(Az(MXe(),rS))||If(t).startsWith(`${If(Zhe())}${Ime}`)&&t.endsWith(`${Ime}home${Ime}${rS}`)||!ZE()&&(If(t)===If(e)||If(t)===If(Q3())))return!1;try{return VSn(t).isDirectory()}catch{return!1}}function JSn(t=process.cwd()){return DXe(t)[0]??null}function XSn(t,e){let n=[],r=If(MXe()),i=PXe(t);for(;;){let o=Az(i,rS);if(YSn(o,e)&&n.push(o),If(i)===r)return n;let s=KSn(i);if(s===i)return n;i=s}}function DXe(t=process.cwd(),e=she()||null){return ZSn(t,e)}function ZSn(t,e){let n=PXe(t),r=Qd(),i=[n];if(!ZE()&&e!==null&&e!=="")try{let{manifest:a}=Qx(e);for(let c of a.projects)i.push(c.path)}catch{}let o=new Set,s=[];for(let a of i)for(let c of XSn(a,r))o.has(c)||(o.add(c),s.push(c));return s}function BXe(t){return JSn(t)}function bA(t){return t==="builtin"?null:t==="user"?Qd():BXe()}function LXe(t){let e=t==="user"?Zm():bA(t);return e?Az(e,"plugins"):null}var wS=x(()=>{"use strict";Kc();Yc();AXe();Qp();hR();_l();xA()});import{join as eCn}from"node:path";function tCn(t){return eCn(t,sKe,aKe)}function nCn(t){let e;try{e=uS(t)}catch(n){return{status:"broken",error:n instanceof Error?n.message:String(n)}}return e===null?{status:"absent"}:typeof e!="object"||Array.isArray(e)?{status:"broken",error:"manifest is not a JSON object"}:{status:"ok",manifest:e}}function rCn(t){return nCn(tCn(t))}function OXe(t){let e=rCn(t);return e.status==="ok"?e.manifest:null}var kme=x(()=>{"use strict";Yc();_l()});import{existsSync as iCn,mkdirSync as oCn,readdirSync as $Xe,rmSync as FXe,rmdirSync as sCn,statSync as aCn,unlinkSync as cCn,writeFileSync as uCn}from"node:fs";import{randomUUID as lCn}from"node:crypto";function QXe(t){return Math.min(t*2,dCn)}function WXe(t){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,t)}function Rme(t,e){return`${t}/${Tme}${e}`}function Mme(t){try{return $Xe(t).find(e=>e.startsWith(Tme))?.slice(Tme.length)??null}catch{return null}}function HXe(t){let e=Number(t.split(".",1)[0]);if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(n){return n.code==="EPERM"}}function fCn(t){try{return $Xe(t).length===0}catch{return!1}}function mCn(t){try{return Date.now()-aCn(t).mtimeMs}catch{return 0}}function gCn(t,e){let n=Mme(t);if(n!==null){if(HXe(n))return;try{cCn(Rme(t,n))}catch(r){if(r.code==="ENOENT")return;throw r}}else{if(mCn(t)<=e)return;if(!fCn(t)){FXe(t,{recursive:!0,force:!0});return}}try{sCn(t)}catch(r){let i=r.code;if(i!=="ENOENT"&&i!=="ENOTEMPTY"&&i!=="EEXIST")throw r}}function fR(t){let e=Mme(t);if(e===null)return null;let n=Number(e.split(".",1)[0]);return Number.isSafeInteger(n)&&n>0?n:null}function qXe(t,e){let n=Date.now()+e,r=UXe;for(;;){let i=Mme(t);if(i===null||Number(i.split(".",1)[0])===process.pid||!HXe(i))return;let o=n-Date.now();if(o<=0)return;WXe(Math.min(r,o)),r=QXe(r)}}function NXe(t,e){let n=`${process.pid}.${lCn()}`;try{return oCn(t,{mode:448}),uCn(Rme(t,n),"",{flag:"wx",mode:384}),{path:t,token:n}}catch(r){if(r.code!=="EEXIST")throw r;return gCn(t,e),null}}function bS(t,e,n={}){let r=n.staleMs??pCn,i=Date.now()+(n.timeoutMs??hCn),o=UXe,s=NXe(t,r);for(;s===null;){if(Date.now()>=i)throw n.timeoutError?.()??new Error(`timed out waiting for the exclusive lock: ${t}`);WXe(Math.min(o,Math.max(0,i-Date.now()))),o=QXe(o),s=NXe(t,r)}try{return e()}finally{iCn(Rme(s.path,s.token))&&FXe(s.path,{recursive:!0,force:!0})}}var Tme,UXe,dCn,pCn,hCn,Wx=x(()=>{"use strict";Tme="owner.",UXe=10,dCn=250,pCn=3e4,hCn=5e3});import{join as yCn}from"node:path";function GXe(t,e){return yCn(t,"tmp",`${e}.swap.lock`)}function jXe(t,e){let n=fR(GXe(t,e));return n!==null&&n!==process.pid}function zXe(t,e){qXe(GXe(t,e),ACn)}var ACn,VXe=x(()=>{"use strict";Wx();ACn=2e3});import{join as Pme}from"node:path";function xCn(t,e){let n=t==="user"?mz("user").settings:uS(Pme(e,k3));return n&&n.plugins&&typeof n.plugins=="object"?n.plugins:{}}function wCn(t,e,n){let r=Object.keys(e);return r.every(i=>n.has(i))?[]:r.filter(i=>!n.has(i)&&jXe(t,i))}function xz(t,e){if(t==="user"&&N3())return[];let n=t!=="user"?Pme(e,"plugins"):LXe("user");if(n===void 0||!Jhe(n))return[];let r=xCn(t,e),i=KXe(t,n,r),o=wCn(e,r,new Set(i.map(s=>s.name)));if(o.length===0)return i;for(let s of o)zXe(e,s);return KXe(t,n,r)}function KXe(t,e,n){let r=[];for(let i of Xhe(e)){let o=Pme(e,i),s=OXe(o);if(!s)continue;let a=n[i],c=typeof a?.version=="string"?a.version:s.version;r.push({name:i,scope:t,root:o,manifest:s,enabled:typeof a?.enabled=="boolean"?a.enabled:!0,sourceMarketplace:typeof a?.source_marketplace=="string"?a.source_marketplace:void 0,version:c})}return r}var wz=x(()=>{"use strict";Yc();_l();kme();VXe();eR();R$();wS()});import{existsSync as bCn,realpathSync as vCn}from"node:fs";import{basename as ECn,dirname as SCn,join as Qpi,resolve as YXe}from"node:path";function mR(t){let e=YXe(t),n=e,r=[];for(;!bCn(n);){let i=SCn(n);if(i===n)return e;r.unshift(ECn(n)),n=i}return YXe(vCn(n),...r)}var JXe=x(()=>{"use strict"});function CCn(t){let e=Fi.indexOf(t);return`less ${Fi.map((r,i)=>i===e?"\u25CF":"\u25CB").map((r,i)=>i===0?r:`${i<=e?"\u2501\u2501\u2501\u2501":"\u2500\u2500\u2500\u2500"}${r}`).join("")} more ${bz[t]}`}function M$(t,e,n){let r=t.indexOf(e),i=r>=0?r:0;return t[(i+n+t.length)%t.length]}function Dme(t,e,n){let r=t.indexOf(e);return r>=0?t[(r+n+t.length)%t.length]:n>=0?t.find(i=>i>e)??t[0]:[...t].reverse().find(i=>i<e)??t[t.length-1]}function vS(t,e){return t==="true"?!0:t==="false"?!1:`${e} must be true or false`}function tZe(t,e){if(!/^\d+$/.test(t))return`${e} must be an integer >= 0`;let n=Number(t);return Number.isSafeInteger(n)?n:`${e} must be an integer >= 0`}function XXe(t,e){let n=tZe(t,e);return typeof n=="string"||n<1?`${e} must be an integer >= 1`:n}function eZe(t,e){let n=t.providerOptions[e];if(n!==void 0)return n;let r={};return t.providerOptions[e]=r,r}function RCn(){let t=[];for(let e of Object.values(nZe))e.surface==="settings"&&("setting"in e?t.push(e.setting):t.push(...Object.values(e.settings)));return t.sort((e,n)=>e.order-n.order)}var bz,ZXe,_Cn,ICn,P$,kCn,nZe,TCn,qpi,Bme=x(()=>{"use strict";Yc();bz={replies:"Replies only",summaries:"Messages + summaries",tools:"Tool calls",previews:"Previews",full:"Full"};ZXe=[!1,"notify","apply"],_Cn=[0,1,6,12,24,48,72,168],ICn=[1,2,3,4,5,6,8,10,12],P$="openai-codex";kCn=[1,2,3,4,5,6],nZe={schema_version:{surface:"specialized",owner:"internal schema migration"},marketplaces:{surface:"specialized",owner:"Plugins and pkg market commands"},plugins:{surface:"specialized",owner:"Plugins tab and pkg plugin commands"},auto_update:{surface:"settings",settings:{crtr:{key:"auto_update.crtr",label:"crouter updates",description:"Notify about crouter releases, install them automatically, or turn checks off.",valueConstraint:"true|false|notify|apply; true stores notify",applies:"Applies on the next crouter command.",group:"updates",order:70,format:t=>t.auto_update.crtr===!1?"off":t.auto_update.crtr,cycle:(t,e)=>{t.auto_update.crtr=M$(ZXe,t.auto_update.crtr,e)},setFromString:(t,e)=>{let n=e==="true"?"notify":e;return n!=="notify"&&n!=="apply"&&n!=="false"?"auto_update.crtr must be notify, apply, or false":(t.auto_update.crtr=n==="false"?!1:n,null)}},content:{key:"auto_update.content",label:"Content updates",description:"Notify about plugin and marketplace updates, apply them automatically, or turn checks off.",valueConstraint:"false|notify|apply",applies:"Applies on the next crouter command.",group:"updates",order:80,format:t=>t.auto_update.content===!1?"off":t.auto_update.content,cycle:(t,e)=>{t.auto_update.content=M$(ZXe,t.auto_update.content,e)},setFromString:(t,e)=>e!=="notify"&&e!=="apply"&&e!=="false"?"auto_update.content must be notify, apply, or false":(t.auto_update.content=e==="false"?!1:e,null)},interval_hours:{key:"auto_update.interval_hours",label:"Update interval",description:"Minimum hours between automatic update checks. Zero checks on every command.",valueConstraint:"integer >= 0",applies:"Applies on the next crouter command.",group:"updates",order:90,format:t=>`${t.auto_update.interval_hours}h`,cycle:(t,e)=>{t.auto_update.interval_hours=Dme(_Cn,t.auto_update.interval_hours,e)},setFromString:(t,e)=>{let n=tZe(e,"auto_update.interval_hours");return typeof n=="string"?n:(t.auto_update.interval_hours=n,null)}}}},max_panes_per_window:{surface:"settings",setting:{key:"max_panes_per_window",label:"Maximum panes",description:"Maximum human-review panes placed in one tmux window before using another window.",valueConstraint:"integer >= 1",applies:"Applies to the next pane placement.",group:"panes",order:20,format:t=>String(t.max_panes_per_window),cycle:(t,e)=>{t.max_panes_per_window=Dme(ICn,t.max_panes_per_window,e)},setFromString:(t,e)=>{let n=XXe(e,"max_panes_per_window");return typeof n=="string"?n:(t.max_panes_per_window=n,null)}}},auto_open_child_viewers:{surface:"settings",setting:{key:"auto_open_child_viewers",label:"Open child panes",description:"Open each managed child beside its watched parent. Off keeps new children running in the background.",valueConstraint:"true|false",applies:"Applies to the next managed child created; independent roots still open their attended viewer.",group:"panes",order:10,format:t=>t.auto_open_child_viewers?"on":"off",cycle:t=>{t.auto_open_child_viewers=!t.auto_open_child_viewers},setFromString:(t,e)=>{let n=vS(e,"auto_open_child_viewers");return typeof n=="string"?n:(t.auto_open_child_viewers=n,null)}}},brokerThresholds:{surface:"specialized",owner:"Broker limits tab"},lifecycle:{surface:"specialized",owner:"sys config set lifecycle.unattendedParkMs"},completion_bell:{surface:"settings",setting:{key:"completion_bell",label:"Completion bell",description:"Ring a short sound when the node in an attached viewer finishes a turn.",valueConstraint:"true|false",applies:"Applies on the next turn end.",group:"display",order:41,format:t=>t.completion_bell?"on":"off",cycle:t=>{t.completion_bell=!t.completion_bell},setFromString:(t,e)=>{let n=vS(e,"completion_bell");return typeof n=="string"?n:(t.completion_bell=n,null)}}},working_gerunds:{surface:"specialized",owner:"sys config set working_gerunds"},whip_mode:{surface:"settings",setting:{key:"whip_mode",label:"Whip mode",description:"Play the whip animation when you send a prompt and when a viewer opens for an agent with an initial prompt.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:39,format:t=>t.whip_mode?"on":"off",cycle:t=>{t.whip_mode=!t.whip_mode},setFromString:(t,e)=>{let n=vS(e,"whip_mode");return typeof n=="string"?n:(t.whip_mode=n,null)}}},page_surface:{surface:"settings",setting:{key:"page_surface",label:"Page human surface",description:"This host reads pages in a browser rather than a terminal. Agents are told the page module runs as written, HTML pages are offered, and document review and live display leave the command tree.",valueConstraint:"true|false",applies:"Applies when human command help is assembled.",group:"display",order:37,format:t=>t.page_surface?"on":"off",cycle:t=>{t.page_surface=!t.page_surface},setFromString:(t,e)=>{let n=vS(e,"page_surface");return typeof n=="string"?n:(t.page_surface=n,null)}}},whip_messages:{surface:"specialized",owner:"sys config set whip_messages"},whip_message_mode:{surface:"settings",setting:{key:"whip_message_mode",label:"Whip message",description:"What the whip action sends: a random line from whip_messages, or the fixed \u201CGo faster\u201D.",valueConstraint:iS.join("|"),applies:"Applies on the next attach.",group:"display",order:40,format:t=>t.whip_message_mode==="go-faster"?"go faster":"random",cycle:(t,e)=>{t.whip_message_mode=M$(iS,t.whip_message_mode,e)},setFromString:(t,e)=>iS.includes(e)?(t.whip_message_mode=e,null):`whip_message_mode must be one of: ${iS.join("|")}`}},mouse_mode_default:{surface:"settings",setting:{key:"mouse_mode_default",label:"Default mouse mode",description:"Initial mouse wheel scrolling for each attached viewer.",valueConstraint:oS.join("|"),applies:"Applies on the next attach.",group:"display",order:38,format:t=>t.mouse_mode_default==="tmux"?"follow tmux":t.mouse_mode_default,cycle:(t,e)=>{t.mouse_mode_default=M$(oS,t.mouse_mode_default,e)},setFromString:(t,e)=>oS.includes(e)?(t.mouse_mode_default=e,null):`mouse_mode_default must be one of: ${oS.join("|")}`}},live_cycles:{surface:"settings",setting:{key:"live_cycles",label:"Live cycles",description:"Trailing refresh cycles rendered at full fidelity; older cycles condense to text.",valueConstraint:"integer >= 1",applies:"Applies on the next attach.",group:"display",order:50,format:t=>String(t.live_cycles),cycle:(t,e)=>{t.live_cycles=Dme(kCn,t.live_cycles,e)},setFromString:(t,e)=>{let n=XXe(e,"live_cycles");return typeof n=="string"?n:(t.live_cycles=n,null)}}},condensed_history:{surface:"settings",setting:{key:"condensed_history",label:"Condensed history",description:"Messages retained from condensed cycles. Tool calls are never kept.",valueConstraint:sS.join("|"),applies:"Applies on the next attach.",group:"display",order:60,format:t=>t.condensed_history,cycle:(t,e)=>{t.condensed_history=M$(sS,t.condensed_history,e)},setFromString:(t,e)=>sS.includes(e)?(t.condensed_history=e,null):`condensed_history must be one of: ${sS.join("|")}`}},bash_tool_purpose:{surface:"settings",setting:{key:"bash_tool_purpose",label:"Bash purpose field",description:"Expose the optional purpose label to agents in the bash tool schema. Off removes the field without disabling the bash valve.",valueConstraint:"true|false",applies:"Applies on the next node session.",group:"display",order:25,format:t=>t.bash_tool_purpose?"on":"off",cycle:t=>{t.bash_tool_purpose=!t.bash_tool_purpose},setFromString:(t,e)=>{let n=vS(e,"bash_tool_purpose");return typeof n=="string"?n:(t.bash_tool_purpose=n,null)}}},verbosity:{surface:"settings",setting:{key:"verbosity",label:"Verbosity",description:"How much of a transcript the viewer shows, from one rewritten reply per message to every tool call untruncated. Ctrl+O shows more and Ctrl+Shift+O less in the open viewer only; this sets where every viewer starts.",valueConstraint:Fi.join("|"),applies:"Applies on the next attach.",group:"display",order:30,format:t=>t.verbosity,display:t=>CCn(t.verbosity),cycle:(t,e)=>{let n=Fi.indexOf(t.verbosity)+e;t.verbosity=Fi[Math.max(0,Math.min(Fi.length-1,n))]},setFromString:(t,e)=>Fi.includes(e)?(t.verbosity=e,null):`verbosity must be one of: ${Fi.join("|")}`}},document_port:{surface:"settings",setting:{key:"document_port",label:"Document browser port",description:"Fixed localhost port where crtrd serves editable document pages.",valueConstraint:"1-65535",applies:"Applies after daemon handover and on the next attach.",group:"display",order:37.5,format:t=>String(t.document_port),cycle:(t,e)=>{t.document_port=Math.max(1,Math.min(65535,t.document_port+e))},setFromString:(t,e)=>{let n=Number(e);return!/^\d+$/.test(e)||!Number.isInteger(n)||n<1||n>65535?"document_port must be an integer from 1 to 65535":(t.document_port=n,null)}}},detailed_tool_recaps:{surface:"settings",setting:{key:"detailed_tool_recaps",label:"Detailed tool recaps",description:"Show each document read and edited file in folded tool recaps. Off shows a compact count line instead.",valueConstraint:"true|false",applies:"Applies on the next attach.",group:"display",order:36,format:t=>t.detailed_tool_recaps?"on":"off",cycle:t=>{t.detailed_tool_recaps=!t.detailed_tool_recaps},setFromString:(t,e)=>{let n=vS(e,"detailed_tool_recaps");return typeof n=="string"?n:(t.detailed_tool_recaps=n,null)}}},keybindings:{surface:"specialized",owner:"Keybindings tab"},tmux_passthrough:{surface:"specialized",owner:"Keybindings tab"},providerOptions:{surface:"settings",settings:{"openai-codex.fastMode":{key:`providerOptions.${P$}.fastMode`,label:"Codex fast mode",description:"Serve Codex turns at the ChatGPT priority tier: about 1.5x faster generation for about 2x the credits. Displayed cost does not reflect the premium.",valueConstraint:"true|false",applies:"Applies on each node's next turn.",group:"providers",order:40,format:t=>t.providerOptions[P$]?.fastMode?"on":"off",cycle:t=>{let e=eZe(t,P$);e.fastMode=!e.fastMode},setFromString:(t,e)=>{let n=vS(e,`providerOptions.${P$}.fastMode`);return typeof n=="string"?n:(eZe(t,P$).fastMode=n,null)}}}},modelLadders:{surface:"specialized",owner:"Models tab"},modelRoutes:{surface:"specialized",owner:"Models route declarations"},modelRouting:{surface:"specialized",owner:"Models route declarations"},kinds:{surface:"specialized",owner:"Models tab and kind registry"},page_components:{surface:"specialized",owner:"Page component catalog: product-registered page component kinds"},remoteCanvas:{surface:"specialized",owner:"canvas config commands"},api:{surface:"specialized",owner:"sys connect"},paths:{surface:"specialized",owner:"runtime layout"},store:{surface:"specialized",owner:"daemon conversation store"},runtime:{surface:"specialized",owner:"app-facing listener"},spawnEnv:{surface:"specialized",owner:"spawn environment allow-list"},bin:{surface:"specialized",owner:"bare-binary contributions on every node PATH"},humanActions:{surface:"specialized",owner:"scope-configured human completion actions"}},TCn=Object.keys(nZe);qpi=RCn()});function D$(t){return t.split("-").map(e=>e===""?"":`${e[0].toUpperCase()}${e.slice(1)}`).join("")}function yR(t){try{let e=JSON.stringify(t);return e===void 0?String(t):e}catch{return String(t)}}function gR(t,e,n,r){if(t!==void 0){if(typeof t!="string"||t.trim()==="")throw new Error(`${n}[${r}].${e} must be a non-empty string; received ${yR(t)}`);return t.trim()}}function $me(t,e="page_components"){if(t===void 0)return[];if(!Array.isArray(t))throw new Error(`${e} must be an array; received ${yR(t)}`);let n=new Set,r=new Set;return t.map((i,o)=>{let s;if(typeof i=="string")s={kind:i.trim()};else if(i!==null&&typeof i=="object"&&!Array.isArray(i)){let u=i,l=Object.keys(u).filter(d=>!["kind","description","useWhen","doc","display"].includes(d));if(l.length>0)throw new Error(`${e}[${o}] has unknown field(s): ${l.join(", ")}`);if(typeof u.kind!="string")throw new Error(`${e}[${o}].kind must be a string; offending entry: ${yR(i)}`);if(u.display!==void 0&&typeof u.display!="boolean")throw new Error(`${e}[${o}].display must be a boolean; offending entry: ${yR(i)}`);s={kind:u.kind.trim(),...gR(u.description,"description",e,o)===void 0?{}:{description:gR(u.description,"description",e,o)},...gR(u.useWhen,"useWhen",e,o)===void 0?{}:{useWhen:gR(u.useWhen,"useWhen",e,o)},...gR(u.doc,"doc",e,o)===void 0?{}:{doc:gR(u.doc,"doc",e,o)},...u.display===!0?{display:!0}:{}}}else throw new Error(`${e}[${o}] must be a string or component object; offending entry: ${yR(i)}`);let a=s.kind;if(!PCn.test(a))throw new Error(`${e}[${o}] has invalid page kind ${yR(a)}; expected /^[a-z][a-z0-9-]{0,63}$/`);if(DCn.has(a)||MCn.includes(a))throw new Error(`${e}[${o}] collides with built-in page kind "${a}"`);if(n.has(a))throw new Error(`${e}[${o}] duplicates page kind "${a}"`);let c=D$(a);if(vz.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which collides with a built-in page component`);if(r.has(c))throw new Error(`${e}[${o}] kind "${a}" derives JSX tag "${c}", which duplicates another product page component`);return n.add(a),r.add(c),s})}function iZe(t){let e=new Map,n=new Map,r=[];for(let i of t)for(let o of i.components){let s=e.get(o.kind);if(s!==void 0)throw new Error(`page component kind "${o.kind}" is registered by both ${s} and ${i.origin}`);let a=D$(o.kind),c=n.get(a);if(c!==void 0)throw new Error(`page component kind "${o.kind}" (${i.origin}) derives JSX tag "${a}", which duplicates kind "${c.kind}" from ${c.origin}`);e.set(o.kind,i.origin),n.set(a,{kind:o.kind,origin:i.origin}),r.push(o)}return r}function oZe(t,e){return e.find(n=>n.kind===t)}var Lme,MCn,PCn,DCn,rZe,Ome,vz,Nme,B$=x(()=>{"use strict";Lme=["options","text","table","cards","chart"],MCn=["page","step"],PCn=/^[a-z][a-z0-9-]{0,63}$/,DCn=new Set(Lme),rZe=[{kind:"page",tag:"Page",description:"the page itself: title, subtitle, and every step it contains",useWhen:"use as the single root element every page returns",builtin:!0,structural:!0},{kind:"step",tag:"Step",description:"one step inside a Page",useWhen:"use for each step the user sees and completes in sequence",builtin:!0,structural:!0},{kind:"options",tag:"UserQuestion",description:"known alternatives with single or multiple selection",useWhen:"use when the user picks among known alternatives, optionally with freetext",builtin:!0,structural:!1},{kind:"text",tag:"UserText",description:"writing surface whose answer is the text the user hands back",useWhen:"use when you need prose from the user \u2014 a value they write, or a draft they revise; prose they only read is a plain element",builtin:!0,structural:!1},{kind:"table",tag:"UserTable",description:"rows and columns with optional selection",useWhen:"use when structured records are easiest to compare in rows and columns",builtin:!0,structural:!1},{kind:"cards",tag:"UserCards",description:"visual records with optional selection",useWhen:"use when the user compares or picks richer items than a compact option list can carry",builtin:!0,structural:!1},{kind:"chart",tag:"Chart",description:"line, bar, or area data visualization",useWhen:"use when shape, trend, or magnitude matters more than exact tabular values",builtin:!0,structural:!1}];Ome=Object.fromEntries(rZe.filter(t=>!t.structural).map(t=>[t.tag,t.kind])),vz=new Set(rZe.map(t=>t.tag)),Nme=new Set(["Card","CardHeader","CardTitle","CardDescription","CardContent","CardFooter","CardAction","Badge","Button","Separator","Progress","Alert","AlertTitle","AlertDescription","Table","TableHeader","TableBody","TableFooter","TableRow","TableHead","TableCell","TableCaption","Tabs","TabsList","TabsTrigger","TabsContent","Accordion","AccordionItem","AccordionTrigger","AccordionContent"])});import{basename as lZe,join as dZe}from"node:path";import{existsSync as LCn,mkdirSync as Jpi,statSync as Xpi}from"node:fs";function OCn(t){return dZe(t,k3)}function NCn(t){return dZe(t,cKe)}function pZe(t){let e=mR(t),n=mR(Qd());if(e===n)return{key:"user",kind:"user",root:n};if(lZe(e)===".crouter")return{key:"project",kind:"project",root:e};for(let r of yz()){let i=mR(gz(r.profileId));if(e===i)return{key:`profile:${r.profileId}`,kind:"profile",root:i,profileId:r.profileId}}throw new Error(`settings root is not a recognized owner: ${t}`)}function hZe(t){if(lZe(t)===".crouter"){let e;try{e=mR(t)}catch(n){if(n.code==="ENOENT")return null;throw n}if(e!==mR(Qd()))return uS(OCn(t))}return mz(pZe(t).key).settings}function Il(t){let e=$Cn[FCn];if(e){if(t!=="user")throw new Error(`broker config snapshot has no ${t} scope`);return e.user}let n=bA(t);return n?UCn(n):R3()}function UCn(t){let e=hZe(t);return e?p_n(e):R3()}function QCn(t){let e=uS(NCn(t));return{marketplaces:e?.marketplaces??{},plugins:e?.plugins??{},activeCanvas:e?.activeCanvas??null,...e?.last_self_check===void 0?{}:{last_self_check:e.last_self_check}}}function fZe(t){let e=bA(t);return e?t==="project"?LCn(e)?QCn(e):Whe():CXe(pZe(e).key):Whe()}function WCn(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))Array.isArray(r)&&r.every(i=>typeof i=="string")&&(e[n]=[...r]);return e}function AR(t){return Array.isArray(t)?[...new Set(t.filter(e=>typeof e=="string"&&nS.has(e)&&HCn.has(e)))]:[]}function qCn(t,e=Qhe()){let n=e;if(t===null||typeof t!="object")return n;let r=t,i={anthropic:{...n.anthropic},openai:{...n.openai},...n.defaultProvider!==void 0?{defaultProvider:n.defaultProvider}:{}};(r.defaultProvider==="anthropic"||r.defaultProvider==="openai")&&(i.defaultProvider=r.defaultProvider);for(let o of["anthropic","openai"]){let s=r[o];if(!(s===null||typeof s!="object"))for(let[a,c]of Object.entries(s))(a==="ultra"||a==="strong"||a==="medium"||a==="light")&&typeof c=="string"&&(i[o][a]=c)}return i}function mZe(t){return t==="ultra"||t==="strong"||t==="medium"||t==="light"}function Fme(){return Object.create(null)}function Ez(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function jCn(t){let e=Fme();for(let[n,r]of Object.entries(t??{}))Ez(e,n,r);return e}function L$(t,e){Rl({level:"warn",event:"config.model_routes.invalid",fields:{route_id:t,rule:e}})}function zCn(t,e={}){let n=jCn(e);if(t===null||typeof t!="object"||Array.isArray(t))return n;for(let[r,i]of Object.entries(t)){if(r.trim()===""){L$(r,"route id must be a non-empty string");continue}if(i===null||typeof i!="object"||Array.isArray(i)){L$(r,"route must be an object");continue}let o=i,s=n[r],a={...s},c;for(let u of["family","credentialSource","providerId"]){let l=o[u];if(l!==void 0){if(typeof l!="string"||l.trim()===""){c=`${u} must be a non-empty string`;break}a[u]=l}}if(c===void 0&&o.models!==void 0)if(o.models===null||typeof o.models!="object"||Array.isArray(o.models))c="models must be an object";else{let u={...s?.models};for(let[l,d]of Object.entries(o.models)){if(!mZe(l)){c=`models.${l} is not a model strength`;break}if(typeof d!="string"||d.trim()===""){c=`models.${l} must be a non-empty provider/id ref`;break}let p=d.indexOf("/");if(p<=0||p===d.length-1){c=`models.${l} must be provider/id`;break}u[l]=d}a.models=u}if(c===void 0&&a.models!==void 0&&a.providerId!==void 0){for(let[u,l]of Object.entries(a.models))if(l.slice(0,l.indexOf("/"))!==a.providerId){c=`models.${u} provider prefix must equal providerId`;break}}if(c!==void 0){L$(r,c);continue}Ez(n,r,a)}return n}function VCn(t){let e=Fme(),n=Fme();for(let[r,i]of Object.entries(t)){if(i.family===void 0||i.credentialSource===void 0||i.providerId===void 0||i.models===void 0){L$(r,"route must include family, credentialSource, providerId, and models");continue}let o=GCn.filter(s=>i.models[s]===void 0);if(o.length>0){L$(r,`incomplete route; missing strengths: ${o.join(", ")}`),Ez(n,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models});continue}Ez(e,r,{family:i.family,credentialSource:i.credentialSource,providerId:i.providerId,models:i.models})}return{complete:e,legacy:n}}function KCn(t,e){if(t===void 0||t===null||typeof t!="object"||Array.isArray(t))return e;let n=t,r=o=>Array.isArray(o)&&o.every(s=>typeof s=="string"&&s.trim()!=="")?[...o]:void 0,i=Array.isArray(n.strengthFallback)&&n.strengthFallback.every(o=>mZe(o))?[...n.strengthFallback]:void 0;return{...r(n.credentialSourceOrder)!==void 0?{credentialSourceOrder:r(n.credentialSourceOrder)}:{},...r(n.familyOrder)!==void 0?{familyOrder:r(n.familyOrder)}:{},...i!==void 0?{strengthFallback:i}:{}}}function YCn(t){return t!==""&&t.replace(/\*/g,"")===""}function JCn(t,e=[]){let n=t,r=Array.isArray(n?.allow)?n.allow.filter(i=>typeof i=="string"):[];for(let i of r)if(YCn(i))throw new Error(`spawnEnv.allow: "${i}" matches every env var name (inherit-all) \u2014 this is exactly the leak the spawn-env boundary closes. Name the specific vars/prefixes you actually need instead (e.g. "AWS_*", "GIT_ASKPASS").`);return{allow:[...new Set([...e,...r])]}}function XCn(t,e={}){let n={};for(let[r,i]of Object.entries(e))n[r]={...i};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){if(i===null||typeof i!="object")continue;let o={...n[r]},s=i.fastMode;typeof s=="boolean"&&(o.fastMode=s),n[r]=o}return n}function e_n(t,e){if(e==="bin"&&ZCn.has(t))return`${e}.${t} is reserved by crouter \u2014 pick another bare command name`;if(!sZe.test(t))return`${e}.${t} is not a safe bare command name (expected ${sZe.source})`}function t_n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e={};for(let[n,r]of Object.entries(t))e_n(n,"bin")===void 0&&(typeof r!="string"||r.trim()===""||(e[n]=r));return e}function n_n(t){if(t===null||typeof t!="object"||Array.isArray(t))return[{name:"humanActions",reason:"humanActions must be a JSON object mapping action names to {argv, cwd}",block:!0}];let e=[];for(let[n,r]of Object.entries(t)){let i=[];if(aZe.test(n)||i.push(`action name must match ${aZe.source}`),r===null||typeof r!="object"||Array.isArray(r))i.push("action must be an object with argv and cwd");else{let o=r,s=Object.keys(o).filter(a=>a!=="argv"&&a!=="cwd");s.length>0&&i.push(`action has unsupported field${s.length===1?"":"s"}: ${s.join(", ")}`),(!Array.isArray(o.argv)||o.argv.length===0||!o.argv.every(a=>typeof a=="string"&&a.length>0))&&i.push("argv must be a non-empty array of non-empty strings"),(typeof o.cwd!="string"||o.cwd.length===0)&&i.push("cwd is required and must be a non-empty string")}i.length>0&&e.push({name:n,reason:i.join("; ")})}return e}function r_n(t){if(t===null||typeof t!="object"||Array.isArray(t))return{};let e=new Set(n_n(t).map(r=>r.name)),n={};for(let[r,i]of Object.entries(t)){if(e.has(r))continue;let o=i;n[r]={argv:[...o.argv],cwd:o.cwd}}return n}function i_n(t){if(t===null||typeof t!="object")return null;let e=t,n={};typeof e.whenToUse=="string"&&e.whenToUse.trim()!==""&&(n.whenToUse=e.whenToUse),typeof e.model=="string"&&e.model.trim()!==""&&(n.model=e.model),typeof e.orchestratorModel=="string"&&e.orchestratorModel.trim()!==""&&(n.orchestratorModel=e.orchestratorModel);let r=i=>Array.isArray(i)&&i.every(o=>typeof o=="string");return r(e.tools)&&(n.tools=e.tools),r(e.extensions)&&(n.extensions=e.extensions),r(e.availableTo)&&(n.availableTo=e.availableTo),Object.keys(n).length>0?n:null}function o_n(t,e=Uhe()){let n={...e};if(t!==null&&typeof t=="object")for(let[r,i]of Object.entries(t)){let o=i_n(i);if(o===null)continue;let s=n[r];s!==void 0?n[r]={...s,...o}:o.whenToUse!==void 0&&(n[r]=o)}return n}function Sz(){let t=[{origin:"config.json",components:Il("user").page_components}],e=bA("user");if(e!==null){let n=xz("user",e).filter(r=>r.enabled&&r.manifest.page_components!==void 0).sort((r,i)=>r.name.localeCompare(i.name));for(let r of n){let i=`plugin "${r.name}" page_components`;t.push({origin:`plugin "${r.name}"`,components:$me(r.manifest.page_components,i)})}}return iZe(t)}function s_n(t){if(t===null||typeof t!="object")return null;let e=t;if(typeof e.previewEndpoint!="string"||e.previewEndpoint.trim()===""||typeof e.relayTokenRef!="string"||e.relayTokenRef.trim()==="")return null;let n={previewEndpoint:e.previewEndpoint,relayTokenRef:e.relayTokenRef};return typeof e.cpOrigin=="string"&&e.cpOrigin.trim()!==""&&(n.cpOrigin=e.cpOrigin),n}function a_n(t,e=Fhe()){let n={...e.targets};if(t!==null&&typeof t=="object"){let r=t;if(r.targets!==null&&typeof r.targets=="object")for(let[i,o]of Object.entries(r.targets)){let s=s_n(o);s!==null&&(n[i]=s)}}return{targets:n}}function cZe(t,e){return t===!0?"notify":t===!1?!1:t==="notify"||t==="apply"?t:e}function O$(t,e){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=1?t:e}function c_n(t,e){let n=t!==null&&typeof t=="object"?t:{},r=O$(n.warning,e.warning),i=O$(n.automaticReviveCap,e.automaticReviveCap);return r<=i?{warning:r,automaticReviveCap:i}:{...e}}function u_n(t,e){return{unattendedParkMs:O$((t!==null&&typeof t=="object"?t:{}).unattendedParkMs,e.unattendedParkMs)}}function l_n(t){if(!Array.isArray(t))return[...T3];let e=t.filter(n=>typeof n=="string"&&n.trim()!=="").map(n=>n.trim());return e.length>0?e:[...T3]}function d_n(t,e){if(t===null||typeof t!="object")return{...e};let n=t.tcp;return{tcp:typeof n=="string"?n:e.tcp}}function p_n(t){!uZe&&t.ledger!==void 0&&(uZe=!0,Rl({level:"warn",event:"config.ledger.ignored",fields:{variables:Object.values(gXe)}}));let e=R3(),n=e.schema_version,r=t.marketplaces===void 0?{}:t.marketplaces,i=t.plugins===void 0?{}:t.plugins,o=t.auto_update,s=o&&typeof o.interval_hours=="number"?o.interval_hours:void 0,a=s!==void 0&&Number.isFinite(s)&&s>=0?s:e.auto_update.interval_hours,c={crtr:cZe(o?.crtr,e.auto_update.crtr),content:cZe(o?.content,e.auto_update.content),interval_hours:a},u=t.max_panes_per_window,l=O$(u,e.max_panes_per_window),d=typeof t.auto_open_child_viewers=="boolean"?t.auto_open_child_viewers:e.auto_open_child_viewers,p=c_n(t.brokerThresholds,e.brokerThresholds),h=u_n(t.lifecycle,e.lifecycle),f=typeof t.completion_bell=="boolean"?t.completion_bell:e.completion_bell,m=t.working_gerunds===void 0?[...e.working_gerunds]:iKe(t.working_gerunds),g=typeof t.whip_mode=="boolean"?t.whip_mode:e.whip_mode,A=$me(t.page_components),b=typeof t.page_surface=="boolean"?t.page_surface:e.page_surface,v=l_n(t.whip_messages),S=iS.includes(t.whip_message_mode)?t.whip_message_mode:e.whip_message_mode,_=oS.includes(t.mouse_mode_default)?t.mouse_mode_default:e.mouse_mode_default,I=O$(t.live_cycles,e.live_cycles),R=sS.includes(t.condensed_history)?t.condensed_history:e.condensed_history,D=typeof t.bash_tool_purpose=="boolean"?t.bash_tool_purpose:e.bash_tool_purpose,B=Fi.includes(t.verbosity)?t.verbosity:e.verbosity,L=typeof t.detailed_tool_recaps=="boolean"?t.detailed_tool_recaps:e.detailed_tool_recaps,F=Number.isInteger(t.document_port)&&t.document_port>=1&&t.document_port<=65535?t.document_port:e.document_port,q=WCn(t.keybindings),j=AR(t.tmux_passthrough),Q=qCn(t.modelLadders),he=XCn(t.providerOptions,e.providerOptions),K=VCn(zCn(t.modelRoutes)),Te=K.complete,Fe=KCn(t.modelRouting,void 0),Ze=o_n(t.kinds),Ct=a_n(t.remoteCanvas),en=d_n(t.api,e.api),Be=t.paths;if(Be?.user_files!==void 0&&(typeof Be.user_files!="string"||!Be.user_files.startsWith("/")))throw new Error("paths.user_files must be an absolute path");let X=t.store,Ue=t.runtime;if(Ue?.person_uids!==void 0&&(!Array.isArray(Ue.person_uids)||!Ue.person_uids.every(rn=>Number.isSafeInteger(rn)&&rn>=0)))throw new Error("runtime.person_uids must be an array of nonnegative integer uids");let Ke=JCn(t.spawnEnv,e.spawnEnv?.allow),Qt=t_n(t.bin),Nt=r_n(t.humanActions);return{bin:Qt,humanActions:Nt,schema_version:n,marketplaces:r,plugins:i,auto_update:c,max_panes_per_window:l,auto_open_child_viewers:d,brokerThresholds:p,lifecycle:h,completion_bell:f,working_gerunds:m,whip_mode:g,page_components:A,page_surface:b,whip_messages:v,whip_message_mode:S,mouse_mode_default:_,live_cycles:I,condensed_history:R,bash_tool_purpose:D,verbosity:B,detailed_tool_recaps:L,document_port:F,keybindings:q,tmux_passthrough:j,modelLadders:Q,providerOptions:he,...Object.keys(Te).length>0?{modelRoutes:Te}:{},...Object.keys(K.legacy).length>0?{legacyModelRoutes:K.legacy}:{},...Fe!==void 0?{modelRouting:Fe}:{},kinds:Ze,remoteCanvas:Ct,api:en,...Be?{paths:Be}:{},...X?{store:X}:{},...Ue?{runtime:Ue}:{},spawnEnv:Ke}}function h_n(t){return hZe(t)}function gZe(t){let e=bA(t);return e?h_n(e):null}var $Cn,FCn,HCn,GCn,sZe,ZCn,aZe,uZe,Nd=x(()=>{"use strict";Kc();Yc();C3();Qp();xS();yXe();_l();wS();wz();hR();JXe();R$();Wx();Bme();I3();B$();$Cn=globalThis,FCn=Symbol.for("crtr.broker.config-snapshot");HCn=new Set(Bd.filter(c$).map(t=>t.id));GCn=["ultra","strong","medium","light"];sZe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/,ZCn=new Set(["crtr","crtrd"]);aZe=/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;uZe=!1});var EA=$((ffi,LZe)=>{"use strict";var DZe=["nodebuffer","arraybuffer","fragments"],BZe=typeof Blob<"u";BZe&&DZe.push("blob");LZe.exports={BINARY_TYPES:DZe,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:BZe,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var q$=$((mfi,Mz)=>{"use strict";var{EMPTY_BUFFER:iIn}=EA(),age=Buffer[Symbol.species];function oIn(t,e){if(t.length===0)return iIn;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let o=t[i];n.set(o,r),r+=o.length}return r<e?new age(n.buffer,n.byteOffset,r):n}function OZe(t,e,n,r,i){for(let o=0;o<i;o++)n[r+o]=t[o]^e[o&3]}function NZe(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function sIn(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function cge(t){if(cge.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new age(t):ArrayBuffer.isView(t)?e=new age(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),cge.readOnly=!1),e}Mz.exports={concat:oIn,mask:OZe,toArrayBuffer:sIn,toBuffer:cge,unmask:NZe};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=Z("bufferutil");Mz.exports.mask=function(e,n,r,i,o){o<48?OZe(e,n,r,i,o):t.mask(e,n,r,i,o)},Mz.exports.unmask=function(e,n){e.length<32?NZe(e,n):t.unmask(e,n)}}catch{}});var UZe=$((gfi,FZe)=>{"use strict";var $Ze=Symbol("kDone"),uge=Symbol("kRun"),lge=class{constructor(e){this[$Ze]=()=>{this.pending--,this[uge]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[uge]()}[uge](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$Ze])}}};FZe.exports=lge});var SR=$((yfi,qZe)=>{"use strict";var G$=Z("zlib"),QZe=q$(),aIn=UZe(),{kStatusCode:WZe}=EA(),cIn=Buffer[Symbol.species],uIn=Buffer.from([0,0,255,255]),Dz=Symbol("permessage-deflate"),SA=Symbol("total-length"),vR=Symbol("callback"),zx=Symbol("buffers"),ER=Symbol("error"),Pz,dge=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!Pz){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Pz=new aIn(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[vR];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let o=+i;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=o}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){Pz.add(i=>{this._decompress(e,n,(o,s)=>{i(),r(o,s)})})}compress(e,n,r){Pz.add(i=>{this._compress(e,n,(o,s)=>{i(),r(o,s)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?G$.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=G$.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Dz]=this,this._inflate[SA]=0,this._inflate[zx]=[],this._inflate.on("error",dIn),this._inflate.on("data",HZe)}this._inflate[vR]=r,this._inflate.write(e),n&&this._inflate.write(uIn),this._inflate.flush(()=>{let o=this._inflate[ER];if(o){this._inflate.close(),this._inflate=null,r(o);return}let s=QZe.concat(this._inflate[zx],this._inflate[SA]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[SA]=0,this._inflate[zx]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,s)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let o=`${i}_max_window_bits`,s=typeof this.params[o]!="number"?G$.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=G$.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[SA]=0,this._deflate[zx]=[],this._deflate.on("data",lIn)}this._deflate[vR]=r,this._deflate.write(e),this._deflate.flush(G$.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=QZe.concat(this._deflate[zx],this._deflate[SA]);n&&(o=new cIn(o.buffer,o.byteOffset,o.length-4)),this._deflate[vR]=null,this._deflate[SA]=0,this._deflate[zx]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,o)})}};qZe.exports=dge;function lIn(t){this[zx].push(t),this[SA]+=t.length}function HZe(t){if(this[SA]+=t.length,this[Dz]._maxPayload<1||this[SA]<=this[Dz]._maxPayload){this[zx].push(t);return}this[ER]=new RangeError("Max payload size exceeded"),this[ER].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ER][WZe]=1009,this.removeListener("data",HZe),this.reset()}function dIn(t){if(this[Dz]._inflate=null,this[ER]){this[vR](this[ER]);return}t[WZe]=1007,this[vR](t)}});var CR=$((Afi,Bz)=>{"use strict";var{isUtf8:GZe}=Z("buffer"),{hasBlob:pIn}=EA(),hIn=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function fIn(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function pge(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function mIn(t){return pIn&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Bz.exports={isBlob:mIn,isValidStatusCode:fIn,isValidUTF8:pge,tokenChars:hIn};if(GZe)Bz.exports.isValidUTF8=function(t){return t.length<24?pge(t):GZe(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=Z("utf-8-validate");Bz.exports.isValidUTF8=function(e){return e.length<32?pge(e):t(e)}}catch{}});var yge=$((xfi,XZe)=>{"use strict";var{Writable:gIn}=Z("stream"),jZe=SR(),{BINARY_TYPES:yIn,EMPTY_BUFFER:zZe,kStatusCode:AIn,kWebSocket:xIn}=EA(),{concat:hge,toArrayBuffer:wIn,unmask:bIn}=q$(),{isValidStatusCode:vIn,isValidUTF8:VZe}=CR(),Lz=Buffer[Symbol.species],Hp=0,KZe=1,YZe=2,JZe=3,fge=4,mge=5,Oz=6,gge=class extends gIn{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||yIn[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxBufferedChunks=e.maxBufferedChunks|0,this._maxFragments=e.maxFragments|0,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xIn]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=Hp}_write(e,n,r){if(this._opcode===8&&this._state==Hp)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new Lz(r.buffer,r.byteOffset+e,r.length-e),new Lz(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new Lz(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case Hp:this.getInfo(e);break;case KZe:this.getPayloadLength16(e);break;case YZe:this.getPayloadLength64(e);break;case JZe:this.getMask();break;case fge:this.getData(e);break;case mge:case Oz:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[jZe.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(n[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=KZe:this._payloadLength===127?this._state=YZe:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=JZe:this._state=fge}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=fge}getData(e){let n=zZe;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&bIn(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");e(r);return}if(this._compressed){this._state=mge,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[jZe.extensionName].decompress(e,this._fin,(i,o)=>{if(i)return n(i);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");n(s);return}this._fragments.push(o)}this.dataMessage(n),this._state===Hp&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=Hp;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=hge(r,n):this._binaryType==="arraybuffer"?i=wIn(hge(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Hp):(this._state=Oz,setImmediate(()=>{this.emit("message",i,!0),this._state=Hp,this.startLoop(e)}))}else{let i=hge(r,n);if(!this._skipUTF8Validation&&!VZe(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===mge||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Hp):(this._state=Oz,setImmediate(()=>{this.emit("message",i,!1),this._state=Hp,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,zZe),this.end();else{let r=e.readUInt16BE(0);if(!vIn(r)){let o=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(o);return}let i=new Lz(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!VZe(i)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(o);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=Hp;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Hp):(this._state=Oz,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Hp,this.startLoop(n)}))}createError(e,n,r,i,o){this._loop=!1,this._errored=!0;let s=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(s,this.createError),s.code=o,s[AIn]=i,s}};XZe.exports=gge});var wge=$((bfi,tet)=>{"use strict";var{Duplex:wfi}=Z("stream"),{randomFillSync:EIn}=Z("crypto"),{types:{isUint8Array:SIn}}=Z("util"),ZZe=SR(),{EMPTY_BUFFER:CIn,kWebSocket:_In,NOOP:IIn}=EA(),{isBlob:_R,isValidStatusCode:kIn}=CR(),{mask:eet,toBuffer:_S}=q$(),qp=Symbol("kByteLength"),TIn=Buffer.alloc(4),Nz=8*1024,IS,IR=Nz,Rf=0,RIn=1,MIn=2,Age=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Rf,this.onerror=IIn,this[_In]=void 0}static frame(e,n){let r,i=!1,o=2,s=!1;n.mask&&(r=n.maskBuffer||TIn,n.generateMask?n.generateMask(r):(IR===Nz&&(IS===void 0&&(IS=Buffer.alloc(Nz)),EIn(IS,0,Nz),IR=0),r[0]=IS[IR++],r[1]=IS[IR++],r[2]=IS[IR++],r[3]=IS[IR++]),s=(r[0]|r[1]|r[2]|r[3])===0,o=6);let a;typeof e=="string"?(!n.mask||s)&&n[qp]!==void 0?a=n[qp]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.readOnly&&!s);let c=a;a>=65536?(o+=8,c=127):a>125&&(o+=2,c=126);let u=Buffer.allocUnsafe(i?a+o:o);return u[0]=n.fin?n.opcode|128:n.opcode,n.rsv1&&(u[0]|=64),u[1]=c,c===126?u.writeUInt16BE(a,2):c===127&&(u[2]=u[3]=0,u.writeUIntBE(a,4,6)),n.mask?(u[1]|=128,u[o-4]=r[0],u[o-3]=r[1],u[o-2]=r[2],u[o-1]=r[3],s?[u,e]:i?(eet(e,r,u,o,a),[u]):(eet(e,r,e,0,a),[u,e])):[u,e]}close(e,n,r,i){let o;if(e===void 0)o=CIn;else{if(typeof e!="number"||!kIn(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof n=="string")o.write(n,2);else if(SIn(n))o.set(n,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let s={[qp]:o.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Rf?this.enqueue([this.dispatch,o,!1,s,i]):this.sendFrame(t.frame(o,s),i)}ping(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):_R(e)?(i=e.size,o=!1):(e=_S(e),i=e.length,o=_S.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[qp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};_R(e)?this._state!==Rf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Rf?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}pong(e,n,r){let i,o;if(typeof e=="string"?(i=Buffer.byteLength(e),o=!1):_R(e)?(i=e.size,o=!1):(e=_S(e),i=e.length,o=_S.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[qp]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};_R(e)?this._state!==Rf?this.enqueue([this.getBlobData,e,!1,s,r]):this.getBlobData(e,!1,s,r):this._state!==Rf?this.enqueue([this.dispatch,e,!1,s,r]):this.sendFrame(t.frame(e,s),r)}send(e,n,r){let i=this._extensions[ZZe.extensionName],o=n.binary?2:1,s=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):_R(e)?(a=e.size,c=!1):(e=_S(e),a=e.length,c=_S.readOnly),this._firstFragment?(this._firstFragment=!1,s&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=i._threshold),this._compress=s):(s=!1,o=0),n.fin&&(this._firstFragment=!0);let u={[qp]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:c,rsv1:s};_R(e)?this._state!==Rf?this.enqueue([this.getBlobData,e,this._compress,u,r]):this.getBlobData(e,this._compress,u,r):this._state!==Rf?this.enqueue([this.dispatch,e,this._compress,u,r]):this.dispatch(e,this._compress,u,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[qp],this._state=MIn,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(xge,this,a,i);return}this._bufferedBytes-=r[qp];let s=_S(o);n?this.dispatch(s,n,r,i):(this._state=Rf,this.sendFrame(t.frame(s,r),i),this.dequeue())}).catch(o=>{process.nextTick(PIn,this,o,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let o=this._extensions[ZZe.extensionName];this._bufferedBytes+=r[qp],this._state=RIn,o.compress(e,r.fin,(s,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");xge(this,c,i);return}this._bufferedBytes-=r[qp],this._state=Rf,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Rf&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][qp],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][qp],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};tet.exports=Age;function xge(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],o=i[i.length-1];typeof o=="function"&&o(e)}}function PIn(t,e,n){xge(t,e,n),t.onerror(e)}});var det=$((vfi,uet)=>{"use strict";var{kForOnEventAttribute:j$,kListener:bge}=EA(),net=Symbol("kCode"),ret=Symbol("kData"),iet=Symbol("kError"),oet=Symbol("kMessage"),set=Symbol("kReason"),kR=Symbol("kTarget"),aet=Symbol("kType"),cet=Symbol("kWasClean"),CA=class{constructor(e){this[kR]=null,this[aet]=e}get target(){return this[kR]}get type(){return this[aet]}};Object.defineProperty(CA.prototype,"target",{enumerable:!0});Object.defineProperty(CA.prototype,"type",{enumerable:!0});var kS=class extends CA{constructor(e,n={}){super(e),this[net]=n.code===void 0?0:n.code,this[set]=n.reason===void 0?"":n.reason,this[cet]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[net]}get reason(){return this[set]}get wasClean(){return this[cet]}};Object.defineProperty(kS.prototype,"code",{enumerable:!0});Object.defineProperty(kS.prototype,"reason",{enumerable:!0});Object.defineProperty(kS.prototype,"wasClean",{enumerable:!0});var TR=class extends CA{constructor(e,n={}){super(e),this[iet]=n.error===void 0?null:n.error,this[oet]=n.message===void 0?"":n.message}get error(){return this[iet]}get message(){return this[oet]}};Object.defineProperty(TR.prototype,"error",{enumerable:!0});Object.defineProperty(TR.prototype,"message",{enumerable:!0});var z$=class extends CA{constructor(e,n={}){super(e),this[ret]=n.data===void 0?null:n.data}get data(){return this[ret]}};Object.defineProperty(z$.prototype,"data",{enumerable:!0});var DIn={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[j$]&&i[bge]===e&&!i[j$])return;let r;if(t==="message")r=function(o,s){let a=new z$("message",{data:s?o:o.toString()});a[kR]=this,$z(e,this,a)};else if(t==="close")r=function(o,s){let a=new kS("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[kR]=this,$z(e,this,a)};else if(t==="error")r=function(o){let s=new TR("error",{error:o,message:o.message});s[kR]=this,$z(e,this,s)};else if(t==="open")r=function(){let o=new CA("open");o[kR]=this,$z(e,this,o)};else return;r[j$]=!!n[j$],r[bge]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[bge]===e&&!n[j$]){this.removeListener(t,n);break}}};uet.exports={CloseEvent:kS,ErrorEvent:TR,Event:CA,EventTarget:DIn,MessageEvent:z$};function $z(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var Fz=$((Efi,pet)=>{"use strict";var{tokenChars:V$}=CR();function sg(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function BIn(t){let e=Object.create(null),n=Object.create(null),r=!1,i=!1,o=!1,s,a,c=-1,u=-1,l=-1,d=0;for(;d<t.length;d++)if(u=t.charCodeAt(d),s===void 0)if(l===-1&&V$[u]===1)c===-1&&(c=d);else if(d!==0&&(u===32||u===9))l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);u===44?(sg(e,h,n),n=Object.create(null)):s=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(l===-1&&V$[u]===1)c===-1&&(c=d);else if(u===32||u===9)l===-1&&c!==-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d),sg(n,t.slice(c,l),!0),u===44&&(sg(e,s,n),n=Object.create(null),s=void 0),c=l=-1}else if(u===61&&c!==-1&&l===-1)a=t.slice(c,d),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(i){if(V$[u]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);c===-1?c=d:r||(r=!0),i=!1}else if(o)if(V$[u]===1)c===-1&&(c=d);else if(u===34&&c!==-1)o=!1,l=d;else if(u===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(u===34&&t.charCodeAt(d-1)===61)o=!0;else if(l===-1&&V$[u]===1)c===-1&&(c=d);else if(c!==-1&&(u===32||u===9))l===-1&&(l=d);else if(u===59||u===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1&&(l=d);let h=t.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),sg(n,a,h),u===44&&(sg(e,s,n),n=Object.create(null),s=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(c===-1||o||u===32||u===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=d);let p=t.slice(c,l);return s===void 0?sg(e,p,n):(a===void 0?sg(n,p,!0):r?sg(n,a,p.replace(/\\/g,"")):sg(n,a,p),sg(e,s,n)),e}function LIn(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let o=r[i];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?i:`${i}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}pet.exports={format:LIn,parse:BIn}});var Hz=$((_fi,Cet)=>{"use strict";var OIn=Z("events"),NIn=Z("https"),$In=Z("http"),met=Z("net"),FIn=Z("tls"),{randomBytes:UIn,createHash:QIn}=Z("crypto"),{Duplex:Sfi,Readable:Cfi}=Z("stream"),{URL:vge}=Z("url"),Vx=SR(),WIn=yge(),HIn=wge(),{isBlob:qIn}=CR(),{BINARY_TYPES:het,CLOSE_TIMEOUT:GIn,EMPTY_BUFFER:Uz,GUID:jIn,kForOnEventAttribute:Ege,kListener:zIn,kStatusCode:VIn,kWebSocket:Wa,NOOP:get}=EA(),{EventTarget:{addEventListener:KIn,removeEventListener:YIn}}=det(),{format:JIn,parse:XIn}=Fz(),{toBuffer:ZIn}=q$(),yet=Symbol("kAborted"),Sge=[8,13],_A=["CONNECTING","OPEN","CLOSING","CLOSED"],ekn=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Lo=class t extends OIn{constructor(e,n,r){super(),this._binaryType=het[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Uz,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Aet(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){het.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new WIn({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),o=new HIn(e,this._extensions,r.generateMask);this._receiver=i,this._sender=o,this._socket=e,i[Wa]=this,o[Wa]=this,e[Wa]=this,i.on("conclude",rkn),i.on("drain",ikn),i.on("error",okn),i.on("message",skn),i.on("ping",akn),i.on("pong",ckn),o.onerror=ukn,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",bet),e.on("data",Wz),e.on("end",vet),e.on("error",Eet),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Vx.extensionName]&&this._extensions[Vx.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Wd(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),wet(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Cge(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||Uz,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Cge(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||Uz,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Cge(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Vx.extensionName]||(i.compress=!1),this._sender.send(e||Uz,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Wd(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Lo,"CONNECTING",{enumerable:!0,value:_A.indexOf("CONNECTING")});Object.defineProperty(Lo.prototype,"CONNECTING",{enumerable:!0,value:_A.indexOf("CONNECTING")});Object.defineProperty(Lo,"OPEN",{enumerable:!0,value:_A.indexOf("OPEN")});Object.defineProperty(Lo.prototype,"OPEN",{enumerable:!0,value:_A.indexOf("OPEN")});Object.defineProperty(Lo,"CLOSING",{enumerable:!0,value:_A.indexOf("CLOSING")});Object.defineProperty(Lo.prototype,"CLOSING",{enumerable:!0,value:_A.indexOf("CLOSING")});Object.defineProperty(Lo,"CLOSED",{enumerable:!0,value:_A.indexOf("CLOSED")});Object.defineProperty(Lo.prototype,"CLOSED",{enumerable:!0,value:_A.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Lo.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Lo.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Ege])return e[zIn];return null},set(e){for(let n of this.listeners(t))if(n[Ege]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[Ege]:!0})}})});Lo.prototype.addEventListener=KIn;Lo.prototype.removeEventListener=YIn;Cet.exports=Lo;function Aet(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:GIn,protocolVersion:Sge[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=i.autoPong,t._closeTimeout=i.closeTimeout,!Sge.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Sge.join(", ")})`);let o;if(e instanceof vge)o=e;else try{o=new vge(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),t._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",c;if(o.protocol!=="ws:"&&!s&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?c="The URL's pathname is empty":o.hash&&(c="The URL contains a fragment identifier"),c){let m=new SyntaxError(c);if(t._redirects===0)throw m;Qz(t,m);return}let u=s?443:80,l=UIn(16).toString("base64"),d=s?NIn.request:$In.request,p=new Set,h;if(i.createConnection=i.createConnection||(s?nkn:tkn),i.defaultPort=i.defaultPort||u,i.port=o.port||u,i.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=o.pathname+o.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(h=new Vx({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=JIn({[Vx.extensionName]:h.offer()})),n.length){for(let m of n){if(typeof m!="string"||!ekn.test(m)||p.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");p.add(m)}i.headers["Sec-WebSocket-Protocol"]=n.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(o.username||o.password)&&(i.auth=`${o.username}:${o.password}`),a){let m=i.path.split(":");i.socketPath=m[0],i.path=m[1]}let f;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=s,t._originalHostOrSocketPath=a?i.socketPath:o.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[g,A]of Object.entries(m))r.headers[g.toLowerCase()]=A}else if(t.listenerCount("redirect")===0){let m=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;(!m||t._originalSecure&&!s)&&(delete i.headers.authorization,delete i.headers.cookie,m||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),f=t._req=d(i),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=d(i);i.timeout&&f.on("timeout",()=>{Wd(t,f,"Opening handshake has timed out")}),f.on("error",m=>{f===null||f[yet]||(f=t._req=null,Qz(t,m))}),f.on("response",m=>{let g=m.headers.location,A=m.statusCode;if(g&&i.followRedirects&&A>=300&&A<400){if(++t._redirects>i.maxRedirects){Wd(t,f,"Maximum redirects exceeded");return}f.abort();let b;try{b=new vge(g,e)}catch{let S=new SyntaxError(`Invalid URL: ${g}`);Qz(t,S);return}Aet(t,b,n,r)}else t.emit("unexpected-response",f,m)||Wd(t,f,`Unexpected server response: ${m.statusCode}`)}),f.on("upgrade",(m,g,A)=>{if(t.emit("upgrade",m),t.readyState!==Lo.CONNECTING)return;f=t._req=null;let b=m.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){Wd(t,g,"Invalid Upgrade header");return}let v=QIn("sha1").update(l+jIn).digest("base64");if(m.headers["sec-websocket-accept"]!==v){Wd(t,g,"Invalid Sec-WebSocket-Accept header");return}let S=m.headers["sec-websocket-protocol"],_;if(S!==void 0?p.size?p.has(S)||(_="Server sent an invalid subprotocol"):_="Server sent a subprotocol but none was requested":p.size&&(_="Server sent no subprotocol"),_){Wd(t,g,_);return}S&&(t._protocol=S);let I=m.headers["sec-websocket-extensions"];if(I!==void 0){if(!h){Wd(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=XIn(I)}catch{Wd(t,g,"Invalid Sec-WebSocket-Extensions header");return}let D=Object.keys(R);if(D.length!==1||D[0]!==Vx.extensionName){Wd(t,g,"Server indicated an extension that was not requested");return}try{h.accept(R[Vx.extensionName])}catch{Wd(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Vx.extensionName]=h}t.setSocket(g,A,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxBufferedChunks:i.maxBufferedChunks,maxFragments:i.maxFragments,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(f,t):f.end()}function Qz(t,e){t._readyState=Lo.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function tkn(t){return t.path=t.socketPath,met.connect(t)}function nkn(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=met.isIP(t.host)?"":t.host),FIn.connect(t)}function Wd(t,e,n){t._readyState=Lo.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Wd),e.setHeader?(e[yet]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Qz,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Cge(t,e,n){if(e){let r=qIn(e)?e.size:ZIn(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${_A[t.readyState]})`);process.nextTick(n,r)}}function rkn(t,e){let n=this[Wa];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[Wa]!==void 0&&(n._socket.removeListener("data",Wz),process.nextTick(xet,n._socket),t===1005?n.close():n.close(t,e))}function ikn(){let t=this[Wa];t.isPaused||t._socket.resume()}function okn(t){let e=this[Wa];e._socket[Wa]!==void 0&&(e._socket.removeListener("data",Wz),process.nextTick(xet,e._socket),e.close(t[VIn])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function fet(){this[Wa].emitClose()}function skn(t,e){this[Wa].emit("message",t,e)}function akn(t){let e=this[Wa];e._autoPong&&e.pong(t,!this._isServer,get),e.emit("ping",t)}function ckn(t){this[Wa].emit("pong",t)}function xet(t){t.resume()}function ukn(t){let e=this[Wa];e.readyState!==Lo.CLOSED&&(e.readyState===Lo.OPEN&&(e._readyState=Lo.CLOSING,wet(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function wet(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function bet(){let t=this[Wa];if(this.removeListener("close",bet),this.removeListener("data",Wz),this.removeListener("end",vet),t._readyState=Lo.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[Wa]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",fet),t._receiver.on("finish",fet))}function Wz(t){this[Wa]._receiver.write(t)||this.pause()}function vet(){let t=this[Wa];t._readyState=Lo.CLOSING,t._receiver.end(),this.end()}function Eet(){let t=this[Wa];this.removeListener("error",Eet),this.on("error",get),t&&(t._readyState=Lo.CLOSING,this.destroy())}});var Tet=$((kfi,ket)=>{"use strict";var Ifi=Hz(),{Duplex:lkn}=Z("stream");function _et(t){t.emit("close")}function dkn(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Iet(t){this.removeListener("error",Iet),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function pkn(t,e){let n=!0,r=new lkn({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,s){let a=!s&&r._readableState.objectMode?o.toString():o;r.push(a)||t.pause()}),t.once("error",function(o){r.destroyed||(n=!1,r.destroy(o))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,o){if(t.readyState===t.CLOSED){o(i),process.nextTick(_et,r);return}let s=!1;t.once("error",function(c){s=!0,o(c)}),t.once("close",function(){s||o(i),process.nextTick(_et,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,o,s){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,o,s)});return}t.send(i,s)},r.on("end",dkn),r.on("error",Iet),r}ket.exports=pkn});var _ge=$((Tfi,Ret)=>{"use strict";var{tokenChars:hkn}=CR();function fkn(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let s=t.charCodeAt(i);if(r===-1&&hkn[s]===1)n===-1&&(n=i);else if(i!==0&&(s===32||s===9))r===-1&&n!==-1&&(r=i);else if(s===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let o=t.slice(n,i);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}Ret.exports={parse:fkn}});var Net=$((Mfi,Oet)=>{"use strict";var mkn=Z("events"),qz=Z("http"),{Duplex:Rfi}=Z("stream"),{createHash:gkn}=Z("crypto"),Met=Fz(),TS=SR(),ykn=_ge(),Akn=Hz(),{CLOSE_TIMEOUT:xkn,GUID:wkn,kWebSocket:bkn}=EA(),vkn=/^[+/0-9A-Za-z]{22}==$/,Pet=0,Det=1,Let=2,Ige=class extends mkn{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:256*1024,maxFragments:16*1024,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xkn,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Akn,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=qz.createServer((r,i)=>{let o=qz.STATUS_CODES[426];i.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),i.end(o)}),this._server.listen(e.port,e.host,e.backlog,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=Ekn(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,o,s)=>{this.handleUpgrade(i,o,s,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Pet}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Let){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(K$,this);return}if(e&&this.once("close",e),this._state!==Det)if(this._state=Det,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(K$,this):process.nextTick(K$,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{K$(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Bet);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){RS(this,e,n,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){RS(this,e,n,400,"Invalid Upgrade header");return}if(o===void 0||!vkn.test(o)){RS(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){RS(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Y$(n,400);return}let c=e.headers["sec-websocket-protocol"],u=new Set;if(c!==void 0)try{u=ykn.parse(c)}catch{RS(this,e,n,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&l!==void 0){let p=new TS({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=Met.parse(l);h[TS.extensionName]&&(p.accept(h[TS.extensionName]),d[TS.extensionName]=p)}catch{RS(this,e,n,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let p={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(p,(h,f,m,g)=>{if(!h)return Y$(n,f||401,m,g);this.completeUpgrade(d,o,u,e,n,r,i)});return}if(!this.options.verifyClient(p))return Y$(n,401)}this.completeUpgrade(d,o,u,e,n,r,i)}completeUpgrade(e,n,r,i,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[bkn])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Pet)return Y$(o,503);let u=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${gkn("sha1").update(n+wkn).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;d&&(u.push(`Sec-WebSocket-Protocol: ${d}`),l._protocol=d)}if(e[TS.extensionName]){let d=e[TS.extensionName].params,p=Met.format({[TS.extensionName]:[d]});u.push(`Sec-WebSocket-Extensions: ${p}`),l._extensions=e}this.emit("headers",u,i),o.write(u.concat(`\r
|
|
94
94
|
`).join(`\r
|
|
@@ -1732,7 +1732,7 @@ Follow the instructions below exactly as written \u2014 every part, including th
|
|
|
1732
1732
|
${r}`}function gmn(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 r=n;return typeof r.name!="string"||typeof r.description!="string"||typeof r.source!="string"?[]:r.source!=="builtin"&&r.source!=="command"&&r.source!=="template"?[]:r.template!==void 0&&typeof r.template!="string"?[]:r.expansion!==void 0&&!upe(r.expansion)?[]:[{name:r.name,description:r.description,source:r.source,...typeof r.template=="string"?{template:r.template}:{},...upe(r.expansion)?{expansion:r.expansion}:{}}]}):[]}catch{return[]}}function Kri(t){let e=[],n="",r=null;for(let i of t)r!==null?i===r?r=null:n+=i:i==='"'||i==="'"?r=i:/\s/.test(i)?n!==""&&(e.push(n),n=""):n+=i;return n!==""&&e.push(n),e}function Yri(t,e){let n=e.join(" ");return t.replace(/\$\{(\d+):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(r,i,o,s,a,c)=>{if(i!==void 0)return e[Number.parseInt(i,10)-1]||o||"";if(s!==void 0){let u=Math.max(0,Number.parseInt(s,10)-1);return a!==void 0?e.slice(u,u+Number.parseInt(a,10)).join(" "):e.slice(u).join(" ")}return c==="ARGUMENTS"||c==="@"?n:e[Number.parseInt(c||"0",10)-1]??""})}function ymn(t,e){let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(n===null)return;let r=n[1];if(e.some(c=>c.source==="builtin"&&c.name===r))return;let i=t.indexOf(" "),o=i===-1?t.slice(1):t.slice(1,i),s=e.find(c=>c.source==="command"&&c.name===o);if(s!==void 0){if(s.expansion===void 0||!upe(s.expansion))return;let c=i===-1?"":t.slice(i+1);return{name:s.name,invocation:t,content:mmn(s.expansion,c)}}let a=e.find(c=>c.source==="template"&&c.name===r);if(typeof a?.template=="string")return{name:a.name,invocation:t,content:Yri(a.template,Kri(n[2]??""))}}var Jri="CRTR_TIMING",Amn="CRTR_TIMING_T0";function Xri(){return performance.timeOrigin+performance.now()}var xmn=(()=>{let t=process.env[Jri];return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"})(),Zri=(()=>{if(!xmn)return 0;let t=Number(process.env[Amn]);if(Number.isFinite(t)&&t>0)return t;let e=performance.timeOrigin;return process.env[Amn]=String(e),e})(),eii=(()=>{let t=process.env.CRTR_TIMING_PROC;return t!==void 0&&t!==""?t:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})(),uVe=0;function LT(t,e){if(!xmn)return;let n=Xri(),r=n-Zri,i=uVe===0?r:n-uVe;uVe=n;let o=performance.now(),s=e===void 0?"":" "+Object.entries(e).map(([u,l])=>`${u}=${String(l)}`).join(" "),a=process.env.CRTR_TIMING_PROC??eii,c=u=>u.toFixed(1).padStart(8);process.stderr.write(`[timing] +${c(r)}ms \u0394${c(i)}ms up=${c(o)}ms t=${n.toFixed(1)} ${a}/${process.pid} ${t}${s}
|
|
1733
1733
|
`)}function wmn(t,e){let{socket:n}=t,r=()=>{n.send({type:"get_commands"}),e.resetMemoryRefs()},i=a=>{if(a.for==="get_commands"&&a.ok&&a.detail){try{e.setCommands(gmn(a.detail))}catch{}return}if(a.for==="navigate_tree"&&a.ok){a.detail&&e.setEditorText(a.detail);return}if(a.for==="share"){a.ok&&a.detail?(e.setNotice(`Shared: ${a.detail}`),p6e(a.detail)):a.ok||e.setNotice(`share failed: ${a.detail??"unknown error"}`);return}if(a.for==="clone"&&!a.ok){e.setNotice(`clone failed: ${a.detail??"unknown error"}`);return}if(!a.ok){e.setNotice(`command failed: ${a.for}${a.detail?` \u2014 ${a.detail}`:""}`);return}a.for==="reload"&&(e.reloadBindings(),e.setCommands(),r(),e.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},o=a=>{e.chat.handleEvent(a),a.type==="session_info_changed"?e.refreshNodeIdentity():a.type==="thinking_level_changed"?e.setNotice(e.modelThinkingLabel()??`Thinking level: ${a.level}`):(a.type==="tool_execution_start"||a.type==="tool_execution_end")&&e.renderFooter()},s=!1;return a=>{switch(e.foldState(a),a.type){case"welcome":{s||(s=!0,LT("viewer.welcome")),e.chat.applySnapshot(a.snapshot),e.refreshNodeIdentity(),r(),a.pending_dialog!=null&&e.attachDialog(a.pending_dialog),e.onWelcome?.();break}case"tool_group_summary":e.chat.applyToolGroupSummary(a.key,a.summary);break;case"turn_reply":e.chat.applyTurnReply(a.key,a.reply);break;case"working_activity":e.chat.setWorkingActivity(a.activity);break;case"model_changed":{let c=e.modelThinkingLabel();c&&e.setNotice(c);break}case"error":a.code==="read_only"?e.setNotice("read-only"):e.chat.showError(a.message);break;case"node_named":break;case"ack":i(a);break;case"extension_ui_request":a.method!=="setStatus"&&a.method!=="setWidget"&&a.method!=="setTitle"&&e.attachDialog(a);break;case"extension_ui_dismiss":e.dismissDialog(a.id);break;case"bash_start":e.chat.bashStart(a.command,a.excludeFromContext);break;case"bash_output":e.chat.bashOutput(a.chunk);break;case"bash_end":e.chat.bashEnd(a);break;default:o(a);break}}}var tii=1e3;function bmn(t,e){let{tui:n,editor:r}=t,i=0,o={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":()=>{let s=Date.now();if(s-i<tii){i=0,e.cancelTurn();return}i=s,r.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(s=>{if(s.includes("\x1B[I")||s.includes("\x1B[O")){e.setPaneFocused(s.lastIndexOf("\x1B[I")>s.lastIndexOf("\x1B[O")),n.requestRender();let c=s.replaceAll("\x1B[I","").replaceAll("\x1B[O","");return c.length>0?{data:c}:{consume:!0}}let a=Gme(s);if(a!==void 0)return u6e(a.actionId,o),a.remaining.length>0?{data:a.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(s)?{consume:!0}:e.searchHandleKey(s)?{consume:!0}:r.focused&&Ydn(e.bindings(),s,e.viewportActions())?{consume:!0}:e.stripHandleKey(s)?{consume:!0}:e.rosterHandleKey(s)?{consume:!0}:Kdn(e.bindings(),s,o)?{consume:!0}:void 0})}import{spawnSync as nii}from"node:child_process";var rii="\x1B[?1002h\x1B[?1006h",vmn="\x1B[?1002l\x1B[?1006l",Emn=3;function iii(){if(!Ps())return!1;let t=nii("tmux",["show-options","-gv","mouse"],{encoding:"utf8"});return t.status===0&&t.stdout?.trim()==="on"}function Smn(t,e){let n=e==="on"||e==="tmux"&&iii(),r=()=>{t(n?rii:vmn)},i=()=>{n=!1;try{t(vmn)}catch{}};return process.once("exit",i),{enabled:()=>n,toggle:()=>(n=!n,r(),n),reassert:r,disable:i,install:(o,s)=>o.addInputListener(a=>{let c=!1,l=a.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,(d,p,h,f,m)=>{c=!0;let g=Number(p),A=g&-29;return A===64?s.onWheel("up",Emn,Number(h)):A===65?s.onWheel("down",Emn,Number(h)):A===32&&m==="M"?s.onPrimaryDrag(Number(h),Number(f)):A===0&&m==="m"?s.onPrimaryRelease(Number(h),Number(f)):g===0&&m==="M"&&s.onPrimaryPress(Number(h),Number(f)),""}).replace(/\x1b\[M[\s\S]{3}/g,()=>(c=!0,""));if(c)return l.length>0?{data:l}:{consume:!0}})}}function oii(t,e){return t.row<e.row||t.row===e.row&&t.column<=e.column}function Cmn(t,e,n){let[r,i]=oii(t,e)?[t,e]:[e,t],o=[];for(let s=r.row;s<=i.row;s++){let a=s===r.row?r.column-1:0,c=s===i.row?i.column:n;c>a&&o.push({row:s,from:a,to:c})}return o}function _mn(t){let e,n,r=()=>e!==void 0&&n!==void 0?{anchor:e,head:n}:void 0,i=()=>{let o=r();if(!o)return"";let s=t.frame(),a=Cmn(o.anchor,o.head,t.width()).map(c=>$dn(s[c.row-1]??"",c.from,c.to).trimEnd());for(;a.length>0&&a[a.length-1]==="";)a.pop();return a.join(`
|
|
1734
1734
|
`)};return{begin(o,s){e={row:s,column:o},n=void 0},extend(o,s){return e===void 0||n!==void 0&&n.row===s&&n.column===o?!1:(n={row:s,column:o},!0)},release(){let o=e;if(o===void 0)return;if(n===void 0)return e=void 0,{kind:"click",column:o.column,row:o.row};let s=i();if(s==="")return e=void 0,n=void 0,{kind:"selection",notice:"Nothing to copy \u2014 selection is empty"};let{system:a,tmux:c}=wde(s),u=a&&c?"clipboard + tmux buffer":a?"clipboard":c?"tmux buffer":void 0,l=s.split(`
|
|
1735
|
-
`).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Cmn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=Fdn(c[l],u.from,u.to,a))}return c}}}import{existsSync as sii}from"node:fs";var Imn="\x1B_crtr-file-open;",kmn="\x1B\\";function Tmn(t){let e=t.indexOf(Imn);if(e===-1)return;let n=e+Imn.length,r=t.indexOf(kmn,n);return r===-1?void 0:{file:aii(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+kmn.length)}}function aii(t){let e=t.startsWith("'")?cii(t):uii(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function cii(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function uii(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Rmn(t){if(!sii(t.file))return"missing";if(!tKe())return"no_nvim";let e=`crtr surface attach to ${an(t.nodeId)}${t.observer?" --observer":""}`,n=`${XT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),oge({pane:t.pane,cwd:t.cwd,env:eF(),command:n})?"opened":"failed"}function Mmn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchSecret().then(a=>{i=a,VHe(),r||t.refresh()},t.onSecretError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);VHe(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>t.remote||i===void 0?void 0:`http://127.0.0.1:${t.port}/r/${a.split("/").map(encodeURIComponent).join("/")}?t=${i}`};return KHe(s),{dispose(){r=!0,KHe(void 0)}}}tt();import{execFile as lii}from"node:child_process";function pVe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Pmn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Dmn(t){return`${pVe(t.mode)} ${t.kind}`}var dii=.72,pii={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},hii=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],fii=[["crtr.graph.dismiss","dismiss"]],mii=[["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"]],gii=[...["active","idle","done","dead","canceled"].map(t=>[_T(t,{}),t]),[_T("active",{streaming:!0}),"live"],[_T("active",{frozen:!0}),"frozen"],[_T("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${Op}${t.color}m${t.glyph}${Fr} ${zc}${e}${Fr}`).join(" ");function yii(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var lpe=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof DE}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;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return SS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${zs(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+Rd(s);if(o+a>n)break;i.push(s),o+=a}return i.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,pii),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 fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Pt().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,yii(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async A=>{let b=i.get(A);if(b!==void 0)return b;let v;try{v=await e.subscriptions(A)}catch{v=[]}let S=v.filter(_=>n.get(_)?.kind!=="human");return i.set(A,S),S},u=async A=>{if(s.has(A))return s.get(A);let b;try{b=(await e.subscribers(A))[0]}catch{b=void 0}return s.set(A,b),b},l=async()=>{let A=this.self,b=new Set([A]);for(;;){let v=await u(A);if(v===void 0||b.has(v))break;b.add(v),A=v}return A},d=async A=>{let b=o.get(A);if(b!==void 0)return b;let v=[...await c(A)];return v.sort((S,_)=>P6e(n.get(S)?.status)-P6e(n.get(_)?.status)),o.set(A,v),v},p=new Set,h=new Set,f=async A=>{let b=n.get(A)?.status==="active";if(h.has(A))return{active:b?1:0,reveal:b||A===this.self};h.add(A);let v=0,S=!1;for(let _ of await c(A)){let I=await f(_);v+=I.active,I.reveal&&(S=!0)}return a.set(A,v),S&&p.add(A),{active:v+(b?1:0),reveal:S||b||A===this.self}},m=await l();await f(m),await Promise.all([...i.keys()].map(A=>d(A)));let g={root:m,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(_,I)=>r?_x(_,bf(),UE):I?_x(_,bf(),jdn):Cx(_);if(n.cycle){let _=`${n.branch} ${zc}\u21BA ${Ade(n.id)}${Fr}`;return o(_,!1)}let s=e.nodes.get(n.id)??null,a=fde(s),c=kT(s,n.id),u=n.isSelf?`${vj}${c}${Fr}`:c,l=`${zc}${s?.kind??""}${Fr}`,d=`${zc}${mde(s,this.remote)}${Fr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${zc}\u25B8${Fr} `:" ",f=yde(s),m=e.childIds.get(n.id)?.length??0,g=s!==null&&m>0?` ${zc}\u2933${m}${Fr}`:"",A=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${hde}\u21E3${e.activeBelow.get(s.node_id)??0}${Fr}`:"",b=s?.fault??null,v=b!==null?` \xB7 ${qdn(b)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${f}${g}${A}${xde(n.id,i)}${gde(s,this.remote)}${v}`;return o(S,Vdn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(v=>v.id===this.cursorId);i<0&&(i=r.findIndex(v=>v.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Gdn,s=Math.max(3,Math.min(Math.floor(o*dii),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let v=0;c>0&&v<4;v++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${zc} \u2191 ${this.scrollTop} more${Fr}`);for(let v=this.scrollTop;v<d;v++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[v],v===i,n):"")}for(u&&d<r.length&&p.push(`${zc} \u2193 ${r.length-d} more${Fr}`),p.unshift(gii);p.length<a;)p.push("");let h=r.length>0?`${vj}\u2317 canvas graph${Fr} ${zc}(${i+1}/${r.length})${Fr}`:`${vj}\u2317 canvas graph${Fr} ${zc}(loading)${Fr}`,f=this.pendingConfirm!==void 0?`${Ej}${this.pendingConfirm.label} ${vj}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Fr}`:`${zc}${this.fitHints([...this.remote||this.role!=="controller"?fii:hii,...mii],Math.max(1,e-5))}${Fr}`,m=this.palette.border,g=Math.max(1,e-4),A=p.map(v=>`${m("\u2502")} ${ot(v,g,"",!0)} ${m("\u2502")}`),b=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...A,this.borderRow("\u2570","\u256F",f,e)].map(b)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-Rd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),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 u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),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 u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),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 u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Pmn(l):Ade(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Pt(),i=await r.getNode(e);(await Tde(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Fa(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{lii("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};tt();var Aii=.72,xii={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},dpe=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 r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*Aii),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(f=>this.boxRow(f,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(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,xii)}matchesBinding(e,n){return this.bindings!==void 0&&SS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,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(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=rg.map(({actionId:s})=>{let a=Bd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,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"),r("mouse wheel (when reporting is on)"),i,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"},i,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"},i,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"},i,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"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":zs(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&_e(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}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 r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-_e(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-_e(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};tt();tt();var ppe=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,AF(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())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&hVe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>_e(a)>r?(hVe(`surface row is ${_e(a)} cells wide; expected at most ${r}`),Bmn(Wi(a,0,r,!0),r)):Bmn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=wii(o);return s>1?(hVe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(bii)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function Bmn(t,e){return ot(t,e,"",!0)}function wii(t){return t.reduce((e,n)=>e+n.split(Yr).length-1,0)}function bii(t){return t.split(Yr).join("")}function hVe(t){HE("surface-frame",t)}var vii={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},Eii={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},fpe=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 r=new ppe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,vii),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){hpe("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new mVe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,Eii),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=Pt(),r=await n.getNode(e),i=await kde(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Fa(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=jde(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(Sii(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(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 o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){hpe(`surface overlay hide failed: ${fVe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>hpe(`surface cleanup failed: ${fVe(a)}`))}catch(s){hpe(`surface cleanup failed: ${fVe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.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}},mVe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function Sii(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function hpe(t){HE("surface-host",t)}function fVe(t){return t instanceof Error?t.message:String(t)}tt();import{watch as Dii}from"node:fs";function Cii(t,e){switch(e){case"gray":return`${qle}${t}${Oe}`;case"cyan":return`${hs}${t}${Oe}`;case"red":return`${vln}${t}${Oe}`;case"yellow":return`${Gs}${t}${Oe}`;default:return t}}var _ii={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},Iii={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function kii(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 Lmn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ps}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${bln}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>Tii(l,d,n,s)),c=Rii(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function Tii(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=_ii[i]??"\xB7",s=kii(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${hs}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),l=[`${a}${Cii(o,Iii[i]??"cyan")} ${ps}${Gle(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,` ${ut}${Gle(t.subtitle,r-6)}${Oe}`],d=gVe(t);return d!==void 0&&l.push(` ${ut}Recommended: ${Gle(d,Math.max(1,r-19))}${Oe}`),l}function gVe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function Rii(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&Mii(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function Mii(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function mpe(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 r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}Nd();xS();var gpe=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)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Ix().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(Pii(n)),!1}return!this.stopped&&qde(this.opts.host,e)}};function Pii(t){return t instanceof cA?UN(t):t instanceof Error?t.message:String(t)}var Ape=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??Bii,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.open;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Fa(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&_un(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}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=mpe(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Gs}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=Lmn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${qle}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ya(n[s]??"",e.listWidth),c=ya(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-_e(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}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.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},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()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();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=await this.requestOrNull(e.id);if(yVe(n)){this.status=ype(n),await this.rescan();return}let r=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${gVe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Dj(e.id,e.fastAction.responses),this.status=r}catch(i){this.status=Bj(i)==="already_settled"?ype(await this.requestOrNull(e.id)):Fa(i)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Ix().cancel(e.id,"Canceled from the inbox."):await Ifn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Fa(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(yVe(n)){this.status=ype(n),await this.rescan();return}let r,i;try{let o=await Pt().getHumanInboxPage(e.inboxTicketId);if(o.state==="resolved"||o.state==="canceled"){this.status=vN(o),await this.rescan();return}r=vT(o),i=o.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new WN({ticketId:e.inboxTicketId,page:r,productKinds:Sz(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:o=>{this.complete(o)}}),this.openRevision=i,this.watchSelected(e.dir),this.markDirty())}async activateReview(e){this.reviewAdapter=new gpe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Fa(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Pt().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(vT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.reviewAdapter?.stop(),this.leaveDetail();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.open;if(n===void 0)return;this.submittingDir=n.dir;try{await Dj(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Fa(i);let o=Bj(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=ype(await this.requestOrNull(n.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);Rl({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:yVe(await this.requestOrNull(n.id)),still_listed:r}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=rpe(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=mpe(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 r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ya(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===mce())return r.lines;let i=Omn(r.view,n);return this.preview={...r,width:n,links:mce(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Pt().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=vT(n),i=this.preview?.width??mpe(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:mce(),lines:Omn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Pt().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...jc(vl(r.title),Math.max(10,e-2)).map(s=>` ${ps}${hs}${s}${Oe}`),""];for(let s of pce(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ya(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Gs}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=QN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=Dii(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function Bii(){let{tickets:t}=await Pt().listHumanInbox();return t.map(zm).sort(BE)}function Omn(t,e){let n=t.manifest.dialect==="html"?gN(t.document):mN(t.document,t.manifest);return zle(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function yVe(t){return t!==void 0&&t.state!=="pending"}function ype(t){return t?.page===void 0?"ticket was already resolved":vN(t.page)}var AVe=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)),Lii(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=npe(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function Lii(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ya(i,e);return o+" ".repeat(Math.max(0,e-Bo(o)))})}async function Oii(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Pt().listHumanInbox();return e.map(zm).sort(BE)}async function Nmn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function $mn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new Ape({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new AVe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?Nmn("inbox visibility",()=>Oii(t)):void 0,d=u===void 0?void 0:Nmn("profile membership",()=>Pt().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}hR();eR();R$();var xVe=t=>t.snapshot;async function Fmn(){let t=await Pt().getSettings();TKe(t.person),vXe(t.person,xVe(t)),SXe(async()=>xVe(await Pt().getSettings())),EXe(async(e,n)=>{try{return xVe(await Pt().putSettings({ops:n}))}catch(r){throw r instanceof zt&&r.status===409?new T$:r}})}hR();import{homedir as Gii}from"node:os";import{fileURLToPath as Uii}from"node:url";import{join as Wmn,dirname as Qii}from"node:path";Nd();_l();kme();wS();wz();wz();import{readFileSync as Nii}from"node:fs";import{dirname as $ii,join as Umn}from"node:path";import{fileURLToPath as Fii}from"node:url";var xpe=null;function Qmn(){if(xpe!==null)return xpe;let t=Umn($ii(Fii(import.meta.url)),"..","..");return xpe=JSON.parse(Nii(Umn(t,"package.json"),"utf8")).version,xpe}Qp();Qp();var Wii=Uii(import.meta.url),Hii=Qii(Wii),qii=Wmn(Hii,"..",".."),uUs=Wmn(qii,"scripts","self-update.mjs");function Hmn(){return Qmn()}var jii="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function qmn(t){let e;try{e=Hmn()}catch{}let n;try{t.profile_id&&(n=Qx(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=Gii();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?jii:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}kl();import{createConnection as zii}from"node:net";var Vii=15e3;async function Kii(t,e){let n=await Tle(e);return setInterval(()=>{Tle(e).then(i=>{n=i},()=>{})},Vii).unref(),{previewEndpoint:t,get relayToken(){return n}}}function Gmn(t){return t?"observer":"controller"}async function Yii(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=nR(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=zii(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function jmn(t,e,n=!0){let r=e!==void 0,i=r?void 0:xT(),o=e!==void 0?yln({canvasName:e}):new bN,s,a,c,u,l;if(e!==void 0)s={cwd:process.cwd()},c=new qE(t,Ule(e));else{let f=await o.getNode(t);if(f===null)throw new Pp({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});s=f,a=f;try{if((await Pt().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await Pt().getSnapshot(t);u=g.snapshot,l=g.commands}}catch(m){Hze(m,"The node may be finalized or otherwise not attachable.")}i!==void 0?c=new qE(t,await Kii(i.apiUrl,i.directoryUrl)):(u===void 0&&await Yii(t),c=new qE(t,{socketPath:VKe()}))}let d=new Oj(t,{transport:c}),p=f=>f instanceof Ym?new Pp({error:"no_broker",message:f.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Pp({error:"socket_error",message:`could not attach to node ${t}: ${String(f?.message??f)}`,received:t,next:"Check the node has a running headless broker."}),h;return d.on("error",f=>{h===void 0&&(h=f)}),u===void 0&&await new Promise(async(f,m)=>{let g=()=>{b(),f()},A=v=>{b(),m(v)},b=()=>{d.off("connect",g),d.off("error",A)};d.on("connect",g),d.on("error",A),d.connect()}).catch(f=>{throw p(f)}),{remote:r,canvasSource:o,meta:s,nodeIdentity:a,socket:d,...u===void 0?{}:{initialSnapshot:u,initialCommands:l},assertConnected:()=>{if(u===void 0&&h!==void 0)throw p(h)}}}import{basename as Doi}from"node:path";ga();tt();_ye();import{statSync as uoi}from"node:fs";tt();wS();import{mkdirSync as Jii,readFileSync as Xii,writeFileSync as Zii}from"node:fs";import{dirname as eoi,join as toi}from"node:path";var noi="completion-frecency.json",roi=336*60*60*1e3,ioi=8,ooi=1e3;function soi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/roi),i=1-Math.exp(-t.n/3);return ioi*r*i}function aoi(t){let e={};try{let n=JSON.parse(Xii(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function coi(t,e){try{Jii(eoi(t),{recursive:!0}),Zii(t,JSON.stringify(e),"utf8")}catch{}}function zmn(t=toi(Qd(),noi)){let e=aoi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,coi(t,e)},ooi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>soi(e[i],o)}}function wVe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=OR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function bVe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Vmn(t){return t.replace(/:/g,"")}function Nj(t,e,n){let r=t.join(`
|
|
1735
|
+
`).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Cmn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=Fdn(c[l],u.from,u.to,a))}return c}}}import{existsSync as sii}from"node:fs";var Imn="\x1B_crtr-file-open;",kmn="\x1B\\";function Tmn(t){let e=t.indexOf(Imn);if(e===-1)return;let n=e+Imn.length,r=t.indexOf(kmn,n);return r===-1?void 0:{file:aii(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+kmn.length)}}function aii(t){let e=t.startsWith("'")?cii(t):uii(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function cii(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function uii(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Rmn(t){if(!sii(t.file))return"missing";if(!tKe())return"no_nvim";let e=`crtr surface attach to ${an(t.nodeId)}${t.observer?" --observer":""}`,n=`${XT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),oge({pane:t.pane,cwd:t.cwd,env:eF(),command:n})?"opened":"failed"}function Mmn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchAccess().then(a=>{i=a,VHe(),r||t.refresh()},t.onAccessError);let o=()=>{if(n)return;n=!0;let a=t.canvasSource;(a.panelRoster?a.panelRoster().then(u=>u.nodes):a.listNodes()).then(u=>{for(let l of u)e.set(l.node_id,l.name);VHe(),r||t.refresh()},()=>{n=!1})},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>{if(t.remote||i===void 0)return;let c=`/r/${a.split("/").map(encodeURIComponent).join("/")}`;return"canvas_url"in i?`${i.canvas_url}${c}`:`http://127.0.0.1:${t.port}${c}?t=${i.secret}`}};return KHe(s),{dispose(){r=!0,KHe(void 0)}}}tt();import{execFile as lii}from"node:child_process";function pVe(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Pmn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Dmn(t){return`${pVe(t.mode)} ${t.kind}`}var dii=.72,pii={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},hii=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],fii=[["crtr.graph.dismiss","dismiss"]],mii=[["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"]],gii=[...["active","idle","done","dead","canceled"].map(t=>[_T(t,{}),t]),[_T("active",{streaming:!0}),"live"],[_T("active",{frozen:!0}),"frozen"],[_T("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${Op}${t.color}m${t.glyph}${Fr} ${zc}${e}${Fr}`).join(" ");function yii(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var lpe=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof DE}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;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return SS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${zs(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+Rd(s);if(o+a>n)break;i.push(s),o+=a}return i.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,pii),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 fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Pt().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,yii(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async A=>{let b=i.get(A);if(b!==void 0)return b;let v;try{v=await e.subscriptions(A)}catch{v=[]}let S=v.filter(_=>n.get(_)?.kind!=="human");return i.set(A,S),S},u=async A=>{if(s.has(A))return s.get(A);let b;try{b=(await e.subscribers(A))[0]}catch{b=void 0}return s.set(A,b),b},l=async()=>{let A=this.self,b=new Set([A]);for(;;){let v=await u(A);if(v===void 0||b.has(v))break;b.add(v),A=v}return A},d=async A=>{let b=o.get(A);if(b!==void 0)return b;let v=[...await c(A)];return v.sort((S,_)=>P6e(n.get(S)?.status)-P6e(n.get(_)?.status)),o.set(A,v),v},p=new Set,h=new Set,f=async A=>{let b=n.get(A)?.status==="active";if(h.has(A))return{active:b?1:0,reveal:b||A===this.self};h.add(A);let v=0,S=!1;for(let _ of await c(A)){let I=await f(_);v+=I.active,I.reveal&&(S=!0)}return a.set(A,v),S&&p.add(A),{active:v+(b?1:0),reveal:S||b||A===this.self}},m=await l();await f(m),await Promise.all([...i.keys()].map(A=>d(A)));let g={root:m,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(_,I)=>r?_x(_,bf(),UE):I?_x(_,bf(),jdn):Cx(_);if(n.cycle){let _=`${n.branch} ${zc}\u21BA ${Ade(n.id)}${Fr}`;return o(_,!1)}let s=e.nodes.get(n.id)??null,a=fde(s),c=kT(s,n.id),u=n.isSelf?`${vj}${c}${Fr}`:c,l=`${zc}${s?.kind??""}${Fr}`,d=`${zc}${mde(s,this.remote)}${Fr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${zc}\u25B8${Fr} `:" ",f=yde(s),m=e.childIds.get(n.id)?.length??0,g=s!==null&&m>0?` ${zc}\u2933${m}${Fr}`:"",A=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${hde}\u21E3${e.activeBelow.get(s.node_id)??0}${Fr}`:"",b=s?.fault??null,v=b!==null?` \xB7 ${qdn(b)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${f}${g}${A}${xde(n.id,i)}${gde(s,this.remote)}${v}`;return o(S,Vdn(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(v=>v.id===this.cursorId);i<0&&(i=r.findIndex(v=>v.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??Gdn,s=Math.max(3,Math.min(Math.floor(o*dii),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let v=0;c>0&&v<4;v++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${zc} \u2191 ${this.scrollTop} more${Fr}`);for(let v=this.scrollTop;v<d;v++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[v],v===i,n):"")}for(u&&d<r.length&&p.push(`${zc} \u2193 ${r.length-d} more${Fr}`),p.unshift(gii);p.length<a;)p.push("");let h=r.length>0?`${vj}\u2317 canvas graph${Fr} ${zc}(${i+1}/${r.length})${Fr}`:`${vj}\u2317 canvas graph${Fr} ${zc}(loading)${Fr}`,f=this.pendingConfirm!==void 0?`${Ej}${this.pendingConfirm.label} ${vj}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Fr}`:`${zc}${this.fitHints([...this.remote||this.role!=="controller"?fii:hii,...mii],Math.max(1,e-5))}${Fr}`,m=this.palette.border,g=Math.max(1,e-4),A=p.map(v=>`${m("\u2502")} ${ot(v,g,"",!0)} ${m("\u2502")}`),b=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...A,this.borderRow("\u2570","\u256F",f,e)].map(b)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-Rd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),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 u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),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 u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),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 u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Pmn(l):Ade(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Pt(),i=await r.getNode(e);(await Tde(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Fa(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{lii("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};tt();var Aii=.72,xii={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},dpe=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 r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*Aii),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(f=>this.boxRow(f,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(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,xii)}matchesBinding(e,n){return this.bindings!==void 0&&SS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,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(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=rg.map(({actionId:s})=>{let a=Bd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,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"),r("mouse wheel (when reporting is on)"),i,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"},i,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"},i,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"},i,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"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":zs(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&_e(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}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 r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-_e(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-_e(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};tt();tt();var ppe=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,AF(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())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&hVe(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>_e(a)>r?(hVe(`surface row is ${_e(a)} cells wide; expected at most ${r}`),Bmn(Wi(a,0,r,!0),r)):Bmn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=wii(o);return s>1?(hVe(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(bii)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function Bmn(t,e){return ot(t,e,"",!0)}function wii(t){return t.reduce((e,n)=>e+n.split(Yr).length-1,0)}function bii(t){return t.split(Yr).join("")}function hVe(t){HE("surface-frame",t)}var vii={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},Eii={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},fpe=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 r=new ppe(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,vii),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){hpe("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new mVe(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,Eii),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=Pt(),r=await n.getNode(e),i=await kde(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Fa(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=jde(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount(Sii(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(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 o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){hpe(`surface overlay hide failed: ${fVe(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>hpe(`surface cleanup failed: ${fVe(a)}`))}catch(s){hpe(`surface cleanup failed: ${fVe(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.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}},mVe=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function Sii(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function hpe(t){HE("surface-host",t)}function fVe(t){return t instanceof Error?t.message:String(t)}tt();import{watch as Dii}from"node:fs";function Cii(t,e){switch(e){case"gray":return`${qle}${t}${Oe}`;case"cyan":return`${hs}${t}${Oe}`;case"red":return`${vln}${t}${Oe}`;case"yellow":return`${Gs}${t}${Oe}`;default:return t}}var _ii={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},Iii={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function kii(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 Lmn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${ps}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${bln}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>Tii(l,d,n,s)),c=Rii(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function Tii(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=_ii[i]??"\xB7",s=kii(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${hs}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),l=[`${a}${Cii(o,Iii[i]??"cyan")} ${ps}${Gle(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,` ${ut}${Gle(t.subtitle,r-6)}${Oe}`],d=gVe(t);return d!==void 0&&l.push(` ${ut}Recommended: ${Gle(d,Math.max(1,r-19))}${Oe}`),l}function gVe(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function Rii(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&Mii(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function Mii(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function mpe(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 r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}Nd();xS();var gpe=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)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Ix().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(Pii(n)),!1}return!this.stopped&&qde(this.opts.host,e)}};function Pii(t){return t instanceof cA?UN(t):t instanceof Error?t.message:String(t)}var Ape=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;open;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??Bii,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.open;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Fa(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&_un(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail()}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots())}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.open!==void 0){await this.reloadSelectedPage();return}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=mpe(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Gs}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=Lmn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${qle}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ya(n[s]??"",e.listWidth),c=ya(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-_e(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}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.adapter.hasShortcut(e)){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},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()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();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=await this.requestOrNull(e.id);if(yVe(n)){this.status=ype(n),await this.rescan();return}let r=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${gVe(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await Dj(e.id,e.fastAction.responses),this.status=r}catch(i){this.status=Bj(i)==="already_settled"?ype(await this.requestOrNull(e.id)):Fa(i)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Ix().cancel(e.id,"Canceled from the inbox."):await Ifn(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Fa(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(yVe(n)){this.status=ype(n),await this.rescan();return}let r,i;try{let o=await Pt().getHumanInboxPage(e.inboxTicketId);if(o.state==="resolved"||o.state==="canceled"){this.status=vN(o),await this.rescan();return}r=vT(o),i=o.revision}catch{this.status="page could not be read",await this.invalidate();return}this.closed||this.open!==void 0||this.adapter!==void 0||(this.open={dir:e.dir,id:e.id,ticketId:e.inboxTicketId},this.screen="detail",this.adapter=new WN({ticketId:e.inboxTicketId,page:r,productKinds:Sz(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:o=>{this.complete(o)}}),this.openRevision=i,this.watchSelected(e.dir),this.markDirty())}async activateReview(e){this.reviewAdapter=new gpe({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Fa(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.open;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Pt().getHumanInboxPage(e.ticketId);if(this.closed||this.open!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(vT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.reviewAdapter?.stop(),this.leaveDetail();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.open;if(n===void 0)return;this.submittingDir=n.dir;try{await Dj(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Fa(i);let o=Bj(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=ype(await this.requestOrNull(n.id))),this.leaveDetail(),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);Rl({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:yVe(await this.requestOrNull(n.id)),still_listed:r}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=rpe(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.open=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=mpe(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 r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ya(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.open?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===mce())return r.lines;let i=Omn(r.view,n);return this.preview={...r,width:n,links:mce(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Pt().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=vT(n),i=this.preview?.width??mpe(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:mce(),lines:Omn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Pt().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...jc(vl(r.title),Math.max(10,e-2)).map(s=>` ${ps}${hs}${s}${Oe}`),""];for(let s of pce(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ya(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Gs}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=QN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=Dii(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function Bii(){let{tickets:t}=await Pt().listHumanInbox();return t.map(zm).sort(BE)}function Omn(t,e){let n=t.manifest.dialect==="html"?gN(t.document):mN(t.document,t.manifest);return zle(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function yVe(t){return t!==void 0&&t.state!=="pending"}function ype(t){return t?.page===void 0?"ticket was already resolved":vN(t.page)}var AVe=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)),Lii(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=npe(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function Lii(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ya(i,e);return o+" ".repeat(Math.max(0,e-Bo(o)))})}async function Oii(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Pt().listHumanInbox();return e.map(zm).sort(BE)}async function Nmn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function $mn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new Ape({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new AVe(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?Nmn("inbox visibility",()=>Oii(t)):void 0,d=u===void 0?void 0:Nmn("profile membership",()=>Pt().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}hR();eR();R$();var xVe=t=>t.snapshot;async function Fmn(){let t=await Pt().getSettings();TKe(t.person),vXe(t.person,xVe(t)),SXe(async()=>xVe(await Pt().getSettings())),EXe(async(e,n)=>{try{return xVe(await Pt().putSettings({ops:n}))}catch(r){throw r instanceof zt&&r.status===409?new T$:r}})}hR();import{homedir as Gii}from"node:os";import{fileURLToPath as Uii}from"node:url";import{join as Wmn,dirname as Qii}from"node:path";Nd();_l();kme();wS();wz();wz();import{readFileSync as Nii}from"node:fs";import{dirname as $ii,join as Umn}from"node:path";import{fileURLToPath as Fii}from"node:url";var xpe=null;function Qmn(){if(xpe!==null)return xpe;let t=Umn($ii(Fii(import.meta.url)),"..","..");return xpe=JSON.parse(Nii(Umn(t,"package.json"),"utf8")).version,xpe}Qp();Qp();var Wii=Uii(import.meta.url),Hii=Qii(Wii),qii=Wmn(Hii,"..",".."),uUs=Wmn(qii,"scripts","self-update.mjs");function Hmn(){return Qmn()}var jii="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function qmn(t){let e;try{e=Hmn()}catch{}let n;try{t.profile_id&&(n=Qx(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=Gii();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?jii:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}kl();import{createConnection as zii}from"node:net";var Vii=15e3;async function Kii(t,e){let n=await Tle(e);return setInterval(()=>{Tle(e).then(i=>{n=i},()=>{})},Vii).unref(),{previewEndpoint:t,get relayToken(){return n}}}function Gmn(t){return t?"observer":"controller"}async function Yii(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=nR(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=zii(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function jmn(t,e,n=!0){let r=e!==void 0,i=r?void 0:xT(),o=e!==void 0?yln({canvasName:e}):new bN,s,a,c,u,l;if(e!==void 0)s={cwd:process.cwd()},c=new qE(t,Ule(e));else{let f=await o.getNode(t);if(f===null)throw new Pp({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});s=f,a=f;try{if((await Pt().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let g=await Pt().getSnapshot(t);u=g.snapshot,l=g.commands}}catch(m){Hze(m,"The node may be finalized or otherwise not attachable.")}i!==void 0?c=new qE(t,await Kii(i.apiUrl,i.directoryUrl)):(u===void 0&&await Yii(t),c=new qE(t,{socketPath:VKe()}))}let d=new Oj(t,{transport:c}),p=f=>f instanceof Ym?new Pp({error:"no_broker",message:f.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Pp({error:"socket_error",message:`could not attach to node ${t}: ${String(f?.message??f)}`,received:t,next:"Check the node has a running headless broker."}),h;return d.on("error",f=>{h===void 0&&(h=f)}),u===void 0&&await new Promise(async(f,m)=>{let g=()=>{b(),f()},A=v=>{b(),m(v)},b=()=>{d.off("connect",g),d.off("error",A)};d.on("connect",g),d.on("error",A),d.connect()}).catch(f=>{throw p(f)}),{remote:r,canvasSource:o,meta:s,nodeIdentity:a,socket:d,...u===void 0?{}:{initialSnapshot:u,initialCommands:l},assertConnected:()=>{if(u===void 0&&h!==void 0)throw p(h)}}}import{basename as Doi}from"node:path";ga();tt();_ye();import{statSync as uoi}from"node:fs";tt();wS();import{mkdirSync as Jii,readFileSync as Xii,writeFileSync as Zii}from"node:fs";import{dirname as eoi,join as toi}from"node:path";var noi="completion-frecency.json",roi=336*60*60*1e3,ioi=8,ooi=1e3;function soi(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/roi),i=1-Math.exp(-t.n/3);return ioi*r*i}function aoi(t){let e={};try{let n=JSON.parse(Xii(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function coi(t,e){try{Jii(eoi(t),{recursive:!0}),Zii(t,JSON.stringify(e),"utf8")}catch{}}function zmn(t=toi(Qd(),noi)){let e=aoi(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,coi(t,e)},ooi),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>soi(e[i],o)}}function wVe(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=OR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function bVe(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function Vmn(t){return t.replace(/:/g,"")}function Nj(t,e,n){let r=t.join(`
|
|
1736
1736
|
`),i=0;for(let l=0;l<e&&l<t.length;l++)i+=t[l].length+1;let o=i+n,s=cpn(r,o);if(!s)return null;let a=s.start-i,c=s.end-i;return{kind:s.start===0?"leading":"ref",startCol:a,endCol:c,prefix:s.surfacePrefix}}var wpe=class{refs;refNames;delegate;frecency;constructor(e,n,r){this.refs=e,this.refNames=new Set(e.map(i=>i.name)),this.delegate=n,this.frecency=r}get triggerCharacters(){return this.delegate.triggerCharacters}async getSuggestions(e,n,r,i){let o=Nj(e,n,r);if(!o)return this.delegate.getSuggestions(e,n,r,i);if(o.kind==="leading"){if(i.force)return this.delegate.getSuggestions(e,n,r,i);let c=(e[n]??"").slice(0,r),u=await this.delegate.getSuggestions(["/"],0,1,i);if(!u)return null;let l=wVe(u.items,c.slice(1),{searchableOf:d=>bVe(d.value),idOf:d=>`command:${d.value}`,store:this.frecency});return l.length===0?null:{items:l,prefix:c}}let s=wVe(this.refs,Vmn(o.prefix.slice(1)),{searchableOf:c=>bVe(c.name),idOf:c=>`ref:${c.name}`,store:this.frecency});return s.length===0?null:{items:s.map(c=>({value:c.name,label:f6e(c.name),description:c.shortForm||void 0})),prefix:o.prefix.slice(1)}}applyCompletion(e,n,r,i,o){let s=Nj(e,n,r);if(s&&s.kind==="ref"&&this.refNames.has(i.value)){let a=f6e(i.value),c=e[n]??"",u=c.slice(0,s.startCol)+a+c.slice(s.endCol),l=e.slice();return l[n]=u,{lines:l,cursorLine:n,cursorCol:s.startCol+a.length}}return this.delegate.applyCompletion(e,n,r,i,o)}shouldTriggerFileCompletion(e,n,r){let i=Nj(e,n,r);return i&&i.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,r):!1}};var vVe=8,loi=24,doi=8192;function poi(t,e){let n=t.slice(0,e),r=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:r}}function hoi(t,e){if(e<loi)return[];let n=Math.min(doi,Math.max(256,e*vVe*4)),r=poi(t,n),i=Oo(r.text,e);if(!r.truncated&&i.length<=vVe)return i;let o=i.slice(0,vVe-1);return o.push(ot("\u2026 truncated \xB7 inspect for full prompt",e)),o}var $j=[46,92,190],Fj=[166,98,24],foi=[0,145,170];function Uj(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 Kmn={off:void 0,minimal:Uj($j,Fj,0/4),low:Uj($j,Fj,1/4),medium:Uj($j,Fj,2/4),high:Uj($j,Fj,3/4),xhigh:Uj($j,Fj,4/4),max:foi},moi={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 Ymn(t){let e=t.trim().toLowerCase(),n=/^colour(\d{1,3})$/.exec(e);if(n!==null)return l=>`\x1B[48;5;${n[1]}m\x1B[97m\x1B[1m ${l} \x1B[0m`;let r,i=/^#([0-9a-f]{6})$/.exec(e);if(i!==null){let l=i[1];r=[parseInt(l.slice(0,2),16),parseInt(l.slice(2,4),16),parseInt(l.slice(4,6),16)]}else r=moi[e];if(r===void 0)return;let[o,s,a]=r,u=.299*o+.587*s+.114*a>160?"\x1B[30m":"\x1B[97m";return l=>`\x1B[48;2;${o};${s};${a}m${u}\x1B[1m ${l} \x1B[0m`}var bpe=t=>`\x1B[7m ${t} \x1B[27m`;function Jmn(t,e){let n=t===void 0?void 0:Kmn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[38;2;${r};${i};${o}m${s}\x1B[39m`}function Xmn(t,e){let n=t===void 0?void 0:Kmn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[48;2;${r};${i};${o}m\x1B[97m\x1B[1m ${s} \x1B[0m`}function goi(t,e,n,r,i){let o=e?r(ot(e,Math.max(1,t-4),"\u2026")):"",s=_e(o),a=t-s,c="";n&&a>4&&(c=_e(n)<=a?n:ot(n,a,"\u2026"));let u=Math.max(0,t-s-_e(c));return o+i("\u2500".repeat(u))+c}var vpe="\x1B[7m",Epe="\x1B[0m",EVe="\x1B[48;5;240m";function yoi(t){let e=t.indexOf(Yr);if(e===-1)return;let n=e+Yr.length;if(!t.startsWith(vpe,n))return;let r=n+vpe.length,i=t.indexOf(Epe,r);if(i===-1)return;let o=t.slice(r,i),s=`${EVe}${o}\x1B[0m`;return t.slice(0,n)+s+t.slice(i+Epe.length)}var Aoi=/\.(png|jpe?g|gif|webp|bmp)$/i;function xoi(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 r=n.replace(/\\(.)/g,"$1");if(/\n/.test(r)||!Aoi.test(r))return null;try{if(!uoi(r).isFile())return null}catch{return null}return r}function woi(t,e,n,r){let i=[];if(t.length===0||t.length===1&&t[0]==="")return i.push({logicalLine:0,startIndex:0,endIndex:0,text:"",hasCursor:!0,cursorPos:0}),i;for(let o=0;o<t.length;o++){let s=t[o]??"",a=o===n;if(_e(s)<=e){i.push({logicalLine:o,startIndex:0,endIndex:s.length,text:s,hasCursor:a,cursorPos:a?r:0});continue}let c=xF(s,e);for(let u=0;u<c.length;u++){let l=c[u];if(!l)continue;let d=u===c.length-1,p=!1,h=0;a&&(d?(p=r>=l.startIndex,h=r-l.startIndex):(p=r>=l.startIndex&&r<l.endIndex,p&&(h=r-l.startIndex,h>l.text.length&&(h=l.text.length)))),i.push({logicalLine:o,startIndex:l.startIndex,endIndex:l.endIndex,text:l.text,hasCursor:p,cursorPos:h})}}return i}function boi(t,e){return vde(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}var voi="\x1B[4m\x1B[2m",Eoi="\x1B[24m\x1B[22m",Soi=new Intl.Segmenter(void 0,{granularity:"grapheme"});function Coi(t){for(let e of Soi.segment(t))return e.segment.length;return 0}function _oi(t){let e=t.indexOf(Yr),n=e===-1?0:e+Yr.length,r=t.indexOf(vpe,n),i=vpe.length;if(r===-1&&(r=t.indexOf(EVe,n),i=EVe.length),r===-1)return null;let o=t.indexOf(Epe,r+i);return o===-1?null:{start:e!==-1?e:r,end:o+Epe.length}}function Ioi(t,e,n,r,i){let o=[];if(e.hasCursor){let a=_oi(t);if(a===null)return t;let c=e.text.slice(e.cursorPos),u=c.length===0?0:Coi(c),l=e.cursorPos+u;for(let d of n){let p=d.start-e.startIndex,h=d.end-e.startIndex;if(h<=e.cursorPos){let f=i+p,m=i+h;m<=a.start&&t.slice(f,m)===r.slice(d.start,d.end)&&o.push({absStart:f,absEnd:m})}else if(p>=l){let f=a.end+(p-l),m=a.end+(h-l);f>=a.end&&t.slice(f,m)===r.slice(d.start,d.end)&&o.push({absStart:f,absEnd:m})}}}else for(let a of n){let c=i+(a.start-e.startIndex),u=i+(a.end-e.startIndex);t.slice(c,u)===r.slice(a.start,a.end)&&o.push({absStart:c,absEnd:u})}if(o.length===0)return t;o.sort((a,c)=>c.absStart-a.absStart);let s=t;for(let a of o)s=s.slice(0,a.absStart)+voi+s.slice(a.absStart,a.absEnd)+Eoi+s.slice(a.absEnd);return s}function koi(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function Toi(t,e){if(!t.startsWith("/"))return!1;let n=t.indexOf(" "),r=n===-1?t.slice(1):t.slice(1,n);if(e.has(r))return!0;if(t.startsWith("/skill:")){let i=n===-1?t.slice(7):t.slice(7,n);if(e.has(`skill:${i}`))return!0}return!1}var Spe=class t extends Uk{km;pendingRawSubmitText;realOnSubmit;pendingReturn;static PASTE_BURST_MS=10;constructor(e,n,r,i){super(e,n,r,i),this.km=r;let o=this.submitValue.bind(this);this.submitValue=()=>{let s=this;this.pendingRawSubmitText=s.getExpandedText(),o()},Object.defineProperty(this,"onSubmit",{configurable:!0,get:()=>s=>{let a=this.pendingRawSubmitText??s;this.pendingRawSubmitText=void 0,this.realOnSubmit?.(a)},set:s=>{this.realOnSubmit=s}})}onPasteImagePath;settleHeldReturn(e){let n=this.pendingReturn;if(n!==void 0){if(clearTimeout(n.timer),this.pendingReturn=void 0,e==="newline"){this.insertTextAtCursor(`
|
|
1737
1737
|
`);return}super.handleInput(n.data),this.tui.requestRender()}}imageTokenWidthBeforeCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(0,n).match(/\[Image #\d+\]$/);return i?i[0].length:0}imageTokenWidthAfterCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(n).match(/^\[Image #\d+\]/);return i?i[0].length:0}handleInput(e){if(this.settleHeldReturn("newline"),!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorDown")){let s=this,a=this.getCursor(),c=s.historyIndex;super.handleInput(e);let u=this.getCursor();s.historyIndex===c&&u.line===a.line&&u.col===a.col&&this.onCursorDownAtBottom?.();return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.input.newLine")){this.insertTextAtCursor(`
|
|
1738
1738
|
`);return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.deleteCharBackward")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorLeft")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorRight")){let s=this.imageTokenWidthAfterCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}let n=xoi(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
|
|
@@ -1743,7 +1743,7 @@ Invocation: \`${c.invocation.replaceAll("`","\\`")}\`
|
|
|
1743
1743
|
|
|
1744
1744
|
${c.content}
|
|
1745
1745
|
`,noNvim:"nvim is required to inspect loaded commands. Install Neovim and retry."})}}}function sgn(t,e,n){let r=e;return{current:()=>r,refresh:()=>{t.canvasSource.getNode(t.nodeId).then(i=>{n.isTornDown()||i===null||(r=i,n.onChanged())}).catch(()=>{})}}}var zoi={readOption:Tf,writeOption:(t,e,n)=>{og(t,e,n)},stampAsync:rge,currentPane:()=>process.env.TMUX_PANE??ig()?.pane,ownerId:()=>String(process.pid)};function cgn(t,e,n=zoi){let r,i=n.ownerId(),o=()=>{if(r===void 0||r==="")return!0;let s=n.readOption(r,ugn);return s===void 0||s===""?!0:s===i};return{set:()=>{r=n.currentPane(),agn(r,i,n.writeOption),Yoi(t,r,e,n.writeOption),Xoi(r,n.writeOption),Voi(t,r,n.writeOption)},stamp:()=>{t||r===void 0||r===""||n.stampAsync(r)},clear:()=>{o()&&(Joi(t,r,n.writeOption),Zoi(r,n.writeOption),Koi(t,r,n.writeOption),agn(r,"",n.writeOption))},pane:()=>r}}var ugn="@crtr_viewer_pid";function agn(t,e,n){if(!(t===void 0||t===""))try{n(t,ugn,e)}catch{}}function Voi(t,e,n){if(!(t||e===void 0||e===""))try{n(e,W$,String(Date.now()))}catch{}}function Koi(t,e,n=og){if(!(t||e===void 0||e===""))try{n(e,W$,"")}catch{}}function Yoi(t,e,n,r=og){if(!(t||e===void 0||e===""))try{r(e,"@crtr_node",n)}catch{}}function Joi(t,e,n=og){if(!(t||e===void 0||e===""))try{n(e,"@crtr_node","")}catch{}}function Xoi(t,e=og){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","1")}catch{}}function Zoi(t,e=og){if(!(t===void 0||t===""))try{e(t,"@crtr_attach","")}catch{}}hR();kl();import{constants as esi,accessSync as tsi,existsSync as nsi,mkdtempSync as rsi,readFileSync as isi,rmSync as _pe,statSync as osi}from"node:fs";import{tmpdir as ssi}from"node:os";import{delimiter as asi,join as Ipe,resolve as csi,sep as dgn}from"node:path";import{execFile as lgn,spawnSync as usi}from"node:child_process";function lsi(t,e){let n=new Map(t.map(o=>[o.node_id,o])),r=new Set([e]);for(let o=n.get(e);o?.parent!==null&&o?.parent!==void 0;){let s=o.parent;if(r.has(s))break;r.add(s),o=n.get(s)}let i=[e];for(;i.length>0;){let o=i.pop();for(let s of t)s.parent!==o||r.has(s.node_id)||(r.add(s.node_id),i.push(s.node_id))}return t.filter(o=>r.has(o.node_id)).map(o=>o.node_id)}function pgn(t,e){let n=new Set(lsi(t,e));return t.filter(r=>n.has(r.node_id))}function dsi(t){let e=[];for(let n of t)try{e.push(XKe(n.node_id,n.grantee))}catch{continue}return _Ve(e)}function psi(t){try{return osi(t).isDirectory()}catch{return!1}}function hsi(t,e){let n=[...e==null?[]:[e],...(process.env.PATH??"").split(asi).filter(Boolean).map(r=>Ipe(r,t))];return[...new Set(n)]}function CVe(t,e){for(let n of hsi(t,e)){try{tsi(n,esi.X_OK)}catch{continue}if(usi(n,["--version"],{stdio:"ignore"}).status===0)return n}return null}function fsi(t){if(t===null||t==="")return{projects:[],settings:null};try{let{profileId:e,manifest:n}=Qx(t);return{projects:n.projects.map(r=>r.path),settings:gz(e)}}catch{return{projects:[],settings:null}}}function _Ve(t){let e=new Set,n=[];for(let r of t){let i=csi(r);e.has(i)||!psi(i)||(e.add(i),n.push(i))}return n}function msi(t){return t.filter(e=>!t.some(n=>n!==e&&e.startsWith(n+dgn)))}var gsi=20;function ysi(t){try{let e=isi(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 hgn(t){let e=CVe("fd",t.fdPath);if(e===null){t.onNotice("fd is required for profile file search");return}let n=CVe("fzf");if(n===null){t.onNotice("fzf is required for profile file search");return}let r=CVe("nvim");if(r===null){t.onNotice("Neovim is required for profile file search");return}let i=fsi(t.profileId),o=_Ve([t.cwd,...t.nodeDirs,...i.projects]);if(o.length===0){t.onNotice("No profile file-search directories exist");return}let s=msi(o),a=_Ve([...i.settings===null?[]:[i.settings]]),c=rsi(Ipe(ssi(),"crtr-profile-files-")),u=Ipe(c,"selection"),l=Ipe(c,"candidates"),d=dsi(t.nodes).filter(m=>!s.some(g=>m===g||m.startsWith(g+dgn))),f=`{ ${[...s.map(m=>`${an(e)} --type f --hidden --exclude .git . ${an(m)}`),...d.map(m=>`${an(e)} --type f --hidden --exclude .git --exclude ${an("/jobs")} . ${an(m)}`),...a.map(m=>`${an(e)} --type f --hidden --exclude .git --no-ignore . ${an(m)}`)].map(m=>`${m} &`).join(" ")} wait; } > ${an(l)} && ${an(n)} --print0 --scheme=path --hscroll-off=${gsi} --header ${an("fuzzy path \u2022 ctrl-y yank file path")} --bind ${an("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 ${an("head -100 -- {}")} < ${an(l)} > ${an(u)}`;try{lgn("tmux",["display-popup","-E","-T"," profile files ","-w","80%","-h","60%",...Hd(),f],()=>{let m=ysi(u);if(m===null||!nsi(m)){_pe(c,{recursive:!0,force:!0});return}let g=`exec ${XT("edit",[m],r)}`;try{lgn("tmux",["display-popup","-E","-T"," profile file ","-w","90%","-h","90%",...Hd(),g],()=>_pe(c,{recursive:!0,force:!0}))}catch(A){_pe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file: ${A instanceof Error?A.message:String(A)}`)}})}catch(m){_pe(c,{recursive:!0,force:!0}),t.onNotice(`Could not open profile file search: ${m instanceof Error?m.message:String(m)}`)}}var mgn={statuses:{},widgets:{},title:void 0};function ggn(t="observer"){return{role:t,agentDir:void 0,engine:void 0,contextTokens:void 0,queued:[],display:mgn,dialog:null}}function Asi(t){let e=t.snapshot,n=e.display??mgn,r=e.stats.contextUsage;return{role:t.role,agentDir:t.agentDir,engine:e.state,contextTokens:r?.tokens??void 0,queued:xsi(e),display:{statuses:{...n.statuses},widgets:Object.fromEntries(Object.entries(n.widgets).map(([i,o])=>[i,{lines:[...o.lines],placement:o.placement}])),title:n.title},dialog:t.pending_dialog??null}}function ygn(t,e){switch(e.type){case"welcome":return Asi(e);case"model_changed":return jN(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 r={...t.display.statuses};return delete r[e.statusKey],e.statusText!==void 0&&(r[e.statusKey]=e.statusText),{...t,display:{...t.display,statuses:r}}}case"setWidget":{let n=e.widgetLines===void 0?void 0:{lines:[...e.widgetLines],placement:e.widgetPlacement??"aboveEditor"};if(bsi(t.display.widgets[e.widgetKey],n))return t;let r={...t.display.widgets};return delete r[e.widgetKey],n!==void 0&&(r[e.widgetKey]=n),{...t,display:{...t.display,widgets:r}}}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:wsi(t,e.message.usage.input+e.message.usage.cacheRead+e.message.usage.cacheWrite);case"agent_start":return jN(t,{isStreaming:!0});case"agent_end":case"agent_settled":return jN(t,{isStreaming:!1});case"session_info_changed":return jN(t,{sessionName:e.name});case"thinking_level_changed":return jN(t,{thinkingLevel:e.level});case"queue_update":{let n=[...e.steering,...e.followUp].map(i=>({text:i}));return{...jN(t,{pendingMessageCount:n.length}),queued:n}}default:return t}}function xsi(t){let e=t.queued;if(typeof e!="object"||e===null)return[];let{steering:n,followUp:r}=e;return[...fgn(n),...fgn(r)].map(i=>({text:i}))}function fgn(t){return Array.isArray(t)?t.filter(e=>typeof e=="string"):[]}function jN(t,e){let n=t.engine;if(n===void 0)return t;let r=!1;for(let[i,o]of Object.entries(e))if(n[i]!==o){r=!0;break}return r?{...t,engine:{...n,...e}}:t}function wsi(t,e){return t.contextTokens===e?t:{...t,contextTokens:e}}function bsi(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,r)=>n===e.lines[r])}function Agn(t,e){let n=ggn(t),r=i=>{let o=n;if(o===i)return;let s=o.engine!==i.engine;s&&o.engine!==void 0&&(e.setEngineState(o.engine),e.setEditorTitle(o.engine.sessionName)),s&&e.paintEditorFrame(),o.display.widgets!==i.display.widgets&&e.renderExtensionWidgets(),o.display.title!==i.display.title&&o.display.title!==void 0&&e.setTerminalTitle(o.display.title),o.queued!==i.queued&&e.renderQueued(),(s||o.role!==i.role||o.contextTokens!==i.contextTokens||o.display.statuses!==i.display.statuses)&&e.renderFooter(),s&&e.refreshChrome()};return{state:()=>n,fold:i=>{let o=n;n=ygn(n,i),r(o)},patchLocal:i=>{let o=n.engine;if(o===void 0)return;let s=n;n={...n,engine:{...o,...i}},r(s)},modelThinkingLabel:()=>{let i=n.engine?.model?.id;if(i===void 0)return;let o=n.engine?.thinkingLevel;return o!==void 0&&o!=="off"?`${i} ${o}`:i}}}tt();import{spawn as vsi}from"node:child_process";import{fileURLToPath as IVe}from"node:url";var Esi=40,xgn=[IVe(new URL("./assets/whip-snap.mp3",import.meta.url)),IVe(new URL("./assets/whip-crack.mp3",import.meta.url)),IVe(new URL("./assets/whip-06.mp3",import.meta.url))];function Ssi(t){let e=process.platform==="darwin"?"afplay":process.platform==="linux"?"aplay":void 0;if(e!==void 0)try{let n=vsi(e,[t],{stdio:"ignore",detached:!0});n.on("error",()=>{}),n.unref()}catch{}}var wgn=[["","","","","","","","\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",""]],vgn="Go faster",bgn;function Egn(t){let e=t.filter(r=>r!==bgn),n=e[Math.floor(Math.random()*e.length)];return bgn=n,n}var kpe=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;frame=-1;nextSound=0;timer;play(){this.stop(),Ssi(xgn[this.nextSound]),this.nextSound=(this.nextSound+1)%xgn.length,this.frame=0,this.tui.requestRender(),this.timer=setInterval(()=>{if(this.frame++,this.frame<wgn.length){this.tui.requestRender();return}this.stop()},Esi)}dispose(){this.stop()}render(e){if(this.frame<0)return[];let n=Math.max(0,e);return wgn[this.frame].map(r=>ot(this.pal.accent(r),n,"",!0))}invalidate(){}stop(){this.timer!==void 0&&clearInterval(this.timer),this.timer=void 0,this.frame=-1,this.tui.requestRender()}};wS();import{execFile as Csi}from"node:child_process";import{mkdirSync as Sgn,readFileSync as _si,renameSync as Isi,writeFileSync as Cgn}from"node:fs";import{dirname as _gn,join as kVe}from"node:path";var ksi="whip-count.json",Tsi=kVe("tmp","whip-achievement.txt"),Ign=46,Rsi=4,Msi=900,Psi=[{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 Dsi(t){let e={total:0,unlocked:[]};try{let n=JSON.parse(_si(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;let{total:r,firstAt:i,lastAt:o,unlocked:s}=n,a={total:typeof r=="number"&&Number.isFinite(r)&&r>0?Math.floor(r):0,unlocked:Array.isArray(s)?s.filter(c=>typeof c=="number"&&Number.isFinite(c)):[]};return typeof i=="number"&&Number.isFinite(i)&&(a.firstAt=i),typeof o=="number"&&Number.isFinite(o)&&(a.lastAt=o),a}catch{return e}}function Bsi(t,e){try{Sgn(_gn(t),{recursive:!0});let n=`${t}.${process.pid}.tmp`;Cgn(n,JSON.stringify(e),"utf8"),Isi(n,t)}catch{}}function Tpe(t){let e=Math.max(0,Math.floor((Ign-Rd(t))/2));return" ".repeat(e)+t}function Lsi(t,e,n){return["",Tpe(n.accent(n.bold("\u2605 ACHIEVEMENT UNLOCKED \u2605"))),"",Tpe(n.bold(t.title)),Tpe(n.muted(t.line)),"",Tpe(n.faint(`${e} whip${e===1?"":"s"}`))]}function Osi(t,e,n){if(process.env.TMUX===void 0||process.env.TMUX==="")return;let r=Lsi(t,e,n),i=kVe(Qd(),Tsi);try{Sgn(_gn(i),{recursive:!0}),Cgn(i,`\x1B[?25l${r.join(`\r
|
|
1746
|
-
`)}`,"utf8")}catch{return}let o=`cat ${an(i)}; sleep ${Rsi}`;Csi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Ign+2),"-h",String(r.length+2),...Hd(),o],()=>{})}function kgn(t,e=kVe(Qd(),ksi)){let n=Dsi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=Psi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),Bsi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>Osi(i,o,t),Msi).unref?.()}function Tgn(t){return/^[A-Za-z0-9._:@/-]+$/.test(t)?t:an(t)}async function YWs(t,e,n,r=!0){await Fmn(),LT("viewer.connect_start",{node:t});let i=await jmn(t,n,r);LT(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=Gmn(e),l=Nsi();ron({cwd:a.cwd});let d=ion(),p=Xin(),h=Hx(),f=h.bindings;await eon(p);let m=await non(),g=new rw,A=new $A(g),b=new et,v=new bde,S=new dde(A,b,{cwd:a.cwd,palette:d,hideThinking:!0,banner:Hrt(qmn(a)),inlinePageBlocks:!o,pageOpenHint:()=>wR(f),backgroundBashHint:()=>o||!Ps()?null:Cz(f),onActivityChange:Ye=>{v.clear(),Ye&&v.addChild(Ye)}}),_=S.transcriptSource(),I=Udn(_),R=Ndn(_,I.decorate),D=opn(S,R,_),B,L=tmn({tui:A,pal:d},()=>B.state()),F=epn(A,d,R,I,{bindings:()=>f,setNotice:Ye=>V(Ye)}),q=ign(g,A,b,v,d,p,R,F.component),{containers:j,editor:Q}=q,he=new kpe(A,d);j.header.addChild(he),j.header.addChild(L.component);let K={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:A,pal:d,editor:Q,containers:j},Te=Ufn(K,{syncCursor:()=>Pn.sync(),exitRoster:()=>Mn.exit(),openTicket:Ye=>{W.open(Ye)},suppressed:()=>W.active(),setNotice:Ye=>V(Ye),onRefreshFailure:Ye=>At.reportFailure("inbox strip refresh",Ye)});j.header.addChild(Te.component);let Fe=Il("user"),Ze=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let Ct=lfn(),en=process.env.CRTR_ATTACH_OPEN_TICKET;en!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let Be=Smn(Ye=>process.stdout.write(Ye),Fe.mouse_mode_default),X=_mn({frame:()=>q.frame.lastRenderedFrame(),width:()=>A.terminal.columns});q.frame.setOverlay(Ye=>X.apply(Ye));let Ue=Zfn(K,{state:()=>B.state(),bashMode:()=>yt.bashMode(),asks:()=>At.asks(),bindings:()=>f,inboxAffordance:!o&&Ps(),mouseEnabled:()=>Be.enabled()}),Ke=new fpe({tui:A,mouse:Be,rows:()=>A.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Ye=>d.warning(`\u26A0 ${Ye}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Qt=(()=>{let Ye=a.profile_id;if(Ye)try{return{id:Ye,label:Qx(Ye).manifest.name}}catch{return{id:Ye,label:Ye}}})(),Nt=$mn({host:Ke,...Qt===void 0?{}:{profile:Qt},...o?{}:{scan:async()=>{let Ye=Pt(),[ar,ki]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(t,{state:"pending"})]),Ru=new Map;for(let js of ar.tickets){let Md=zm(js);Ru.set(Md.dir,Md)}for(let js of ki.tickets){let Md=zm(js);Md.kind!=="page"||Md.state!=="pending"||!Md.awaitsResponse||Md.inbox||Ru.has(Md.dir)||Ru.set(Md.dir,Md)}for(let js of Te.pendingTickets())Ru.has(js.dir)||Ru.set(js.dir,js);return[...Ru.values()].sort(BE)}}}),rn=o?()=>{}:QN(()=>{S.refreshPageBlocks(),Te.refresh()}),W=Yfn(K,{syncCursor:()=>Pn.sync(),refreshStrip:()=>{Te.refresh()},setNotice:Ye=>V(Ye),openInbox:Ye=>Nt.open(Ye),suspendForChild:()=>Ke.suspendForChild()});j.ticketPanel.addChild(W.component);let G={toggleInbox:()=>{let Ye=W.currentDir();if(Ye!==void 0){W.close(),Nt.open(Ye);return}Nt.toggle()}},V=(Ye,ar)=>{Ke.hasFullPaneSurface()?Ke.notice(Ye,ar):Ue.setNotice(Ye,ar)},ve=Ue.render,ue=Ye=>{V(D.copy(Ye))},we=npn(R,()=>A.requestRender()),De={"crtr.attach.scroll.up":()=>{we.cancel(),R.scrollBy(-1)&&A.requestRender()},"crtr.attach.scroll.down":()=>{we.cancel(),R.scrollBy(1)&&A.requestRender()},"crtr.attach.scroll.page-up":()=>{we.page("up")},"crtr.attach.scroll.page-down":()=>{we.page("down")},"crtr.attach.scroll.live":()=>{we.cancel(),R.goLive(),A.requestRender()},"crtr.attach.mouse.toggle":()=>{let Ye=Be.toggle();!Ye&&X.clear()&&A.requestRender(),V(Ye?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ue("message"),"crtr.attach.verbosity.less":()=>V(eVe(S.lessDetail()))},ce,Ae=Cfn(K,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),Me=zmn(),Ce=ogn(K,Ae,{setNotice:V,bindings:()=>f,fdPath:m,frecency:Me}),ze=sgn(K,i.nodeIdentity,{isTornDown:()=>ci.isTornDown(),onChanged:()=>{yt.syncContextBadge();let Ye=B.state().engine;Ye!==void 0&&yt.setTitle(Ye.sessionName),A.requestRender()}});o&&ze.refresh();let yt=egn(K,{nodeIdentity:ze.current,thinkingLevel:()=>B.state().engine?.thinkingLevel,renderFooter:ve,onTextChange:Ce.syncCommandPreview});yt.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:er}=emn(K,()=>B.state());B=Agn(u,{setEngineState:Ye=>Lt.setState(Ye),setEditorTitle:yt.setTitle,paintEditorFrame:yt.paintFrame,renderExtensionWidgets:()=>{L.render(),st()},renderQueued:er,renderFooter:ve,setTerminalTitle:Ye=>g.setTitle(Ye),refreshChrome:()=>At.refresh()});let $n=Ye=>{if(!Ps()){V("Inspector requires tmux");return}V(`Opening Inspector (${Ye})\u2026`);let ar=mA(),Ru=`${ar===void 0?"":`CRTR_HOME=${an(ar)} `}crtr surface inspect ${an(t)} --section ${Ye}`;$si("tmux",["display-popup","-E","-T",` inspector \xB7 ${Ye} `,"-w","90%","-h","85%",...Hd(),Ru],()=>{At.refresh()})},Mn=Ffn(K,{asks:()=>At.asks(),setNotice:V,requestChromeRefresh:()=>At.refresh(),openInspector:$n,openObject:Ye=>{if(!Ps()){V("Object details require tmux");return}V("Opening object\u2026");let ar=mA(),ki=ar===void 0?"":`CRTR_HOME=${an(ar)} `;Xz({name:Ye,produce:Ru=>`${ki}crtr canvas read ${an(Ye)} > ${Ru} 2>&1`,title:`object \xB7 ${Ye}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>At.refresh()})},syncCursor:()=>Pn.sync()}),Pn=Jfn(Q,[Mn.active,Te.active,W.active]),Vr=new lpe(A,t,()=>At.asks(),d,f,s,u,Ye=>At.reportFailure("canvas graph refresh",Ye),V),wa=new dpe(A,d);wa.setBindings(f);let At=nmn(K,{isTornDown:()=>ci.isTornDown(),setNotice:V,refreshRoster:async()=>{await Mn.refresh(),await Te.refresh()},refreshGraph:()=>Vr.refresh(),refreshIdentity:()=>ze.refresh(),renderFooter:ve,renderExtensionWidgets:st,refreshInFlightTools:()=>S.refreshInFlightTools(),pollGit:yt.pollGit}),Lt=_fn(K,p,Ae,{setNotice:V,agentDir:()=>B.state().agentDir,openNodeMetadata:()=>$n("overview"),isDormant:()=>ce.isDormant(),copyTarget:ue,moreDetail:()=>S.moreDetail(),lessDetail:()=>S.lessDetail(),toggleThinking:()=>S.toggleThinking(),toggleGraph:()=>Vr.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>wa.toggle(),toggleMouse:()=>Be.toggle(),quit:()=>Ms("detach"),setChipColor:yt.setChipColor,onPromptSent:()=>{Fe.whip_mode&&he.play()},frecency:Me}),ne=()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let Ye=Fe.whip_message_mode==="go-faster"?vgn:Egn(Fe.whip_messages);Lt.sendInterrupting(Ye)&&(he.play(),kgn(d),V(`Whipped agent \u2014 ${Ye}`))},se=Mmn({selfNodeId:t,remote:o,canvasSource:s,port:Fe.document_port,fetchSecret:async()=>(await Pt().documents.browserAccess()).secret,onSecretError:Ye=>V(`Document links are unavailable: ${Ye instanceof Error?Ye.message:String(Ye)}`),refresh:()=>S.refreshMarkdown()}),be=()=>{if(W.active()){V("Close the open request first (Esc)");return}let Ye=[...S.getTranscriptDocRefsNewestFirst().map(ki=>`[[${ki}]]`),...S.getTranscriptFilePathsNewestFirst()],ar=ki=>{mfn(Ke,ki,{originNodeId:t,onNotice:V})};if(Ke.hasFullPaneSurface()){Ke.pickReviewFile({candidates:Ye,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(ki=>{ki!==null&&ar(ki)});return}Lt.openFileReviewPicker(Ye,a.cwd,ar)},Qe=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!Ps()){V("Profile file search requires tmux");return}s.listNodes().then(Ye=>{let ar=pgn(Ye,t);hgn({cwd:a.cwd,nodeDirs:ar.map(ki=>ki.cwd),nodes:ar,profileId:a.profile_id??null,fdPath:m,onNotice:V})}).catch(Ye=>{let ar=Ye instanceof Error?Ye.message:String(Ye);V(`Could not load related node directories: ${ar}`)})},Re,Xe=()=>{Re!==void 0&&clearTimeout(Re),Re=setTimeout(()=>{Re=void 0,l6e(()=>h,()=>{},Ps,Jz)},1e3),Re.unref()},bt=wmn(K,{foldState:B.fold,chat:S,setNotice:V,renderFooter:ve,setEditorText:Ye=>{Q.setText(Ye),A.requestRender()},attachDialog:Ye=>Lt.attachDialog(Ye),dismissDialog:Ye=>Lt.dismissDialog(Ye),refreshNodeIdentity:ze.refresh,setCommands:Ce.setCommands,resetMemoryRefs:Ce.resetMemoryRefs,reloadBindings:()=>{h=l6e(Hx,Ye=>{Vr.setBindings(Ye),wa.setBindings(Ye)},Ps,Jz),f=h.bindings},modelThinkingLabel:B.modelThinkingLabel,onWelcome:()=>Xe()}),Ut=Ye=>{let ar=Ye instanceof Error?`${Ye.name}: ${Ye.message}`:String(Ye);HE("attach.unhandled_rejection",ar),sVe(Ye)&&At.reportFailure("background daemon call",Ye)};process.on("unhandledRejection",Ut);let Dr=()=>{process.off("unhandledRejection",Ut)},Gr=cgn(o,t),ci=omn(K,{stopLocal:()=>{Re!==void 0&&clearTimeout(Re),Ke.closeAll(),we.cancel(),Be.disable(),At.stop(),W.close(),Ue.dispose(),Vr.close(),wa.close(),F.close(),he.dispose(),Gr.clear(),Ppe(),Mpe(),Rpe(),Dr(),se.dispose(),rn();try{S.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),reattachCommand:`crtr surface attach to ${Tgn(t)}`+(e?" --observer":"")+(n!==void 0?` --canvas ${Tgn(n)}`:""),tagPane:Gr.pane}),Ms=ci.teardown;ce=fmn(K,{role:u,remote:o,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:bt,setNotice:V,isTornDown:()=>ci.isTornDown(),teardown:Ms,onEnterDormancy:()=>{Xe(),S.settleRun(),B.patchLocal({isStreaming:!1})}}),i.assertConnected(),Gr.set(),ce.install(),q.mount(),A.start(),i.initialSnapshot!==void 0&&(B.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),S.applySnapshot(i.initialSnapshot),Ce.setCommands(i.initialCommands),o||Pt().markNodeRead(t).catch(()=>{})),Fe.whip_mode&&Ze&&he.play(),Be.reassert();let Ac=!1,kx=Ye=>{if(Ac)return;if(o){V("Opening a file is unavailable in a remote attach");return}let ar=ig();if(ar===null)return;let ki=Rmn({file:Ye,pane:ar.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:Gr.clear});if(ki==="opened"){Ac=!0;return}ki==="failed"&&Gr.set(),ki==="missing"&&V("File no longer exists"),ki==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),ki==="failed"&&V("Could not open file in Neovim")};Be.install(A,{onWheel:(Ye,ar)=>{X.clear()&&A.requestRender(),!Ke.handleWheel(Ye,ar)&&(we.cancel(),R.scrollBy(Ye==="up"?-ar:ar)&&A.requestRender())},onPrimaryPress:(Ye,ar)=>{Ke.hasFullPaneSurface()||(X.clear()&&A.requestRender(),X.begin(Ye,ar))},onPrimaryDrag:(Ye,ar)=>{Ke.hasFullPaneSurface()||X.extend(Ye,ar)&&A.requestRender()},onPrimaryRelease:()=>{let Ye=X.release();Ye?.kind==="selection"&&(V(Ye.notice),A.requestRender())}});let Rpe=A.addInputListener(Ye=>{let ar=Tmn(Ye);if(ar===void 0)return;let ki=ar.file;return ki===void 0?V("Could not open file link"):kx(ki),ar.remaining.length>0?{data:ar.remaining}:{consume:!0}}),Mpe=A.addInputListener(()=>{X.clear()&&A.requestRender()}),Ppe=bmn(K,{bindings:()=>f,detachHint:()=>Jdn(f),hasExclusiveSurface:()=>Ke.hasFullPaneSurface(),setPaneFocused:Ye=>{Ye&&Gr.stamp(),Pn.setPaneFocused(Ye),A.requestRender()},viewportActions:()=>De,searchHandleKey:F.handleKey,panelHandleKey:W.handleKey,stripHandleKey:Te.handleKey,rosterHandleKey:Mn.handleKey,setNotice:V,detach:()=>Ms("detach"),cancelTurn:()=>{Lt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${Xdn(f)??"ctrl+d"} to detach`)},toggleGraph:()=>Vr.toggle(),toggleHelp:()=>wa.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}W.active()&&W.close(),Te.toggle()},cycleModelLadder:Ye=>Lt.cycleLadder(Ye),inspectLoadedCommand:Ce.inspectLoadedCommand,openFileReview:be,openProfileFiles:Qe,openSearch:()=>{if(Ke.hasFullPaneSurface()||W.active()){V("Close the active surface before searching the transcript");return}F.open()},whip:ne});ci.installSignalHandlers(),ve(),At.refresh(),er(),yt.pollGit(),LT("viewer.first_paint"),process.stdout.write(rmn),ton(g.kittyProtocolActive),i.initialSnapshot!==void 0&&Xe(),i.initialSnapshot===void 0?(LT("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),At.start(),Ct!==void 0&&dfn(Ke,Ct),en!==void 0&&en!==""&&!o&&(async()=>{let Ye=Pt(),[ar,ki]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(void 0,{state:"pending"})]),Ru=[...ar.tickets,...ki.tickets].map(zm).find(js=>js.inboxTicketId===en&&(js.kind!=="page"||js.state==="pending"));Ru===void 0?V("ask already answered"):W.open(Ru)})().catch(Ye=>V(`could not open the ask: ${String(Ye?.message??Ye)}`)),await ci.done}export{YWs as runAttach};
|
|
1746
|
+
`)}`,"utf8")}catch{return}let o=`cat ${an(i)}; sleep ${Rsi}`;Csi("tmux",["display-popup","-E","-k","-x","R","-y","0","-w",String(Ign+2),"-h",String(r.length+2),...Hd(),o],()=>{})}function kgn(t,e=kVe(Qd(),ksi)){let n=Dsi(e),r=Date.now();n.total+=1,n.firstAt??=r,n.lastAt=r;let i=Psi.find(a=>a.at===n.total&&!n.unlocked.includes(a.at));if(i!==void 0&&n.unlocked.push(i.at),Bsi(e,n),i===void 0)return;let o=n.total;setTimeout(()=>Osi(i,o,t),Msi).unref?.()}function Tgn(t){return/^[A-Za-z0-9._:@/-]+$/.test(t)?t:an(t)}async function YWs(t,e,n,r=!0){await Fmn(),LT("viewer.connect_start",{node:t});let i=await jmn(t,n,r);LT(i.initialSnapshot===void 0?"viewer.socket_connected":"viewer.offline_snapshot_ready");let{remote:o,canvasSource:s,meta:a,socket:c}=i,u=Gmn(e),l=Nsi();ron({cwd:a.cwd});let d=ion(),p=Xin(),h=Hx(),f=h.bindings;await eon(p);let m=await non(),g=new rw,A=new $A(g),b=new et,v=new bde,S=new dde(A,b,{cwd:a.cwd,palette:d,hideThinking:!0,banner:Hrt(qmn(a)),inlinePageBlocks:!o,pageOpenHint:()=>wR(f),backgroundBashHint:()=>o||!Ps()?null:Cz(f),onActivityChange:Ye=>{v.clear(),Ye&&v.addChild(Ye)}}),_=S.transcriptSource(),I=Udn(_),R=Ndn(_,I.decorate),D=opn(S,R,_),B,L=tmn({tui:A,pal:d},()=>B.state()),F=epn(A,d,R,I,{bindings:()=>f,setNotice:Ye=>V(Ye)}),q=ign(g,A,b,v,d,p,R,F.component),{containers:j,editor:Q}=q,he=new kpe(A,d);j.header.addChild(he),j.header.addChild(L.component);let K={nodeId:t,remote:o,role:u,meta:a,canvasSource:s,socket:c,tui:A,pal:d,editor:Q,containers:j},Te=Ufn(K,{syncCursor:()=>Pn.sync(),exitRoster:()=>Mn.exit(),openTicket:Ye=>{W.open(Ye)},suppressed:()=>W.active(),setNotice:Ye=>V(Ye),onRefreshFailure:Ye=>At.reportFailure("inbox strip refresh",Ye)});j.header.addChild(Te.component);let Fe=Il("user"),Ze=process.env.CRTR_ATTACH_INITIAL_WHIP==="1";delete process.env.CRTR_ATTACH_INITIAL_WHIP;let Ct=lfn(),en=process.env.CRTR_ATTACH_OPEN_TICKET;en!==void 0&&delete process.env.CRTR_ATTACH_OPEN_TICKET;let Be=Smn(Ye=>process.stdout.write(Ye),Fe.mouse_mode_default),X=_mn({frame:()=>q.frame.lastRenderedFrame(),width:()=>A.terminal.columns});q.frame.setOverlay(Ye=>X.apply(Ye));let Ue=Zfn(K,{state:()=>B.state(),bashMode:()=>yt.bashMode(),asks:()=>At.asks(),bindings:()=>f,inboxAffordance:!o&&Ps(),mouseEnabled:()=>Be.enabled()}),Ke=new fpe({tui:A,mouse:Be,rows:()=>A.terminal.rows,statusNotice:Ue.setNotice,formatNotice:Ye=>d.warning(`\u26A0 ${Ye}`),noticeMs:3e3,capabilities:{remote:o,canFocusNode:!o&&process.env.TMUX_PANE!==void 0},selfPane:process.env.TMUX_PANE}),Qt=(()=>{let Ye=a.profile_id;if(Ye)try{return{id:Ye,label:Qx(Ye).manifest.name}}catch{return{id:Ye,label:Ye}}})(),Nt=$mn({host:Ke,...Qt===void 0?{}:{profile:Qt},...o?{}:{scan:async()=>{let Ye=Pt(),[ar,ki]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(t,{state:"pending"})]),Ru=new Map;for(let js of ar.tickets){let Md=zm(js);Ru.set(Md.dir,Md)}for(let js of ki.tickets){let Md=zm(js);Md.kind!=="page"||Md.state!=="pending"||!Md.awaitsResponse||Md.inbox||Ru.has(Md.dir)||Ru.set(Md.dir,Md)}for(let js of Te.pendingTickets())Ru.has(js.dir)||Ru.set(js.dir,js);return[...Ru.values()].sort(BE)}}}),rn=o?()=>{}:QN(()=>{S.refreshPageBlocks(),Te.refresh()}),W=Yfn(K,{syncCursor:()=>Pn.sync(),refreshStrip:()=>{Te.refresh()},setNotice:Ye=>V(Ye),openInbox:Ye=>Nt.open(Ye),suspendForChild:()=>Ke.suspendForChild()});j.ticketPanel.addChild(W.component);let G={toggleInbox:()=>{let Ye=W.currentDir();if(Ye!==void 0){W.close(),Nt.open(Ye);return}Nt.toggle()}},V=(Ye,ar)=>{Ke.hasFullPaneSurface()?Ke.notice(Ye,ar):Ue.setNotice(Ye,ar)},ve=Ue.render,ue=Ye=>{V(D.copy(Ye))},we=npn(R,()=>A.requestRender()),De={"crtr.attach.scroll.up":()=>{we.cancel(),R.scrollBy(-1)&&A.requestRender()},"crtr.attach.scroll.down":()=>{we.cancel(),R.scrollBy(1)&&A.requestRender()},"crtr.attach.scroll.page-up":()=>{we.page("up")},"crtr.attach.scroll.page-down":()=>{we.page("down")},"crtr.attach.scroll.live":()=>{we.cancel(),R.goLive(),A.requestRender()},"crtr.attach.mouse.toggle":()=>{let Ye=Be.toggle();!Ye&&X.clear()&&A.requestRender(),V(Ye?"Mouse: wheel scrolling on, drag to select and copy":"Mouse: off \u2014 tmux drag-select and copy-mode restored")},"crtr.attach.copy.message":()=>ue("message"),"crtr.attach.verbosity.less":()=>V(eVe(S.lessDetail()))},ce,Ae=Cfn(K,()=>ce===void 0?i.initialSnapshot!==void 0:ce.isDormant()),Me=zmn(),Ce=ogn(K,Ae,{setNotice:V,bindings:()=>f,fdPath:m,frecency:Me}),ze=sgn(K,i.nodeIdentity,{isTornDown:()=>ci.isTornDown(),onChanged:()=>{yt.syncContextBadge();let Ye=B.state().engine;Ye!==void 0&&yt.setTitle(Ye.sessionName),A.requestRender()}});o&&ze.refresh();let yt=egn(K,{nodeIdentity:ze.current,thinkingLevel:()=>B.state().engine?.thinkingLevel,renderFooter:ve,onTextChange:Ce.syncCommandPreview});yt.syncContextBadge();let{renderExtensionWidgets:st,renderQueued:er}=emn(K,()=>B.state());B=Agn(u,{setEngineState:Ye=>Lt.setState(Ye),setEditorTitle:yt.setTitle,paintEditorFrame:yt.paintFrame,renderExtensionWidgets:()=>{L.render(),st()},renderQueued:er,renderFooter:ve,setTerminalTitle:Ye=>g.setTitle(Ye),refreshChrome:()=>At.refresh()});let $n=Ye=>{if(!Ps()){V("Inspector requires tmux");return}V(`Opening Inspector (${Ye})\u2026`);let ar=mA(),Ru=`${ar===void 0?"":`CRTR_HOME=${an(ar)} `}crtr surface inspect ${an(t)} --section ${Ye}`;$si("tmux",["display-popup","-E","-T",` inspector \xB7 ${Ye} `,"-w","90%","-h","85%",...Hd(),Ru],()=>{At.refresh()})},Mn=Ffn(K,{asks:()=>At.asks(),setNotice:V,requestChromeRefresh:()=>At.refresh(),openInspector:$n,openObject:Ye=>{if(!Ps()){V("Object details require tmux");return}V("Opening object\u2026");let ar=mA(),ki=ar===void 0?"":`CRTR_HOME=${an(ar)} `;Xz({name:Ye,produce:Ru=>`${ki}crtr canvas read ${an(Ye)} > ${Ru} 2>&1`,title:`object \xB7 ${Ye}`,noNvim:"nvim is required to view the object. Install Neovim and retry.",onClose:()=>At.refresh()})},syncCursor:()=>Pn.sync()}),Pn=Jfn(Q,[Mn.active,Te.active,W.active]),Vr=new lpe(A,t,()=>At.asks(),d,f,s,u,Ye=>At.reportFailure("canvas graph refresh",Ye),V),wa=new dpe(A,d);wa.setBindings(f);let At=nmn(K,{isTornDown:()=>ci.isTornDown(),setNotice:V,refreshRoster:async()=>{await Mn.refresh(),await Te.refresh()},refreshGraph:()=>Vr.refresh(),refreshIdentity:()=>ze.refresh(),renderFooter:ve,renderExtensionWidgets:st,refreshInFlightTools:()=>S.refreshInFlightTools(),pollGit:yt.pollGit}),Lt=_fn(K,p,Ae,{setNotice:V,agentDir:()=>B.state().agentDir,openNodeMetadata:()=>$n("overview"),isDormant:()=>ce.isDormant(),copyTarget:ue,moreDetail:()=>S.moreDetail(),lessDetail:()=>S.lessDetail(),toggleThinking:()=>S.toggleThinking(),toggleGraph:()=>Vr.toggle(),toggleInbox:G.toggleInbox,toggleHelp:()=>wa.toggle(),toggleMouse:()=>Be.toggle(),quit:()=>Ms("detach"),setChipColor:yt.setChipColor,onPromptSent:()=>{Fe.whip_mode&&he.play()},frecency:Me}),ne=()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before whipping the agent");return}let Ye=Fe.whip_message_mode==="go-faster"?vgn:Egn(Fe.whip_messages);Lt.sendInterrupting(Ye)&&(he.play(),kgn(d),V(`Whipped agent \u2014 ${Ye}`))},se=Mmn({selfNodeId:t,remote:o,canvasSource:s,port:Fe.document_port,fetchAccess:async()=>await Pt().documents.browserAccess(),onAccessError:Ye=>V(`Document links are unavailable: ${Ye instanceof Error?Ye.message:String(Ye)}`),refresh:()=>S.refreshMarkdown()}),be=()=>{if(W.active()){V("Close the open request first (Esc)");return}let Ye=[...S.getTranscriptDocRefsNewestFirst().map(ki=>`[[${ki}]]`),...S.getTranscriptFilePathsNewestFirst()],ar=ki=>{mfn(Ke,ki,{originNodeId:t,onNotice:V})};if(Ke.hasFullPaneSurface()){Ke.pickReviewFile({candidates:Ye,cwd:a.cwd,title:"Review a file or document named in this transcript"}).then(ki=>{ki!==null&&ar(ki)});return}Lt.openFileReviewPicker(Ye,a.cwd,ar)},Qe=()=>{if(o){V("Profile file search is unavailable on remote canvases");return}if(!Ps()){V("Profile file search requires tmux");return}s.listNodes().then(Ye=>{let ar=pgn(Ye,t);hgn({cwd:a.cwd,nodeDirs:ar.map(ki=>ki.cwd),nodes:ar,profileId:a.profile_id??null,fdPath:m,onNotice:V})}).catch(Ye=>{let ar=Ye instanceof Error?Ye.message:String(Ye);V(`Could not load related node directories: ${ar}`)})},Re,Xe=()=>{Re!==void 0&&clearTimeout(Re),Re=setTimeout(()=>{Re=void 0,l6e(()=>h,()=>{},Ps,Jz)},1e3),Re.unref()},bt=wmn(K,{foldState:B.fold,chat:S,setNotice:V,renderFooter:ve,setEditorText:Ye=>{Q.setText(Ye),A.requestRender()},attachDialog:Ye=>Lt.attachDialog(Ye),dismissDialog:Ye=>Lt.dismissDialog(Ye),refreshNodeIdentity:ze.refresh,setCommands:Ce.setCommands,resetMemoryRefs:Ce.resetMemoryRefs,reloadBindings:()=>{h=l6e(Hx,Ye=>{Vr.setBindings(Ye),wa.setBindings(Ye)},Ps,Jz),f=h.bindings},modelThinkingLabel:B.modelThinkingLabel,onWelcome:()=>Xe()}),Ut=Ye=>{let ar=Ye instanceof Error?`${Ye.name}: ${Ye.message}`:String(Ye);HE("attach.unhandled_rejection",ar),sVe(Ye)&&At.reportFailure("background daemon call",Ye)};process.on("unhandledRejection",Ut);let Dr=()=>{process.off("unhandledRejection",Ut)},Gr=cgn(o,t),ci=omn(K,{stopLocal:()=>{Re!==void 0&&clearTimeout(Re),Ke.closeAll(),we.cancel(),Be.disable(),At.stop(),W.close(),Ue.dispose(),Vr.close(),wa.close(),F.close(),he.dispose(),Gr.clear(),Ppe(),Mpe(),Rpe(),Dr(),se.dispose(),rn();try{S.dispose()}catch{}},lastSocketError:()=>ce.lastSocketError(),reattachCommand:`crtr surface attach to ${Tgn(t)}`+(e?" --observer":"")+(n!==void 0?` --canvas ${Tgn(n)}`:""),tagPane:Gr.pane}),Ms=ci.teardown;ce=fmn(K,{role:u,remote:o,initialDormant:i.initialSnapshot!==void 0,clientId:l,onFrame:bt,setNotice:V,isTornDown:()=>ci.isTornDown(),teardown:Ms,onEnterDormancy:()=>{Xe(),S.settleRun(),B.patchLocal({isStreaming:!1})}}),i.assertConnected(),Gr.set(),ce.install(),q.mount(),A.start(),i.initialSnapshot!==void 0&&(B.fold({type:"welcome",snapshot:i.initialSnapshot,role:u}),S.applySnapshot(i.initialSnapshot),Ce.setCommands(i.initialCommands),o||Pt().markNodeRead(t).catch(()=>{})),Fe.whip_mode&&Ze&&he.play(),Be.reassert();let Ac=!1,kx=Ye=>{if(Ac)return;if(o){V("Opening a file is unavailable in a remote attach");return}let ar=ig();if(ar===null)return;let ki=Rmn({file:Ye,pane:ar.pane,cwd:a.cwd,nodeId:t,observer:e,beforeRespawn:Gr.clear});if(ki==="opened"){Ac=!0;return}ki==="failed"&&Gr.set(),ki==="missing"&&V("File no longer exists"),ki==="no_nvim"&&V("Neovim is required to open files \u2014 install it (brew install neovim / apt install neovim) and retry"),ki==="failed"&&V("Could not open file in Neovim")};Be.install(A,{onWheel:(Ye,ar)=>{X.clear()&&A.requestRender(),!Ke.handleWheel(Ye,ar)&&(we.cancel(),R.scrollBy(Ye==="up"?-ar:ar)&&A.requestRender())},onPrimaryPress:(Ye,ar)=>{Ke.hasFullPaneSurface()||(X.clear()&&A.requestRender(),X.begin(Ye,ar))},onPrimaryDrag:(Ye,ar)=>{Ke.hasFullPaneSurface()||X.extend(Ye,ar)&&A.requestRender()},onPrimaryRelease:()=>{let Ye=X.release();Ye?.kind==="selection"&&(V(Ye.notice),A.requestRender())}});let Rpe=A.addInputListener(Ye=>{let ar=Tmn(Ye);if(ar===void 0)return;let ki=ar.file;return ki===void 0?V("Could not open file link"):kx(ki),ar.remaining.length>0?{data:ar.remaining}:{consume:!0}}),Mpe=A.addInputListener(()=>{X.clear()&&A.requestRender()}),Ppe=bmn(K,{bindings:()=>f,detachHint:()=>Jdn(f),hasExclusiveSurface:()=>Ke.hasFullPaneSurface(),setPaneFocused:Ye=>{Ye&&Gr.stamp(),Pn.setPaneFocused(Ye),A.requestRender()},viewportActions:()=>De,searchHandleKey:F.handleKey,panelHandleKey:W.handleKey,stripHandleKey:Te.handleKey,rosterHandleKey:Mn.handleKey,setNotice:V,detach:()=>Ms("detach"),cancelTurn:()=>{Lt.abortTurn()?V("Canceling the agent\u2026"):V(`Nothing running to cancel \u2014 press ${Xdn(f)??"ctrl+d"} to detach`)},toggleGraph:()=>Vr.toggle(),toggleHelp:()=>wa.toggle(),toggleInbox:G.toggleInbox,toggleInboxStrip:()=>{if(Ke.hasFullPaneSurface()){V("Close the active surface before opening the request strip");return}W.active()&&W.close(),Te.toggle()},cycleModelLadder:Ye=>Lt.cycleLadder(Ye),inspectLoadedCommand:Ce.inspectLoadedCommand,openFileReview:be,openProfileFiles:Qe,openSearch:()=>{if(Ke.hasFullPaneSurface()||W.active()){V("Close the active surface before searching the transcript");return}F.open()},whip:ne});ci.installSignalHandlers(),ve(),At.refresh(),er(),yt.pollGit(),LT("viewer.first_paint"),process.stdout.write(rmn),ton(g.kittyProtocolActive),i.initialSnapshot!==void 0&&Xe(),i.initialSnapshot===void 0?(LT("viewer.hello_sent"),ce.sendHello()):ce.startDormant(),At.start(),Ct!==void 0&&dfn(Ke,Ct),en!==void 0&&en!==""&&!o&&(async()=>{let Ye=Pt(),[ar,ki]=await Promise.all([Ye.listHumanInbox(),Ye.getInboxHistory(void 0,{state:"pending"})]),Ru=[...ar.tickets,...ki.tickets].map(zm).find(js=>js.inboxTicketId===en&&(js.kind!=="page"||js.state==="pending"));Ru===void 0?V("ask already answered"):W.open(Ru)})().catch(Ye=>V(`could not open the ask: ${String(Ye?.message??Ye)}`)),await ci.done}export{YWs as runAttach};
|
|
1747
1747
|
/*! Bundled license information:
|
|
1748
1748
|
|
|
1749
1749
|
undici/lib/web/fetch/body.js:
|